Overview
Concrete tool for running asyncio websocket listeners in a background thread so synchronous code can consume Binance streams, provided by the `ThreadedApiManager` class.
Description
The ThreadedApiManager extends `threading.Thread`. On `run()` it drives an asyncio event loop with `socket_listener()`, which creates an `AsyncClient`, calls the overridable `_before_socket_listener_start` hook, and idles while `_running` and active sockets remain. start_listener runs a single socket as an async context manager, polling `recv()` with a 3-second timeout and dispatching each message to a sync or async `callback` based on `asyncio.iscoroutinefunction`. The `_socket_running` dict maps connection paths to liveness flags so sockets can be stopped individually. stop cleanly tears down the client (with a 5s timeout) and flags all sockets to stop. It is the base class for Implementation:51bitquant_Ai_hedge_fund_crypto_BinanceSocketManager (as `ThreadedWebsocketManager`) and Implementation:51bitquant_Ai_hedge_fund_crypto_DepthCache (as `ThreadedDepthCacheManager`).
Usage
- Synchronous live trading: subclass (or use `ThreadedWebsocketManager`/`ThreadedDepthCacheManager`) and call `start_*` methods with callbacks; the manager thread owns the asyncio loop.
- Custom threaded socket managers: subclass, override `_before_socket_listener_start` to set up an async manager (e.g. a `BinanceSocketManager`), and add `start_*` methods that build sockets and call `start_listener`.
Code Reference
Source Location
Signature
class ThreadedApiManager(threading.Thread):
def __init__(
self,
api_key: Optional[str] = None,
api_secret: Optional[str] = None,
requests_params: Optional[Dict[str, Any]] = None,
tld: str = "com",
testnet: bool = False,
session_params: Optional[Dict[str, Any]] = None,
https_proxy: Optional[str] = None,
_loop: Optional[asyncio.AbstractEventLoop] = None,
): ...
async def _before_socket_listener_start(self): ...
async def socket_listener(self): ...
async def start_listener(self, socket, path: str, callback): ...
def run(self): ...
def stop_socket(self, socket_name): ...
async def stop_client(self): ...
def stop(self): ...
Import
from src.gateway.binance.ws.threaded_stream import ThreadedApiManager
I/O Contract
Inputs
| Name |
Type |
Required |
Description
|
| api_key |
str |
No |
Binance API key
|
| api_secret |
str |
No |
Binance API secret
|
| requests_params |
dict |
No |
Extra request kwargs passed to `AsyncClient`
|
| tld |
str |
No |
Binance top-level domain, default `"com"`
|
| testnet |
bool |
No |
Use testnet endpoints
|
| session_params |
dict |
No |
aiohttp session params
|
| https_proxy |
str |
No |
HTTPS proxy URL
|
| _loop |
asyncio loop |
No |
Existing event loop to reuse
|
Outputs
| Name |
Type |
Description
|
| _client |
AsyncClient |
Created in the listener thread
|
| _socket_running |
Dict[str,bool] |
Active socket paths → liveness
|
| start_listener() |
coroutine |
Drives one socket, calling `callback(msg)` per message
|
Usage Examples
Threaded Trade Stream
from src.gateway.binance.ws.streams import ThreadedWebsocketManager
def on_trade(msg):
print(f"{msg['s']} {msg['p']} x{msg['q']}")
twm = ThreadedWebsocketManager(api_key="...", api_secret="...")
twm.start()
twm.start_trade_socket(on_trade, "BTCUSDT")
# ... from sync code ...
twm.stop_socket("btcusdt@trade") # stop one stream
twm.stop() # stop everything
Related Pages
Implements Principle
Requires Environment
Page Connections
Double-click a node to navigate. Hold to expand connections.