The Market Data Service is a core component of our trading system that handles real-time market data collection, processing, and analysis for the TRUMP/USDC trading pair. It provides essential functionality for order book management, technical analysis, and price level optimization.
graph TD
A[Binance WebSocket] --> B[MarketDataService]
B --> C[Order Book]
B --> D[Candle Storage]
B --> E[Technical Indicators]
B --> F[Market Analysis]
C --> G[Imbalance Calculation]
D --> E
E --> F
G --> F
@dataclass
class Candle:
timestamp: datetime
open: float
high: float
low: float
close: float
volume: float
trades: int
vwap: Optional[float] = None
- Stores OHLCV (Open, High, Low, Close, Volume) data
- Includes trade count and VWAP (Volume-Weighted Average Price)
- Used for technical analysis and pattern recognition
class OrderBook:
def __init__(self, max_depth: int = 20):
self.bids: Dict[float, float] = {} # price -> quantity
self.asks: Dict[float, float] = {} # price -> quantity
- Maintains real-time order book state
- Tracks bid and ask orders up to specified depth
- Calculates volume imbalances for market analysis
- Auto-maintains maximum depth for memory efficiency
class MarketDataService:
def __init__(self, symbol: str, candle_limit: int = 1000):
self.symbol = symbol
self.order_book = OrderBook()
self.trades = deque(maxlen=1000)
self.candles = deque(maxlen=candle_limit)
-
Real-time Data Collection
- WebSocket connection to Binance
- Automatic reconnection handling
- Efficient data structures with size limits
-
Technical Indicators
- Moving Averages (MA5, MA20)
- VWAP (Volume-Weighted Average Price)
- Order book imbalance
-
Market Analysis
- Price level optimization
- Volume profile analysis
- Market state snapshots for AI
# Initialize the service
market_data = MarketDataService(symbol="TRUMPUSDC")
# Start data collection
market_data.start(api_key="your_api_key", api_secret="your_api_secret")
# Get current market state
snapshot = market_data.get_market_snapshot()
print(f"Current price: {snapshot['market_state']['current_price']}")
print(f"Order book imbalance: {snapshot['market_state']['order_book_imbalance']}")
# Get optimal entry prices for 10 USDC
entry_prices = market_data.get_optimal_entry_levels(usdc_amount=10)
print(f"Suggested entry prices: {entry_prices}")
{
"market_state": {
"current_price": 39.67,
"order_book_imbalance": -0.02,
"volume_profile": {
"bid_volume": 15000,
"ask_volume": 12000
},
"technical_indicators": {
"ma5": 39.45,
"ma20": 39.12,
"vwap": 39.33
}
},
"metadata": {
"symbol": "TRUMPUSDC",
"timestamp": "2024-01-21T11:30:00Z"
}
}
{
"e": "depthUpdate",
"b": [["39.50", "1.234"]], // Bids [price, quantity]
"a": [["39.55", "0.567"]] // Asks [price, quantity]
}
The service implements comprehensive error handling:
- WebSocket disconnection recovery
- Invalid data validation
- Error logging and reporting
- Graceful degradation of services
-
Memory Management
- Fixed-size collections (deque) for trades and candles
- Order book depth limitation
- Efficient data structures for quick lookups
-
CPU Optimization
- Incremental technical indicator updates
- Lazy evaluation of expensive calculations
- Efficient order book updates
-
Network Efficiency
- WebSocket connection for real-time updates
- Minimal payload processing
- Automatic reconnection with backoff
-
Planned Features
- Additional technical indicators (RSI, MACD)
- Enhanced VWAP calculation
- Historical data integration
- More sophisticated entry price calculation
-
Optimizations
- Parallel processing for indicators
- Enhanced memory management
- Performance monitoring
- Caching frequently accessed data
The Market Data Service integrates with:
- Binance WebSocket API
- Trading Engine
- AI Strategy Module
- Risk Management System
To test the service:
- Create a test instance with test API keys
- Monitor WebSocket connection status
- Verify data accuracy against Binance UI
- Test error handling and recovery
-
API Key Management
- Use read-only API keys for market data
- Never log sensitive data
- Secure WebSocket connection
-
Data Validation
- Validate all incoming data
- Sanitize outputs
- Handle edge cases gracefully