DlobWebsocketClient and MultiplexWebSocket for building reactive trading applications.
DlobWebsocketClient
TheDlobWebsocketClient subscribes to real-time orderbook data from Drift’s DLOB (Decentralized Limit Order Book) server.
Features
- Real-time L2 orderbook updates
- Support for indicative orderbooks
- Automatic reconnection with exponential backoff
- Slot-based result validation to prevent stale data
- Tab return handling for browser applications
- RxJS-based reactive streams
- Connection multiplexing
Basic Setup
Orderbook Data Structure
The WebSocket client returns processed orderbook data:Configuration Options
Advanced Features
Orderbook Grouping
Group orderbook levels by price increments:Tab Return Handling
Handle browser tab visibility changes:Slot Tracking Reset
Reset slot tracking on reconnection:Indicative vs Regular Orderbook
Regular Orderbook (enableIndicativeOrderbook: false):
- Shows only orders currently on the orderbook
- Reflects actual liquidity available for immediate execution
enableIndicativeOrderbook: true):
- Includes pending orders not yet on the orderbook
- Provides a more complete view of intended liquidity
- Useful for market analysis and forecasting
MultiplexWebSocket
TheMultiplexWebSocket is a lower-level utility that manages WebSocket connections with multiplexing, allowing multiple subscriptions over a single connection.
Key Features
- Connection Pooling: Reuses connections for the same URL
- Automatic Reconnection: Exponential backoff with configurable limits
- Heartbeat Monitoring: Detects dead connections
- Message Filtering: Route messages to specific subscriptions
- Error Handling: Per-subscription error callbacks
Creating a WebSocket Subscription
Reconnection Behavior
The MultiplexWebSocket implements intelligent reconnection:- First attempt: 1 second delay
- Second attempt: 2 seconds delay
- Third attempt: 4 seconds delay
- Fourth attempt: 8 seconds delay
- Fifth attempt: 8 seconds delay
- After 5 attempts in 60s: Throw error
Heartbeat Monitoring
Enable heartbeat monitoring to detect dead connections:Reactive Patterns with RxJS
The WebSocket clients use RxJS for reactive data streams:Combining Multiple Streams
Throttling Updates
Error Recovery
Best Practices
Connection Management
Connection Management
Properly manage WebSocket lifecycle:
Error Handling
Error Handling
Implement fallback mechanisms:
Memory Management
Memory Management
Prevent memory leaks with proper cleanup:
Performance Optimization
Performance Optimization
Use throttling for high-frequency updates:
Next Steps
Client Modules
Learn about other client modules
Utility Functions
Explore helper functions and utilities