Overview
Concrete tool for Binance's WebSocket API — a request-response RPC layer over a websocket — correlating responses to requests by ID, provided by the `WebsocketAPI` class.
Description
The WebsocketAPI extends Implementation:51bitquant_Ai_hedge_fund_crypto_ReconnectingWebsocket. It maintains a `_responses` dict mapping a request `id` to an `asyncio.Future`. The overridden _handle_message routes each incoming JSON message to its future by `id`; if `status != 200` it sets a `BinanceAPIException` on the future, otherwise it sets the result. _ensure_ws_connection serializes connection (re)establishment with an `asyncio.Lock`, waiting/retrying until `STREAMING` state or `MAX_RECONNECTS`. request sends a JSON payload (via `json_dumps`, preferring `orjson`) and awaits the matching future with a `TIMEOUT`. On `__aexit__`, any pending futures are failed with `BinanceWebsocketUnableToConnect` before the underlying socket closes. This provides a lower-latency alternative to HTTP REST for order management.
Usage
- Order management over WS: used by the Binance `BaseClient` `ws_api`/`ws_future` connections to send authenticated trading requests and await responses synchronously per call.
- Direct RPC: instantiate, call `await ws.request(id, payload)` to issue any Binance WS-API method and receive its response (or a `BinanceAPIException`).
Code Reference
Source Location
Signature
class WebsocketAPI(ReconnectingWebsocket):
def __init__(self, url: str, tld: str = "com", testnet: bool = False): ...
def _handle_message(self, msg): ...
async def _ensure_ws_connection(self) -> None: ...
async def request(self, id: str, payload: dict) -> dict: ...
async def __aexit__(self, exc_type, exc_val, exc_tb): ...
Import
from src.gateway.binance.ws.websocket_api import WebsocketAPI
I/O Contract
Inputs
| Name |
Type |
Required |
Description
|
| url |
str |
Yes |
Binance WS-API endpoint URL
|
| tld |
str |
No |
Binance TLD, default `"com"`
|
| testnet |
bool |
No |
Use testnet endpoint
|
| id |
str |
Yes (request) |
Correlation ID matching the Binance request `id`
|
| payload |
dict |
Yes (request) |
WS-API method + params (JSON-serialized)
|
Outputs
| Name |
Type |
Description
|
| request() |
dict |
The `result` field of the matched response, or the whole response
|
| on error |
BinanceAPIException |
Raised (set on the future) when `status != 200`
|
| on timeout |
BinanceWebsocketUnableToConnect |
Raised when no response within `TIMEOUT`
|
Usage Examples
Send a WS-API Request
import asyncio
from src.gateway.binance.ws.websocket_api import WebsocketAPI
async def main():
api = WebsocketAPI(url="wss://ws-api.binance.com:443/ws-api/v3")
async with api:
# Ping the WS-API (no auth needed)
resp = await api.request(id="1", payload={"method": "ping"})
print(resp) # {"result": {}, "id": "1"}
asyncio.run(main())
Related Pages
Implements Principle
Requires Environment
Page Connections
Double-click a node to navigate. Hold to expand connections.