Overview
TheWsManager class is a singleton that manages WebSocket connections to the Exchange Web backend. It handles message buffering, callback registration, and real-time data streaming for market depth and trades.
Base URL
Class: WsManager
Static Methods
getInstance()
Returns the singleton instance of WsManager. Creates a new instance if one doesn’t exist.The singleton WsManager instance
Instance Methods
init()
Initializes the WebSocket connection and sets up event handlers. Called automatically by the constructor.Connection Behavior
- On Open: Flushes all buffered messages to the WebSocket
- On Message: Parses incoming messages and invokes registered callbacks based on message type
Supported Message Types
Order book depth updates
bids(array): Updated bid orders [[price, quantity], …]asks(array): Updated ask orders [[price, quantity], …]
Trade execution data
- Contains trade information from the message data
sendMessage()
Sends a message to the WebSocket server. Automatically buffers messages if connection is not yet established.Message object to send. The method automatically adds a unique
id field.If the WebSocket connection is not initialized, messages are buffered and sent when the connection opens.
Example Message
registerCallback()
Registers a callback function for a specific message type.Message type to listen for (e.g., “depth”, “trade”, “ticker”)
Callback function to invoke when messages of this type are received
Unique identifier for this callback registration (used for deregistration)
Callback Signatures
- Depth Callback
- Trade Callback
deRegisterCallback()
Removes a previously registered callback.Message type the callback was registered for
Unique identifier of the callback to remove
Usage Example
Basic Setup
React Integration
Multiple Callbacks
Message Buffering
The WsManager automatically buffers messages sent before the WebSocket connection is established:Architecture Notes
The WsManager uses the singleton pattern to ensure only one WebSocket connection exists across the application. This prevents duplicate connections and ensures efficient resource usage.
Callbacks are stored in a dictionary keyed by message type. Multiple callbacks can be registered for the same type, and all will be invoked when messages of that type are received.
Source Location
apps/web/src/utils/ws_manager.ts