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.
import { WebsocketClient } from 'okx-api';

const wsClient = new WebsocketClient({
  accounts: [
    {
      apiKey: 'YOUR_API_KEY',
      apiSecret: 'YOUR_API_SECRET',
      apiPass: 'YOUR_API_PASSPHRASE',
    },
  ],
});

wsClient.on('update', (data) => {
  console.log('data update', data);
});

wsClient.on('open', (data) => {
  console.log('connection opened', data.wsKey);
});

wsClient.subscribe({ channel: 'tickers', instId: 'BTC-USDT' });

Constructor

new WebsocketClient(
  options?: WSClientConfigurableOptions,
  logger?: DefaultLogger
)
options
WSClientConfigurableOptions
Optional configuration object. See options below.
logger
DefaultLogger
Optional custom logger. Defaults to the built-in console logger.

Constructor options (WSClientConfigurableOptions)

accounts
APICredentials[]
Array of API credential objects, each with apiKey, apiSecret, and apiPass. Providing credentials enables authentication for private channels and WS API calls.
market
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)
demoTrading
boolean
default:"false"
Set to true to connect to OKX demo trading WebSocket endpoints.
disableHeartbeat
boolean
default:"false"
Disable the ping/pong heartbeat mechanism. Not recommended — OKX requires heartbeats to keep connections alive.
pingInterval
number
How often (ms) to check that the connection is alive by sending a ping.
pongTimeout
number
How long (ms) to wait for a pong response before treating the connection as dead and reconnecting.
reconnectTimeout
number
Delay (ms) before spawning a new connection after a disconnect.
requestOptions
RestClientOptions
Options forwarded to the underlying RestClient used for time synchronisation.
wsOptions
object
Additional options passed directly to the underlying isomorphic-ws WebSocket constructor, such as protocols or agent.
wsUrl
string
Override the WebSocket URL entirely.
customSignMessageFn
(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()

connectAll(): Promise<WSConnectedResult | undefined>[]
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?)

connectPublic(businessEndpoint?: boolean): Promise<WSConnectedResult | undefined>
Connect to the public WebSocket endpoint.
businessEndpoint
boolean
When true, connects to the business WebSocket endpoint instead of the standard public one.

connectPrivate(businessEndpoint?)

connectPrivate(businessEndpoint?: boolean): Promise<WSConnectedResult | undefined>
Connect to the private (authenticated) WebSocket endpoint.
businessEndpoint
boolean
When true, connects to the business WebSocket endpoint.

connectWSAPI()

connectWSAPI(): Promise<unknown[]>
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(
  wsEvents: WsChannelSubUnSubRequestArg[] | WsChannelSubUnSubRequestArg,
  isPrivateTopic?: boolean
): Promise<unknown>[]
Subscribe to one or more WebSocket channels. Subscriptions are tracked and automatically re-subscribed if the connection drops and reconnects.
wsEvents
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).
isPrivateTopic
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:
// Subscribe to a single public channel
wsClient.subscribe({ channel: 'tickers', instId: 'BTC-USDT' });

// Subscribe to multiple channels at once
wsClient.subscribe([
  { channel: 'tickers', instId: 'BTC-USDT' },
  { channel: 'tickers', instId: 'ETH-USDT' },
]);

// Subscribe to a private channel
wsClient.subscribe({ channel: 'orders', instType: 'ANY' });

unsubscribe(wsEvents, isPrivateTopic?)

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

WebSocket API

sendWSAPIRequest(wsKey, operation, params, requestFlags?)

sendWSAPIRequest<TWSKey, TWSOperation, TWSParams, TWSAPIResponse>(
  wsKey: WsKey,
  operation: TWSOperation,
  params: TWSParams & { signRequest?: boolean },
  requestFlags?: WSAPIRequestFlags
): Promise<TWSAPIResponse>
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
WsKey
The WebSocket key identifying which connection to use. Use getMarketWsKey('private') or getMarketWsKey('business') to obtain the correct key.
operation
string
The WS API operation name (e.g. 'order', 'cancel-order', 'batch-orders').
params
object
Parameters for the operation. The shape is typed based on the operation.
requestFlags
WSAPIRequestFlags
Optional flags to control request behaviour, such as expTime and authIsOptional.
Example:
const response = await wsClient.sendWSAPIRequest(
  wsClient.getMarketWsKey('private'),
  'order',
  {
    instId: 'BTC-USDT',
    tdMode: 'cash',
    side: 'buy',
    ordType: 'market',
    sz: '0.01',
  },
);

getMarketWsKey(type)

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

Utility

setTimeOffsetMs(offsetMs)

setTimeOffsetMs(offsetMs: number): void
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:
wsClient.on('eventName', (data) => { ... });
EventPayloadDescription
open{ wsKey: WsKey }A WebSocket connection has been opened.
reconnect{ wsKey: WsKey }The client is attempting to reconnect after a disconnect.
reconnected{ wsKey: WsKey }The client has successfully reconnected.
authenticated{ wsKey: WsKey }A private connection has been successfully authenticated.
updateWsDataEvent & { wsKey: WsKey }A data update was received on a subscribed channel.
responseobject & { wsKey: WsKey }A response to a subscribe, unsubscribe, or WS API request was received.
exceptionobject & { wsKey: WsKey }An error event was received from the server, or an internal error occurred.
close{ wsKey: WsKey }A WebSocket connection has closed.

Handling update events

All channel data arrives via the update event. Use the wsKey and arg.channel properties to route messages:
wsClient.on('update', (data) => {
  const channel = data?.arg?.channel;

  if (channel === 'tickers') {
    console.log('ticker update', data.data);
  }

  if (channel === 'orders') {
    console.log('order update', data.data);
  }
});

Handling errors

wsClient.on('exception', (data) => {
  console.error('WebSocket error', data);
});

Build docs developers (and LLMs) love