Skip to content

WebSocket API requests ​

Use WebsocketAPIClient to submit, amend and cancel orders over an authenticated WebSocket connection. Use WebsocketClient subscriptions separately to follow the resulting account changes.

Use await and try/catch just as you would with a REST API call. The SDK matches responses to requests and manages the WebSocket connection for you. Requests over a persistent WebSocket can offer lower overhead and latency, depending on the exchange, network and workload.

Cancel an existing order ​

This example cancels the remaining quantity of an existing BTC-USDT order. It uses live trading by default. Set OKX_CLIENT_ORDER_ID to an existing order you intend to cancel. Save the example as ws-api.ts beside the credential helper. Follow the compile instructions with ws-api.ts as the entry file and use the same account, region and live/demo environment as the original order:

ts
import { WebsocketAPIClient } from 'okx-api';
import { client, credentials } from './authenticated-client.js';

const api = new WebsocketAPIClient({ accounts: [credentials] });

async function main() {
  const clOrdId = process.env.OKX_CLIENT_ORDER_ID;
  if (!clOrdId) {
    throw new Error('Set OKX_CLIENT_ORDER_ID to the client order ID of the existing BTC-USDT order to cancel.');
  }
  const instruments = await client.getInstruments({ instType: 'SPOT', instId: 'BTC-USDT' });
  const instIdCode = instruments.find((instrument) => instrument.instId === 'BTC-USDT')?.instIdCode;
  if (instIdCode === undefined) {
    throw new Error('BTC-USDT instrument code was not returned; no cancellation was sent.');
  }
  const response = await api.cancelOrder({ instIdCode, clOrdId });
  console.log('Cancellation response:', response);
  if (response.code !== '0') {
    throw new Error(`Cancellation failed: ${response.code}`);
  }
  for (const result of response.data) {
    if (result.sCode !== '0') {
      throw new Error(`Cancellation rejected: ${result.sCode} ${result.sMsg}`);
    }
  }
}

main().catch((error) => {
  console.error('WS API request failed; reconcile before retrying:', error);
  process.exitCode = 1;
}).finally(() => {
  api.getWSClient().closeAll();
});
sh
node --env-file=.env dist/ws-api.js

The example looks up BTC-USDT with getInstruments() and passes its numeric instIdCode to the WebSocket command. Do not copy the REST instId parameter into WebSocket trading requests: use the instrument code required by the current WebSocket API.

Unlike the REST client, the WebSocket wrapper returns a response envelope containing code, msg and data. Inspect the top-level result and each item's sCode and sMsg. Transport or request errors may also reject the promise. Batch responses require checking every item; some items can succeed while others fail.

Available commands ​

The wrapper opens and authenticates connections as needed. A long-running service should retain its client instead of creating and closing it for every order; this single-command example closes on completion.

For lower-level use, sendWSAPIRequest() takes a connection key, operation and parameters. Obtain private routing with getMarketWsKey('private') rather than hardcoding a connection key or URL. Keep market and demoTrading consistent across clients.

An order can fill while cancellation is being processed. Follow the private order stream and check unknown outcomes as described in Order management. Never replay a timed-out trade automatically.

Built by Siebly. Open source SDKs for exchange APIs.