Overview
TheBinancePriceFetcherService is a background service that connects to Binance WebSocket streams to fetch real-time cryptocurrency prices. It manages dynamic subscriptions based on active price rules and maintains price history for technical analysis.
Architecture
Implemented insrc/PriceSignal/BackgroundServices/BinancePriceFetcherService.cs, the service operates as a hosted background service that runs continuously throughout the application lifecycle.
Key Components
- IWebsocketClientProvider: Manages WebSocket connections to Binance
- PriceHistoryCache: In-memory cache for historical price data
- ConcurrentBag<string>: Thread-safe collection of active trading symbols
- AppDbContext: Database context for loading historical data
Service Initialization
Execution Flow
Startup Process
Price History Loading
The service loads the last 500 candles for each symbol on startup:WebSocket Stream Management
Starting the WebSocket Connection
Dynamic Subscription Updates
The service can dynamically add or remove symbol subscriptions:Symbol Management
Add Symbol
Remove Symbol
Shutdown Handling
Binance Stream Format
The service subscribes to Binance aggregated trade streams using the format:Performance Features
- ConcurrentBag for thread-safe symbol management
- Channel-based message processing for backpressure handling
- Lazy loading of price history (500 candles per symbol)
- Dynamic subscriptions to minimize bandwidth usage
Related Components
- Rule Engine - Consumes price data from this service
- NATS Messaging - Distributes price updates across services