WebSocket Service
This document specifies the design and implementation of the real-time WebSocket service, which is responsible for pushing live data and signals to connected frontend clients.
Audience: Gemini (Implementation), You (Verification) Goal: Define the exact events and data structures for real-time communication.
Core Technology
- Library:
python-socketiointegrated with FastAPI viafastapi-socketio. - Purpose: To provide a persistent, bidirectional communication channel between the FastAPI backend and the React frontend.
Service Location
All WebSocket connection logic will be managed within a dedicated service module to keep the main main.py file clean.
- File:
backend/app/services/websocket_manager.py - Object: A singleton class or object instance named
sio(Socket.IO Manager).
This sio object will be initialized in websocket_manager.py and imported into main.py to be attached to the FastAPI application.
Server-Side Event Handlers
The sio manager must implement handlers for the following standard events.
connect
- Trigger: A new client establishes a WebSocket connection.
- Action:
- Log the connection with the client's unique Session ID (
sid). - Emit a
'welcome'message back to the connected client to confirm the connection was successful.
- Log the connection with the client's unique Session ID (
- Example Implementation:
# In websocket_manager.py import socketio sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*') @sio.event async def connect(sid, environ): print(f"[Socket.IO] Client connected: {sid}") await sio.emit('welcome', {'message': 'Successfully connected to Quantum Trader Pro real-time feed.'}, to=sid)
disconnect
- Trigger: A client disconnects.
- Action:
- Log the disconnection event with the client's
sid.
- Log the disconnection event with the client's
- Example Implementation:
@sio.event def disconnect(sid): print(f"[Socket.IO] Client disconnected: {sid}")
Emitted Events (Server to Client)
The server will proactively push data to all connected clients using these custom events.
new_signal
- Trigger: A new trading signal is generated by the backend (e.g., from the Redis Pub/Sub listener).
- Payload (Data Structure): A JSON object with a consistent structure.
{ "type": "QUANTUM_CIPHER", "signal": "BUY" or "SELL", "price": 162.50, "symbol": "BTC/USDT", "timeframe": "1m", "timestamp": "2023-10-27T10:00:00Z" } - Action: The server broadcasts this payload to all connected clients using
await sio.emit('new_signal', data).
status_update
- Trigger: A change in the backend's operational status.
- Payload (Data Structure):
{ "service": "SignalMonitorWorker", "status": "active" or "degraded" or "offline", "message": "Monitoring market for signals." } - Action: Broadcast the status update to all clients.