Skip to main content

Prerequisites

You need a Node.js project with TypeScript support (recommended) or plain JavaScript. The SDK is published to npm as okx-api.
1

Install the SDK

npm install okx-api
2

Make your first public REST call

No API credentials are required for public endpoints. The example below fetches all SPOT instruments and filters for SUI pairs — a useful sanity check that the SDK is installed correctly.
import { RestClient } from 'okx-api';

const client = new RestClient();

(async () => {
  try {
    const results = await client.getInstruments({ instType: 'SPOT' });

    console.log(
      'SUI instruments:',
      results.filter((row) => row.baseCcy === 'SUI'),
    );
  } catch (e) {
    console.error('request failed: ', e);
  }
})();
Responses are automatically unwrapped. When OKX returns { code: '0', data: [...] }, the SDK returns only the data array — no extra nesting to handle.
3

Authenticate and check your balance

For private endpoints you must supply apiKey, apiSecret, and apiPass. Load them from environment variables — never hardcode credentials.
import { RestClient } from 'okx-api';

const client = new RestClient({
  apiKey: process.env.API_KEY_COM,
  apiSecret: process.env.API_SECRET_COM,
  apiPass: process.env.API_PASS_COM,
});

(async () => {
  try {
    const allBalances = await client.getBalance();
    const usdtBalance = allBalances[0].details.find(
      (bal) => bal.ccy === 'USDT',
    );
    console.log('USDT available:', usdtBalance?.availBal);
  } catch (e) {
    console.error('request failed: ', e);
  }
})();
OKX credentials are region-specific. Keys created on www.okx.com (Global) will not work with my.okx.com (EEA) or app.okx.com (US). See Authentication for how to set the market option.
4

Place an order

Once you have a funded account, you can submit orders with client.submitOrder(). The example below places a market buy for BTC-USDT.
import { RestClient } from 'okx-api';

const client = new RestClient({
  apiKey: process.env.API_KEY_COM,
  apiSecret: process.env.API_SECRET_COM,
  apiPass: process.env.API_PASS_COM,
});

(async () => {
  try {
    const order = {
      instId: 'BTC-USDT',
      ordType: 'market',
      side: 'buy',
      sz: '0.002',
      tdMode: 'cash',
      tgtCcy: 'base_ccy',
    };

    const buyResult = await client.submitOrder(order);
    console.log('buy order result: ', buyResult);

    const sellResult = await client.submitOrder({
      instId: 'BTC-USDT',
      ordType: 'market',
      side: 'sell',
      sz: '0.002',
      tdMode: 'cash',
      tgtCcy: 'base_ccy',
    });
    console.log('sell order result: ', sellResult);
  } catch (e) {
    console.error('request failed: ', e);
  }
})();
These examples place real orders on your live account. Use demoTrading: true in your client options while testing. See Authentication for details.
5

Subscribe to real-time data via WebSocket

WebsocketClient handles connection management, heartbeats, automatic reconnection, and resubscription for you. Public channels require no credentials.
import { WebsocketClient } from 'okx-api';

const wsClient = new WebsocketClient({});

// Incoming market data arrives on the 'update' event
wsClient.on('update', (data) => {
  console.log('ws update:', JSON.stringify(data));
});

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

// Subscription confirmations and auth replies arrive on 'response'
wsClient.on('response', (data) => {
  console.log('ws response:', JSON.stringify(data, null, 2));
});

wsClient.on('reconnect', ({ wsKey }) => {
  console.log('ws automatically reconnecting....', wsKey);
});

wsClient.on('reconnected', (data) => {
  console.log('ws has reconnected', data?.wsKey);
});

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

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

// Or subscribe to multiple channels in a single call
wsClient.subscribe([
  { channel: 'instruments', instType: 'SPOT' },
  { channel: 'trades', instId: 'BTC-USDT' },
  { channel: 'books', instId: 'BTC-USDT' },
]);
The client will open a connection automatically when you call subscribe(). If the connection drops, it will reconnect and resubscribe without any extra code on your side.
6

Subscribe to private WebSocket channels

Pass your credentials in the accounts array to enable private channels such as account, positions, and orders.
import { WebsocketClient } from 'okx-api';

const wsClient = new WebsocketClient({
  accounts: [
    {
      apiKey: process.env.API_KEY_COM,
      apiSecret: process.env.API_SECRET_COM,
      apiPass: process.env.API_PASSPHRASE_COM,
    },
  ],
});

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

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

// Authentication happens automatically when subscribing to private channels
wsClient.subscribe([
  { channel: 'account' },
  { channel: 'positions', instType: 'ANY' },
  { channel: 'orders', instType: 'ANY' },
]);

Next steps

Authentication

Learn how to create OKX API keys, pass credentials, and configure region and demo trading mode.

REST Client

Browse every available method, request type, and response shape.

WebSocket Client

Understand WebSocket events, reconnection behavior, and private channel authentication.

WebSocket API Client

Place orders and manage positions over a persistent WebSocket connection using a REST-like interface.

Build docs developers (and LLMs) love