Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:51bitquant Ai hedge fund crypto BinanceSocketManager

From Leeroopedia
Knowledge Sources
Domains Crypto_Markets, Real_Time_Streaming
Last Updated 2026-10-28 14:00 GMT

Overview

Concrete tool for subscribing to Binance real-time market and user-data websocket streams (depth, kline, trade, ticker, mark price, multiplex, user) provided by the `BinanceSocketManager` and `ThreadedWebsocketManager` classes.

Description

The BinanceSocketManager is the central subscription interface for Binance websockets. It resolves the correct stream URL per market segment (spot, USD-M / COIN-M futures, options) and testnet, then lazily creates and caches Implementation:51bitquant_Ai_hedge_fund_crypto_ReconnectingWebsocket (for market streams) or Implementation:51bitquant_Ai_hedge_fund_crypto_KeepAliveWebsocket (for user-data streams needing a listen key). Each public method (`depth_socket`, `kline_socket`, `trade_socket`, `aggtrade_socket`, `ticker_socket`, `symbol_mark_price_socket`, `multiplex_socket`, `user_socket`, `futures_user_socket`, options streams, etc.) builds the Binance stream path and returns a live socket object that callers iterate via `recv()`. BinanceSocketType enumerates the segment kinds. ThreadedWebsocketManager wraps the manager in a background thread (extending Implementation:51bitquant_Ai_hedge_fund_crypto_ThreadedApiManager) exposing `start_*` methods that register a callback per stream.

Usage

  • Async market data: create a `BinanceSocketManager(client)` and call the relevant `*_socket(...)` method, then `async with socket as s: while True: msg = await s.recv()`.
  • Multiplexed streams: combine many streams into one connection with `multiplex_socket(streams)` / `futures_multiplex_socket`.
  • User/account data: use `user_socket()`, `futures_user_socket()`, `margin_socket()`, `isolated_margin_socket(symbol)`, `portfolio_margin_socket()` for authenticated account/order updates.
  • Synchronous callers: use `ThreadedWebsocketManager` and a `start_*` method with a callback to consume streams without managing an event loop.

Code Reference

Source Location

Signature

class BinanceSocketType(str, Enum):
    SPOT = "Spot"
    USD_M_FUTURES = "USD_M_Futures"
    COIN_M_FUTURES = "Coin_M_Futures"
    OPTIONS = "Vanilla_Options"
    ACCOUNT = "Account"


class BinanceSocketManager:
    STREAM_URL = "wss://stream.binance.{}/"
    FSTREAM_URL = "wss://fstream.binance.{}/"
    DSTREAM_URL = "wss://dstream.binance.{}/"
    OPTIONS_URL = "wss://nbstream.binance.{}/eoptions/"
    WEBSOCKET_DEPTH_5 = "5"
    WEBSOCKET_DEPTH_10 = "10"
    WEBSOCKET_DEPTH_20 = "20"

    def __init__(self, client: AsyncClient, user_timeout=KEEPALIVE_TIMEOUT): ...

    def depth_socket(self, symbol: str, depth: Optional[str] = None,
                     interval: Optional[int] = None) -> ReconnectingWebsocket: ...
    def kline_socket(self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE): ...
    def kline_futures_socket(self, symbol: str, interval=..., futures_type=..., contract_type=...): ...
    def miniticker_socket(self, update_time: int = 1000): ...
    def trade_socket(self, symbol: str): ...
    def aggtrade_socket(self, symbol: str): ...
    def aggtrade_futures_socket(self, symbol: str, futures_type=FuturesType.USD_M): ...
    def symbol_miniticker_socket(self, symbol: str): ...
    def symbol_ticker_socket(self, symbol: str): ...
    def ticker_socket(self): ...
    def futures_ticker_socket(self): ...
    def futures_coin_ticker_socket(self): ...
    def index_price_socket(self, symbol: str, fast: bool = True): ...
    def symbol_mark_price_socket(self, symbol, fast=True, futures_type=FuturesType.USD_M): ...
    def all_mark_price_socket(self, fast=True, futures_type=FuturesType.USD_M): ...
    def symbol_ticker_futures_socket(self, symbol, futures_type=FuturesType.USD_M): ...
    def individual_symbol_ticker_futures_socket(self, symbol, futures_type=FuturesType.USD_M): ...
    def all_ticker_futures_socket(self, channel="!bookTicker", futures_type=FuturesType.USD_M): ...
    def symbol_book_ticker_socket(self, symbol: str): ...
    def book_ticker_socket(self): ...
    def multiplex_socket(self, streams: List[str]): ...
    def options_multiplex_socket(self, streams: List[str]): ...
    def futures_multiplex_socket(self, streams, futures_type=FuturesType.USD_M): ...
    def user_socket(self): ...
    def futures_user_socket(self): ...
    def coin_futures_user_socket(self): ...
    def margin_socket(self): ...
    def futures_socket(self): ...
    def coin_futures_socket(self): ...
    def portfolio_margin_socket(self): ...
    def isolated_margin_socket(self, symbol: str): ...
    def options_ticker_socket(self, symbol: str): ...
    def options_ticker_by_expiration_socket(self, symbol: str, expiration_date: str): ...
    def options_recent_trades_socket(self, symbol: str): ...
    def options_kline_socket(self, symbol, interval=AsyncClient.KLINE_INTERVAL_1MINUTE): ...
    def options_depth_socket(self, symbol: str, depth: str = "10"): ...
    def futures_depth_socket(self, symbol: str, depth: str = "10", futures_type=FuturesType.USD_M): ...
    def options_new_symbol_socket(self): ...
    def options_open_interest_socket(self, symbol: str, expiration_date: str): ...
    def options_mark_price_socket(self, symbol: str): ...
    def options_index_price_socket(self, symbol: str): ...


class ThreadedWebsocketManager(ThreadedApiManager):
    def __init__(self, api_key=None, api_secret=None, requests_params=None,
                 tld="com", testnet=False, session_params=None,
                 https_proxy=None, loop=None): ...

    def start_depth_socket(self, callback, symbol, depth=None, interval=None) -> str: ...
    def start_kline_socket(self, callback, symbol, interval=...) -> str: ...
    def start_trade_socket(self, callback, symbol) -> str: ...
    def start_user_socket(self, callback) -> str: ...
    # ...one start_* per BinanceSocketManager method...

Import

from src.gateway.binance.ws.streams import (
    BinanceSocketManager,
    BinanceSocketType,
    ThreadedWebsocketManager,
)

I/O Contract

Inputs

Name Type Required Description
client AsyncClient Yes Binance async client (provides `tld`, `testnet`, proxy, listen-key calls)
user_timeout int No Listen-key keepalive interval (default `KEEPALIVE_TIMEOUT`)
symbol str Most streams Trading symbol, e.g. `"BTCUSDT"` (lowercased internally)
interval str kline streams Kline interval, e.g. `"1m"`, `"1h"`
depth str depth streams Partial book levels: `"5"`, `"10"`, `"20"`
streams List[str] multiplex Lowercase stream names to combine
callback Callable ThreadedWebsocketManager Sync or async function receiving each message

Outputs

Name Type Description
*_socket() ReconnectingWebsocket / KeepAliveWebsocket Live socket to iterate with `recv()`
start_*(...) str Connection key path (threaded variant) for `stop_socket()`
messages dict Raw Binance stream payloads (see each method's docstring schema)

Usage Examples

Async Trade Stream

import asyncio
from src.gateway.binance.async_client import AsyncClient
from src.gateway.binance.ws.streams import BinanceSocketManager

async def main():
    client = await AsyncClient.create()
    bm = BinanceSocketManager(client)
    ts = bm.trade_socket("BTCUSDT")
    async with ts as t:
        while True:
            msg = await t.recv()
            if msg:
                print(f"price={msg['p']} qty={msg['q']}")

Threaded Multiplex with Callback

from src.gateway.binance.ws.streams import ThreadedWebsocketManager

def handle(msg):
    # msg is a {"stream": ..., "data": ...} combined payload
    print(msg["stream"], msg["data"])

twm = ThreadedWebsocketManager(api_key="...", api_secret="...")
twm.start_multiplex_socket(handle, ["btcusdt@trade", "ethusdt@trade"])

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment