WebSocket Proxy Server
Relevant source files
The following files were used as context for generating this wiki page:
The WebSocket Proxy Server is a high-performance streaming component in OpenAlgo that decouples broker-specific market data feeds from end-user client connections. It manages client authentication, manages complex subscription logic across multiple brokers, and ensures low-latency delivery of real-time market data (LTP, Quotes, Depth) and order updates.
Architecturally, the server functions as a bridge between the backend ZeroMQ (ZMQ) bus and frontend WebSocket clients. It uses a fan-in topology where broker adapters connect to a single bound ZMQ SUB socket in the proxy, which then fans out normalized data to authenticated WebSocket subscribers. This design allows the platform to support multiple concurrent sessions for a single user while maintaining only one active server-side broker feed.
Sources: CLAUDE.md, websocket_proxy/server.py:27-40
Architecture and Topology
The WebSocket Proxy Server operates on port 8765 by default and is designed to run as a separate process in production environments. It utilizes ZeroMQ for internal message passing and the websockets library for client communication.
Data Flow Topology
The system implements a "Fan-In" topology for market data collection and a "Fan-Out" strategy for client delivery.
The ZMQ SUB socket in the proxy server is the single binder, and every broker market-data adapter CONNECTs to it as a publisher. This ensures the rendezvous port is deterministic across different process startup orders.
Sources: CLAUDE.md, websocket_proxy/server.py:108-120
Component Breakdown
WebSocketProxy Class
The WebSocketProxy class is the central orchestrator, managing the lifecycle of the server and its listeners.
| Component | Responsibility |
|---|---|
self.clients | Maps client_id to active WebSocket connections. |
self.subscription_index | Optimized (symbol, exchange, mode) -> set(client_ids) map for O(1) lookup. |
self.broker_adapters | Maps user_id to specific BaseBrokerWebSocketAdapter instances. |
self.order_subscribers | Tracks users subscribed to account-level order updates. |
zmq_listener | Asynchronous task that processes ZMQ packets and triggers fan-out. |
| Sources: websocket_proxy/server.py:44-85 |
Broker Adapters and Pools
The system utilizes a broker_factory to create adapters dynamically based on user configuration. For specific brokers like Shoonya and Flattrade, the proxy implements "pooled" adapters. This allows multiple client devices (capped at MAX_SESSIONS_PER_USER = 5) to share one server-side broker feed.
Sources: CLAUDE.md, websocket_proxy/broker_factory.py, websocket_proxy/server.py:535-545
Communication Protocol
Authentication Flow
Clients must authenticate before they can subscribe to data. The server enforces a grace window (default 15 seconds) for unauthenticated connections before dropping them.
Subscription Modes
The proxy supports three primary data modes, where higher modes typically include all data from lower modes.
| Mode | Name | Data Description |
|---|---|---|
| 1 | LTP | Last Traded Price and timestamp. |
| 2 | Quote | Full quote: LTP, OHLC, Volume, and Change. |
| 3 | Depth | Level 2 Market Depth (Bids/Asks) + LTP. |
| Sources: collections/openalgo/IN_stock/WEBSOCKET_README.md, websocket_proxy/server.py:1020-1030 |
Message Throttling and Optimization
- Subscription Indexing: Uses
defaultdict(set)to eliminate nested loops during tick delivery, achieving O(1) client lookup. - Parallel Delivery: Uses
asyncio.gatherfor non-blocking message dispatch to large numbers of clients. - LTP Coalescing: While earlier versions used a time-based throttle, the current implementation prioritizes price accuracy during bursts (e.g., expiry days) by utilizing high-performance fan-out.
Sources: websocket_proxy/server.py:82-95, websocket_proxy/server.py:1055-1065
Operational Management
Stale Feed Detection
The proxy includes diagnostic signals to identify "stale feeds"—situations where an adapter reports it is connected but has delivered no ticks for a threshold (default 120s) while active subscriptions exist. This information is exposed via get_adapter_health().
Sources: websocket_proxy/server.py:438-455
Cache Invalidation
When a user logs out or re-authenticates in the main Flask process, a CACHE_INVALIDATE_ALL message is published to the ZMQ bus. The proxy listens for these and disconnects the relevant adapter and pool to ensure fresh tokens are used on the next connection.
Sources: CLAUDE.md, websocket_proxy/server.py:871-900
Configuration Options
| Environment Variable | Default | Description |
|---|---|---|
WEBSOCKET_HOST | 127.0.0.1 | Host to bind the proxy server. |
WEBSOCKET_PORT | 8765 | Port for client connections. |
ZMQ_PORT | 5555 | Internal port for the market data bus. |
WS_MAX_QUEUE | 1024 | Per-client buffer to absorb tick bursts. |
WS_AUTH_GRACE_SECONDS | 15 | Timeout for completing authentication. |
| Sources: websocket_proxy/server.py:108-112, websocket_proxy/server.py:220-230 |
The WebSocket Proxy Server is critical for maintaining high availability and broker-agnostic logic within OpenAlgo, ensuring that internal trading strategies and external clients receive a continuous, normalized stream of market data.