OKX API in Node.js: ticker, order book, candles and WebSocket with the OKX SDK
The OKX API (v5) serves spot, margin, futures, perpetual swaps and
options over REST at https://www.okx.com/api/v5/ and over
WebSockets at wss://ws.okx.com:8443/ws/v5/public (market
data), /ws/v5/private (account and orders) and
/ws/v5/business (candles and some other channels). This
guide reads public spot market data from Node.js with okx-api, an open-source
TypeScript SDK for the OKX REST APIs, WebSockets and WebSocket API. The
first script needs no API key.
Install
npm install okx-api
Node.js 22 or newer works for these examples. The package ships ES modules, CommonJS and TypeScript declarations.
OKX API REST and WebSocket in one script
Save this as okx-market.mjs:
import { RestClient, WebsocketClient } from 'okx-api';
const client = new RestClient();
// Instrument rules: tick size, lot size and minimum order size
const [inst] = await client.getInstruments({ instType: 'SPOT', instId: 'BTC-USDT' });
console.log('instId:', inst.instId, 'tickSz:', inst.tickSz, 'lotSz:', inst.lotSz, 'minSz:', inst.minSz);
// Last price, best bid and best ask
const [ticker] = await client.getTicker({ instId: 'BTC-USDT' });
console.log('last:', ticker.last, 'bid:', ticker.bidPx, 'ask:', ticker.askPx);
// Top of the order book: [price, size, deprecated, number of orders]
const [book] = await client.getOrderBook({ instId: 'BTC-USDT', sz: '3' });
console.log('best bid:', book.bids[0], 'best ask:', book.asks[0]);
// Hourly candles, newest first: [ts, open, high, low, close, vol, volCcy, volCcyQuote, confirm]
const candles = await client.getCandles({ instId: 'BTC-USDT', bar: '1H', limit: '2' });
console.log('latest candle:', candles[0]);
// Live ticker over the public WebSocket (wss://ws.okx.com:8443/ws/v5/public)
const ws = new WebsocketClient();
let updates = 0;
ws.on('update', (msg) => {
if (msg.arg?.channel !== 'tickers') return;
console.log('ws ticker:', msg.data[0].instId, msg.data[0].last);
if (++updates === 3) ws.closeAll();
});
ws.on('exception', (err) => console.error('ws error:', err));
ws.subscribe({ channel: 'tickers', instId: 'BTC-USDT' });
Run it with node okx-market.mjs.
Example output (the SDK also prints its own connection log lines, left out here):
instId: BTC-USDT tickSz: 0.1 lotSz: 0.00000001 minSz: 0.00001
last: 52206.1 bid: 52199.2 ask: 52199.3
best bid: [ '52202.4', '0.00004151', '0', '1' ] best ask: [ '52202.5', '0.14825128', '0', '3' ]
latest candle: [
'1796385600000',
'51119.1',
'52298.2',
'51065.1',
'52235.2',
'515.54766552',
'26602153.648708515',
'26602153.648708515',
'0'
]
ws ticker: BTC-USDT 52197
ws ticker: BTC-USDT 52198.8
ws ticker: BTC-USDT 52192.2
Prices will differ on each run.
OKX instrument IDs, arrays and candle order
- Instrument IDs use a hyphen. Spot is
BTC-USDT, a perpetual swap isBTC-USDT-SWAPand a dated future adds the expiry, for exampleBTC-USDT-261225. - Responses are arrays. The SDK returns the
dataarray from each OKX reply, so a single ticker or instrument is the first item. - Numbers are strings. Round prices to
tickSzand sizes tolotSzfromgetInstruments(), and keep each order at or aboveminSz. - Candles are newest first. Each candle is
[ts, open, high, low, close, vol, volCcy, volCcyQuote, confirm];confirmis'0'while the bar is still open and'1'once it has closed. - The WebSocket client picks the right URL. Public, private and business channels live on different connections. The client routes each subscription, sends the ping OKX expects, reconnects after a drop and resubscribes your channels.
Authenticated OKX API calls
Private endpoints need three values from the API key page: the key,
the secret and the passphrase you chose when you created the key. Each
request is signed with HMAC SHA256 over the timestamp, method, request
path and body, then sent with the OK-ACCESS-* headers. The
SDK does that for you:
import { RestClient } from 'okx-api';
const client = new RestClient({
apiKey: process.env.OKX_API_KEY,
apiSecret: process.env.OKX_API_SECRET,
apiPass: process.env.OKX_API_PASSPHRASE,
});
const [account] = await client.getBalance();
console.log(account.details.map((d) => [d.ccy, d.availBal]));
The passphrase is the API key passphrase, not your account password.
Keep keys in environment variables on a server you control, enable only
the permissions you need and bind the key to your server IP. For demo
trading keys, pass demoTrading: true to the client.
More OKX API examples
- OKX JavaScript SDK overview, tutorial and examples: https://siebly.io/sdk/okx/javascript
- OKX SDK documentation: https://sieblyio.github.io/docs/okx/
- npm package: https://www.npmjs.com/package/okx-api
- Coinbase WebSocket in Node.js on this site: coinbase-websocket-nodejs