Day 21: Real-Time Dashboard Backend (SSE)
What I Built
- Server-Sent Events (SSE) streaming endpoint at /api/events/equity for real-time dashboard updates
- PaperTradingStateManager class for position tracking, P&L calculations, and equity snapshots
- REST API endpoints for paper trading status, trade history, and equity history
- Comprehensive test suite with 4 unit tests covering all endpoints
Code Highlight
@app.get("/api/events/equity")
async def equity_stream():
"""Stream equity updates via Server-Sent Events."""
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
},
)
async def event_generator():
"""Generate SSE events for real-time updates."""
last_update = None
while True:
try:
# Only send update if state changed
current_state = json.dumps(paper_trading_state)
if current_state != last_update:
yield f"data: {current_state}\n\n"
last_update = current_state
# Send heartbeat every 5 seconds (SSE spec)
await asyncio.sleep(5)
except asyncio.CancelledError:
logger.info("SSE client disconnected")
break
except Exception as e:
logger.error(f"SSE error: {e}")
yield f"data: {json.dumps({'error': str(e)})}\n\n"
Architecture Decision
Chose Server-Sent Events (SSE) over WebSockets for the dashboard streaming because SSE is simpler for one-way server-to-client communication, has built-in reconnection handling, and works well with HTTP/2. For a trading dashboard that primarily needs to push equity updates, SSE provides the right balance of simplicity and reliability without the complexity of WebSocket protocol management.
Testing Results
All 4 unit tests pass, covering critical scenarios:
- SSE endpoint availability and proper content-type headers
- Paper trading status endpoint returns correct state structure
- Trade history endpoint with pagination support
- Equity history endpoint for charting data
Next Steps
Day 22 will implement the React dashboard frontend with Recharts integration for real-time equity curve visualization and trade history display.
Follow @therealkamba on X for regular updates. View all posts →