Skip to main content

Overview

WebsocketClient is the primary class for subscribing to OKX WebSocket channels and for making WebSocket API (WS API) requests. It extends BaseWebsocketClient and emits typed events for connection lifecycle and market data updates.

Constructor

WSClientConfigurableOptions
Optional configuration object. See options below.
DefaultLogger
Optional custom logger. Defaults to the built-in console logger.

Constructor options (WSClientConfigurableOptions)

APICredentials[]
Array of API credential objects, each with apiKey, apiSecret, and apiPass. Providing credentials enables authentication for private channels and WS API calls.
string
default:"prod"
The API group to connect to:
  • 'prod' — OKX global (wss://ws.okx.com)
  • 'EEA' — European Economic Area (wss://wspap.okx.com)
  • 'US' — United States (wss://wsaws.okx.com)
boolean
default:"false"
Set to true to connect to OKX demo trading WebSocket endpoints.
boolean
default:"false"
Disable the ping/pong heartbeat mechanism. Not recommended — OKX requires heartbeats to keep connections alive.
number
How often (ms) to check that the connection is alive by sending a ping.
number
How long (ms) to wait for a pong response before treating the connection as dead and reconnecting.
number
Delay (ms) before spawning a new connection after a disconnect.
RestClientOptions
Options forwarded to the underlying RestClient used for time synchronisation.
object
Additional options passed directly to the underlying isomorphic-ws WebSocket constructor, such as protocols or agent.
string
Override the WebSocket URL entirely.
(message: string, secret: string) => Promise<string>
Provide a custom HMAC signing function for authentication. Useful for using Node’s native crypto.createHmac.

Methods

Connection management

connectAll()

Requests connection of all dependent public and private WebSockets at once, rather than waiting for the library to connect automatically on the first subscription. Returns an array of two promises: one for the public connection and one for the private connection.

connectPublic(businessEndpoint?)

Connect to the public WebSocket endpoint.
boolean
When true, connects to the business WebSocket endpoint instead of the standard public one.

connectPrivate(businessEndpoint?)

Connect to the private (authenticated) WebSocket endpoint.
boolean
When true, connects to the business WebSocket endpoint.

connectWSAPI()

Ensures both the private and business WebSocket connections are active and authenticated. Call this before making WS API requests to pre-warm the connection and reduce latency on the first request.

Subscriptions

subscribe(wsEvents, isPrivateTopic?)

Subscribe to one or more WebSocket channels. Subscriptions are tracked and automatically re-subscribed if the connection drops and reconnects.
WsChannelSubUnSubRequestArg | WsChannelSubUnSubRequestArg[]
A single channel subscription object or an array of them. Each object must include a channel property, plus any channel-specific parameters (e.g. instId).
boolean
Optional hint to force the library to treat a channel as private. The library auto-detects most private channels; only set this if a channel is not yet recognised.
Returns an array of promises, one per unique WebSocket connection used. Example:

unsubscribe(wsEvents, isPrivateTopic?)

Unsubscribe from one or more channels. The subscription is removed from memory and will not be re-subscribed on reconnection.
WsChannelSubUnSubRequestArg | WsChannelSubUnSubRequestArg[]
The channel(s) to unsubscribe from. Must match the arguments used when subscribing.
boolean
Optional private topic hint, same as in subscribe().

WebSocket API

sendWSAPIRequest(wsKey, operation, params, requestFlags?)

Send a request over the WebSocket API. This is a lower-level method — for most use cases, prefer the higher-level WebsocketAPIClient. The method ensures the connection is active and authenticated before sending, then returns a promise that resolves or rejects when the matching response arrives.
WsKey
The WebSocket key identifying which connection to use. Use getMarketWsKey('private') or getMarketWsKey('business') to obtain the correct key.
string
The WS API operation name (e.g. 'order', 'cancel-order', 'batch-orders').
object
Parameters for the operation. The shape is typed based on the operation.
WSAPIRequestFlags
Optional flags to control request behaviour, such as expTime and authIsOptional.
Example:

getMarketWsKey(type)

Returns the correct WsKey for the active market (prod / EEA / US) and the given connection type. Used when calling sendWSAPIRequest() directly.
string
'private' for order management and account data, or 'business' for spread trading and other business-line WS API operations.

Utility

setTimeOffsetMs(offsetMs)

Manually set the time offset (ms) between the local clock and the OKX server clock. The client uses this to generate valid authentication timestamps. Normally the SDK handles this automatically.

Events

Listen to events using the on() method:

Handling update events

All channel data arrives via the update event. Use the wsKey and arg.channel properties to route messages:

Handling errors