Example Overview
The three Python examples demonstrate a real-time market data pipeline.
Architecture
flowchart TD
BINANCE[Binance WebSocket<br/>btcusdt@depth@100ms]
ALPACA[Alpaca WebSocket<br/>BTC/USD orderbooks]
WSM[WebSocketManager]
WM[WorkManager]
API[API Gateway]
DAPR[Dapr State + Pub/Sub]
BINANCE -->|wss://| WSM
ALPACA -->|wss:// + auth| WSM
WSM -->|Publish depth| DAPR
DAPR -->|State store| API
API -->|btcusdt-orderbook| STATE[(State Store)]
WM -->|Poll state| API
WM -->|Calculate imbalance| RESULT[btcusdt-imbalance]
Data Flow
- WebSocketManager connects to Binance/Alpaca and:
- Publishes raw depth to Dapr pub/sub (
btcusdt-depth,btcusd-orderbook) -
Stores top-20 order book snapshot to state store
-
API Gateway provides:
- State persistence (
examples/btcusdt-orderbook) -
Pub/sub topic management
-
WorkManager imbalance worker:
- Monitors state store for new order book data
- Calculates weighted bid/ask imbalance
- Outputs pressure signal: SELLING / BUYING / NEUTRAL
Key Concepts
| Concept | Implementation |
|---|---|
| WebSocket connection | WebSocketManagerClient.connect() with auto_reconnect=True |
| Order book management | Local OrderBook class with snapshot + diff updates |
| API authentication | Alpaca sends auth message over WebSocket |
| State store persistence | API Gateway REST endpoints (SaveState, GetState) |
| Reconnection | Exponential backoff: 1s, 2s, 4s, 8s, 16s, max 30s |
| Bid/ask imbalance | Σ ask_price × ask_qty − Σ bid_price × bid_qty for top N levels |