WebsocketClient class provides an event-driven interface for subscribing to OKX WebSocket channels. It handles connection management, authentication, heartbeats, and automatic reconnection so you can focus on processing incoming data.
Installation
Basic usage
Constructor options
Pass aWSClientConfigurableOptions object as the first argument to the constructor.
| Option | Type | Default | Description |
|---|---|---|---|
accounts | APICredentials[] | — | One or more API credentials. Required for private channels. |
market | 'prod' | 'EEA' | 'US' | 'prod' | Selects the regional endpoint. 'prod' connects to www.okx.com, 'EEA' to my.okx.com, and 'US' to app.okx.com. |
demoTrading | boolean | false | Use OKX demo trading endpoints. |
pingInterval | number | — | Milliseconds between heartbeat pings. |
pongTimeout | number | — | Milliseconds to wait for a pong before treating the connection as dead. |
reconnectTimeout | number | — | Milliseconds to wait before respawning a dropped connection. |
disableHeartbeat | boolean | false | Disable the ping/pong heartbeat. Not recommended. |
customSignMessageFn | (message: string, secret: string) => Promise<string> | — | Override the default HMAC signing implementation, e.g. to use Node’s createHmac. |
wsOptions | object | — | Raw options forwarded to the underlying WebSocket constructor (agent, protocols, etc.). |
wsUrl | string | — | Override the WebSocket URL entirely. |
Subscribe and unsubscribe
Callsubscribe() with a single channel arg object or an array of them. The client automatically opens the appropriate WebSocket connection if one does not exist yet, and resubscribes after any reconnection.
Topics are persisted in memory. If the connection drops and reconnects, all active subscriptions are automatically resubscribed. Calling
unsubscribe() removes a topic from that list so it is not resubscribed.Event-driven architecture
All incoming data and lifecycle events are surfaced through Node.jsEventEmitter events. Attach listeners with .on() before subscribing.
Connections
The client manages separate WebSocket connections per endpoint type (public, private, business). You can eagerly open connections before subscribing, or let the library open them on demand.Legacy WebSocket client
The SDK also exportsWebsocketClientLegacy, which is a previous implementation retained for backwards compatibility. New integrations should use WebsocketClient instead.
Learn more
Public Channels
Subscribe to instruments, tickers, order books, trades, and candles without authentication.
Private Channels
Subscribe to account, positions, orders, and fills with API credentials.
Event Handling
Full reference for all emitted events and their TypeScript types.
Reconnection
How the client detects dropped connections and restores subscriptions automatically.

