06 - WebSockets Architecture

Overview

OpenAlgo implements a unified WebSocket proxy server that handles real-time market data streaming from 29 brokers. The architecture uses ZeroMQ for high-performance internal messaging and supports connection pooling for handling thousands of symbol subscriptions.

Architecture Diagram

Core Components

1. WebSocket Proxy Server

Location: websocket_proxy/server.py

The central component that manages client connections, authentication, and message routing.

2. Broker Adapters

Location: websocket_proxy/base_adapter.py

Abstract base class for broker-specific WebSocket implementations:

3. Connection Pooling

Configuration:

Connection Pool Logic:

Message Flow

Client Authentication Flow

Subscription Flow

Data Streaming Flow

Client Protocol

Message Format

Authentication:

Subscribe:

Unsubscribe:

Response Format

Market Data (LTP):

Market Data (QUOTE):

Market Data (DEPTH):

Performance Optimizations

1. Subscription Index (O(1) Lookup)

2. Message Throttling

3. Mode Mapping Pre-computation

Broker Adapter Structure

Each broker has a dedicated adapter in broker/{broker_name}/streaming/:

Adapter Implementation Example:

Configuration

Environment Variables

Symbol Limits by Broker

Broker
Max Symbols/Connection
Default Pool Size
Depth Levels

Zerodha

3000

1

5

Angel

1000

3

5

Dhan

1000

3

20

Fyers

2000

2

5

Nubra

1000

3

5

Others

1000

3

5

Note: Only Dhan supports 20-level market depth. All other brokers provide 5-level depth. The frontend provides depth level routes at /websocket/test/20, /websocket/test/30, and /websocket/test/50 for testing different depth configurations.

Frontend Integration

React Hook (useMarketData)

websocket_proxy/ Directory Structure

App Integration (app_integration.py)

The WebSocket server runs as a daemon thread inside the main Flask application:

Key Points:

  • No separate service needed - WebSocket runs inside main process

  • Single worker (-w 1) required for Gunicorn

  • Thread automatically cleans up on application shutdown

  • ZeroMQ context shared for message routing

Key Files Reference

File
Purpose

websocket_proxy/server.py

Main WebSocket proxy server (port 8765)

websocket_proxy/base_adapter.py

Base class for broker adapters

websocket_proxy/broker_factory.py

Creates broker-specific adapters

websocket_proxy/connection_manager.py

Connection pool management

websocket_proxy/app_integration.py

Flask app integration (thread management)

broker/*/streaming/*_adapter.py

Broker-specific implementations

frontend/src/hooks/useMarketData.ts

React WebSocket hook

Last updated