binance-connector-typescript: Map websocket response

Hello

I start using the official typescript client and established a websocket connection. Everything works fine, but how can I get the corresponding response for my request?

E.g.

  • I call client.exchangeInfo()
  • the “message” callback of the client gets called with the response data

But: If I send several requests in parallel, it gets confusing.

  • I cannot set the id of the request, because it’s not typed on the opt parameter.
  • So the id gets set with a random value - which I don’t get back from the send call.

So how can I wait for the right response? Why is there no promise returned or something? Or at least the generated id of the request?

Here when an order is created (async_create_order), a unique ID is generated and included in the request. The ID is also used to store a future in the pending_requests dictionary. The WebSocket listener (listen_for_responses) checks incoming responses for these IDs and resolves the corresponding futures with the response data.

This approach allows you to handle responses for specific requests, even when multiple requests are sent in parallel.

import asyncio
import json
import uuid

# Existing imports and class definitions...

class BinanceSpotWebSocket:
    # Existing methods...

    def __init__(self, api_key, api_secret, is_testnet=False):
        # Existing initialization code...
        self.pending_requests = {}  # Dictionary to store pending requests

    # Other existing methods...

    async def async_create_order(self, ws, trade, api_key, api_secret):
        # Existing order creation code...
        request_id = str(uuid.uuid4())  # Generate a unique ID for the request
        trade['id'] = request_id  # Store the ID in the trade

        # Store a future in the pending_requests dictionary
        future = asyncio.get_event_loop().create_future()
        self.pending_requests[request_id] = future

        # Send the request with the ID
        # ...

        # Wait for the future to resolve with the response
        response = await future
        return response  # Process the response as needed

    async def listen_for_responses(self, ws, api_key, api_secret):
        while True:
            # Existing response listening code...
            response_data = json.loads(response)

            # Extract the ID from the response and resolve the corresponding future
            response_id = response_data.get("id")
            if response_id in self.pending_requests:
                future = self.pending_requests.pop(response_id)
                future.set_result(response_data)

            # Other existing code...

# Main execution code...

1 Like