Overview
Concrete resilient websocket base that connects to a Binance stream, reads messages into an async queue with automatic reconnection and exponential backoff, provided by the `ReconnectingWebsocket` class.
Description
The ReconnectingWebsocket is the foundation of all Binance gateway websocket connections. It manages a `WSListenerState` lifecycle (`INITIALISING` → `STREAMING` → `RECONNECTING` → `EXITING`), opens a `websockets` connection (optionally through an HTTPS proxy via `websockets_proxy`), and runs a background `_read_loop` that decompresses binary (gzip) payloads, parses JSON (preferring `orjson`), and pushes messages onto an `asyncio.Queue` capped at `MAX_QUEUE_SIZE` (100). On connection loss it retries up to `MAX_RECONNECTS` (5) with randomized exponential backoff capped at `MAX_RECONNECT_SECONDS` (60), then signals `BinanceWebsocketUnableToConnect`. Errors are surfaced to consumers as `{"e": "error", ...}` queue messages so a single bad stream does not crash the pipeline. Subclasses override `_before_connect`/`_after_connect` (e.g. listen-key fetch) — see Implementation:51bitquant_Ai_hedge_fund_crypto_KeepAliveWebsocket and Implementation:51bitquant_Ai_hedge_fund_crypto_WebsocketAPI.
Usage
- As a base class: subclass and override `_before_connect`/`_after_connect`/`_handle_message` for specialized streams (listen-key keepalive, request-response API).
- Direct market streams: instantiated by `BinanceSocketManager._get_socket()` for all public market data streams; consumers iterate with `async with socket as s: await s.recv()`.
Code Reference
Source Location
Signature
class ReconnectingWebsocket:
MAX_RECONNECTS = 5
MAX_RECONNECT_SECONDS = 60
MIN_RECONNECT_WAIT = 0.1
TIMEOUT = 10
NO_MESSAGE_RECONNECT_TIMEOUT = 60
MAX_QUEUE_SIZE = 100
def __init__(
self,
url: str,
path: Optional[str] = None,
prefix: str = "ws/",
is_binary: bool = False,
exit_coro=None,
https_proxy: Optional[str] = None,
**kwargs,
): ...
async def __aenter__(self): ...
async def __aexit__(self, exc_type, exc_val, exc_tb): ...
async def close(self): ...
async def connect(self): ...
async def recv(self): ...
async def _before_connect(self): ...
async def _after_connect(self): ...
def _handle_message(self, evt): ...
async def _read_loop(self): ...
async def _run_reconnect(self): ...
async def before_reconnect(self): ...
def _reconnect(self): ...
def _get_reconnect_wait(self, attempts: int) -> int: ...
Import
from src.gateway.binance.ws.reconnecting_websocket import ReconnectingWebsocket
I/O Contract
Inputs
| Name |
Type |
Required |
Description
|
| url |
str |
Yes |
Base websocket URL
|
| path |
str |
No |
Stream path appended to `url`+`prefix`
|
| prefix |
str |
No |
URL prefix, default `"ws/"`
|
| is_binary |
bool |
No |
Gzip-decompress payloads if `True`
|
| exit_coro |
Callable |
No |
Cleanup coroutine called with path on exit
|
| https_proxy |
str |
No |
HTTPS proxy URL (requires `websockets_proxy`)
|
Outputs
| Name |
Type |
Description
|
| recv() |
dict/None |
Next parsed JSON message from the queue (10s timeout)
|
| error messages |
dict |
`{"e":"error","type":...,"m":...}` enqueued on connection/parse errors
|
| ws_state |
WSListenerState |
Current lifecycle state
|
Usage Examples
Consume a Market Stream
import asyncio
from src.gateway.binance.ws.reconnecting_websocket import ReconnectingWebsocket
async def main():
ws = ReconnectingWebsocket(
url="wss://stream.binance.com:9443/",
path="btcusdt@trade",
)
async with ws:
while True:
msg = await ws.recv()
if msg and msg.get("e") != "error":
print("trade price:", msg["p"])
asyncio.run(main())
Related Pages
Implements Principle
Requires Environment
Page Connections
Double-click a node to navigate. Hold to expand connections.