Always-on market data streaming
Whenever a valid Zerodha access token exists in the database,ensureMarketDataRunning() starts (or restarts) the WebSocket feed and financial interval. This runs:
- After Zerodha login (manual callback, auto-login, or revisiting
/loginwith a valid token) - On server restart (via
initializeMarketServices()→initializeMarketDataIfNeeded()) - At 6:00 AM auto-login
- Manual Zerodha logout
- The 6:00 AM daily token refresh job (or manual logout)
- Server shutdown (
handleZerodhaDisconnect())
handlePostZerodhaLogin() delegates to ensureMarketDataRunning({ forceRestart: true }), which:
- Validates the access token (with retries on transient network errors; no destructive cleanup on failure)
- Restarts the WebSocket (
restartMarketData) - Starts the financial interval (with a fresh financial WebSocket — stale clients are cleared on disconnect)
handleZerodhaDisconnect()), market data, the financial interval, and the financial WebSocket singleton stop immediately.
Startup recovery
If the server restarts (e.g. PM2) and no valid streaming session exists,initializeMarketDataIfNeeded() attempts autoZerodhaLogin() once when credentials are configured. Look for log lines:
Startup auto-login succeededStartup auto-login failed: ...
Required environment variables
Add these to the server.env file. Do not commit real values to git.
See TOTP setup for configuring
ZERODHA_TOTP_SECRET.
Schedule
See Daily refresh schedule for operational context.
Deployment (Ubuntu / PM2)
Environment is loaded viasrc/env.ts before other modules. PM2 must use the server directory as working directory.
node -r dotenv/config dist/src/app.js with cwd set to the server folder.
See PM2 deployment for full backend deploy steps.
Manual test script
Market data streaming ensured and no repeating Error in startFinacialInterval: Incorrect api_key or access_token.
Manual test endpoint
Admin-only endpoint for testing without waiting for cron:Log verification and fallback
See Zerodha troubleshooting for log grep patterns, fallback manual login, and security notes.Security notes
- Store credentials only in environment variables or a secrets manager
- Never log password or TOTP secret values
- Auto-login uses unofficial Kite web login endpoints; keep manual login as fallback