Skip to content

Binance CLOB Example

File: python/websocketmanager/binance_clob_example.py

Streams BTC/USDT order book depth from Binance WebSocket API.

API Details

Property Value
WebSocket URL wss://stream.binance.com:9443/ws/btcusdt@depth@100ms
Authentication None (public market data)
Update frequency Every 100ms
Stream type Diff depth (depthUpdate events)
REST snapshot GET https://api.binance.com/api/v3/depth?symbol=BTCUSDT&limit=5000

What It Does

  1. Fetches initial order book snapshot from Binance REST API
  2. Connects to Binance WebSocket via WebSocketManager
  3. Maintains local order book from diff depth updates
  4. Stores top 20 levels + spread to state store every 10s
  5. Publishes depth to Dapr pub/sub topic btcusdt-depth

Reconnection

Uses explicit exponential backoff loop:

for attempt in range(1, 6):
    try:
        conn = await client.connect(url, auto_reconnect=True)
        return conn.id
    except Exception as e:
        delay = min(1.0 * (2 ** (attempt - 1)), 30)
        await asyncio.sleep(delay)

WebSocketManager also handles automatic reconnection transparently via auto_reconnect=True.

Running

source .env
python python/websocketmanager/binance_clob_example.py

Expected output:

============================================================
  Binance CLOB Example — BTCUSDT Order Book Depth
============================================================

  Snapshot loaded: 5,000 bids, 5,000 asks (updateId=123456789)
  ✓ Connected: id=abc123
  ✓ Publishing depth updates to topic: btcusdt-depth
  ✓ Initial state saved to: examples/btcusdt-orderbook

  Monitoring depth updates (Ctrl+C to stop)...
     Time       Best Bid       Best Ask     Spread    Lvl
   ────────  ──────────  ────────────  ────────  ─────
      10.0s    87650.00      87651.50      1.50    20
      20.0s    87648.50      87650.00      1.50    40