---
title: "OKX Perpetual Futures API Node.js"
description: "A professional guide to the OKX Perpetual Futures API Node.js. Learn to build a robust system with awaitable WebSockets and type-safe requests using okx-api."
canonical: "https://siebly.io/blog/okx-perpetual-futures-api-nodejs-a-professional-engineering-guide"
---

# OKX Perpetual Futures API Node.js: A Professional Engineering Guide

A professional guide to the OKX Perpetual Futures API Node.js. Learn to build a robust system with awaitable WebSockets and type-safe requests using okx-api.

## Technical Disclaimer

These articles are software engineering references for exchange API integrations. They are not financial, investment, legal, tax, compliance, or trading advice. Use public data, demo, testnet, or paper workflows first. Keep API credentials out of frontend code and disable withdrawal permissions for automation keys.

## Overview {#overview}

Relying solely on REST for high-frequency execution is no longer the standard for a professional desk. Most engineers building an OKX Perpetual Futures API Node.js integration hit the same walls: fragmented V5 docs, request signing, and home-grown WebSocket reconnect loops. You want a WebSocket order to behave like an awaitable promise, not a loose event. That is what keeps local state in sync when the book is moving fast.

Managing raw signatures and timestamps yourself is a waste of time when you should be writing execution logic. This guide uses the okx-api package as the implementation layer. You will set up a TypeScript client, configure the V5 unified account for swaps, and place orders through WebsocketAPIClient. Rate limiting is still your job. The SDK does the transport and auth. We start with the Node.js environment and OKX V5 endpoints.

## Key Takeaways {#key-takeaways}

- Understand the OKX V5 unified account, including all four account modes, and set the correct regional `market` value for Global, EEA, and US.
- Cut signing boilerplate with okx-api. It handles HMAC-SHA256 auth and TypeScript request shapes.
- Configure swap risk before you trade: `setLeverage`, `setPositionMode`, and margin mode on the instrument.
- Place and cancel orders over a persistent socket with WebsocketAPIClient. Methods such as `submitNewOrder` return promises.
- Test on demo trading with `demoTrading: true`. Build your own rate-limit logic. The SDK does not throttle for you.



## Navigating OKX V5 Perpetual Futures API Architecture {#navigating-okx-v5-perpetual-futures-api-architecture}

The OKX V5 API is the current interface for the unified account. For an OKX Perpetual Futures API Node.js integration, this architecture is the starting point. V5 does not split spot and derivatives into separate accounts. Perpetual futures use instrument IDs with a `-SWAP` suffix, for example `BTC-USDT-SWAP`. Dated futures put an expiry in the ID instead.

### Regional Domain and Endpoint Configuration {#regional-domain-and-endpoint-configuration}

OKX routes traffic by registration region. Pick the wrong host and private calls fail auth.

The [okx-api](/sdk/okx/javascript) `market` option maps to those hosts:

- Global (default): `market: 'GLOBAL'` or omit it.

Those values are uppercase. `market: 'eea'` is not a valid SDK option.

Demo trading is a separate flag, not a market. Do not set `market: 'demo'`. The client throws if you do. Use `demoTrading: true`. That adds the `x-simulated-trading: 1` header on REST and switches WebSockets to the demo endpoints.

### Understanding the Unified Account Mode {#understanding-the-unified-account-mode}

V5 is built around Unified Account. Margin can be shared across perpetuals, spot, and options, depending on the mode. There are four modes, not three:

- Spot mode (`acctLv: '1'`): spot and options buy-only. No futures, no margin, no swaps.
- Futures mode (`acctLv: '2'`): single-currency margin. You can trade swaps. Cross margin is per settlement currency.
- Multi-currency margin (`acctLv: '3'`): all instruments share margin. Assets are valued in USD for collateral.
- Portfolio margin (`acctLv: '4'`): risk-based margin across the book. Aimed at professional desks.

Read the mode with `getAccountConfiguration()` before you send a swap order. Spot mode will reject it. This check belongs in startup, not after the first fill fails.

Private REST calls need an API key, secret, and passphrase. The sign string is `timestamp + method + requestPath + body`, hashed with HMAC-SHA256 and base64-encoded. okx-api builds that for you, including the `OK-ACCESS-PASSPHRASE` header.

## Configuring the okx-api SDK for Node.js {#configuring-the-okx-api-sdk-for-nodejs}

The okx-api package is the implementation layer for an OKX Perpetual Futures API Node.js integration. It signs requests, keeps timestamps in sync, and types the V5 shapes so you are not hand-writing every path.

### Installation and Project Setup {#installation-and-project-setup}

Install the package:

```bash title="Imported example"
npm install okx-api
```

It ships TypeScript definitions for V5 requests and responses. A public call is enough to prove the host is reachable before you touch private endpoints.

```ts title="Imported example"
import { RestClient } from "okx-api";

const client = new RestClient({
  // Global users can omit market. Default is www.okx.com.
  // market: 'EEA', // EEA users (my.okx.com / eea.okx.com)
  // market: 'US',  // US users (app.okx.com / us.okx.com)
});

const ticker = await client.getTicker({ instId: "BTC-USDT-SWAP" });
console.log(ticker);
```

`getTicker` is public. No keys required.

### Secure Authentication and Secret Handling {#secure-authentication-and-secret-handling}

Do not hardcode the API key, secret, or passphrase. Load them from the environment or a secret manager. In the OKX dashboard, turn off withdrawal on automation keys and pin them to known IPs. Align internal controls with [FINRA Algorithmic Trading Supervision](https://www.finra.org/rules-guidance/key-topics/algorithmic-trading) if that applies to your desk.

RestClient takes `apiKey`, `apiSecret`, and `apiPass`. `market` is optional. Only set it when you are not on Global.

```ts title="Imported example"
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_PASSPHRASE_COM,
  demoTrading: true,
});
```

For a walkthrough of these patterns on futures workflows, see the [okx-api tutorial](/sdk/okx/javascript/tutorial).

The SDK signs and sends. It does not throttle. Successful RestClient calls return the unwrapped `data` array, not the raw Axios response, so you will not see `x-ratelimit-remaining` on the value you `await`. Build your own limiter. Hitting the cap can mean a temporary ban. Keep client construction in one module so REST and WebSocket share the same credentials and region.

## Engineering Perpetual Futures Workflows: Leverage and Margin {#engineering-perpetual-futures-workflows-leverage-and-margin}

Connection setup is not enough. Leverage and margin on OKX are per instrument. Set them before the first order so size and liquidation math match the account you think you have.

### Managing Leverage and Margin Modes {#managing-leverage-and-margin-modes}

Use `setLeverage` from the [okx-api](/sdk/okx/javascript) RestClient. Pass the swap `instId`, the leverage as a string, and `mgnMode` as `cross` or `isolated`.

```ts title="Imported example"
const leverage = await client.setLeverage({
  instId: "BTC-USDT-SWAP",
  lever: "5",
  mgnMode: "cross",
});
console.log(leverage);
```

Isolated caps loss to that position. Cross shares collateral across the account. Position mode is a second switch:

- `long_short_mode` (hedge): you can hold long and short on the same swap.
- `net_mode` (one-way): a sell reduces an existing long.

```ts title="Imported example"
const posMode = await client.setPositionMode({
  posMode: "net_mode",
});
console.log(posMode);
```

In hedge mode, orders need `posSide: 'long'` or `posSide: 'short'`. In net mode you omit it. Check the response before you send size.

A REST market order on the swap looks like this (from the commented SWAP path in the SDK examples):

```ts title="Imported example"
const order = await client.submitOrder({
  instId: "BTC-USDT-SWAP",
  tdMode: "cross",
  ordType: "market",
  side: "buy",
  sz: "0.01",
});
console.log(order);
```

`tdMode: 'cash'` is spot. Swaps use `cross` or `isolated`.

### Handling Position and Account State {#handling-position-and-account-state}

Keep a local picture of the unified account or you will invent ghost positions. Polling is fine for startup. Live trading should follow private WebSocket events.

```ts title="Imported example"
const config = await client.getAccountConfiguration();
console.log("account level", config[0]?.acctLv, "posMode", config[0]?.posMode);

const balance = await client.getBalance({ ccy: "USDT" });
const positions = await client.getPositions({ instType: "SWAP" });
```

The method is `getBalance`, not `getAccountBalance`. `acctLv` is `'1'` through `'4'` as listed above.

Watch margin ratio and equity. If equity cannot cover initial margin, OKX rejects the order. For a higher-level cache of account and position state, see the [Siebly AI exchange state framework](/ai/exchange-state).



## Executing Low-Latency Trades via Awaitable WebSockets {#executing-low-latency-trades-via-awaitable-websockets}

REST is fine for config and snapshots. Execution belongs on the WebSocket API so you are not paying an HTTP handshake per order. Keep one TCP connection and place, amend, and cancel on it.

### The Awaitable WebSocket Pattern {#the-awaitable-websocket-pattern}

Raw sockets push events. You then have to match request IDs yourself. okx-api wraps that in WebsocketAPIClient. Each call returns a promise that resolves when OKX sends the matching response.

Use the typed helpers (`submitNewOrder`, `cancelOrder`, `amendOrder`, `submitMultipleOrders`). `sendWSAPIRequest` lives on WebsocketClient. WebsocketAPIClient already calls it for you.

```ts title="Imported example"
import { WebsocketAPIClient } from "okx-api";

const wsApi = new WebsocketAPIClient({
  demoTrading: true,
  accounts: [
{
apiKey: process.env.API_KEY_COM,
apiSecret: process.env.API_SECRET_COM,
apiPass: process.env.API_PASSPHRASE_COM,
},
  ],
});

const result = await wsApi.submitNewOrder({
  instId: "BTC-USDT-SWAP",
  tdMode: "cross",
  side: "buy",
  ordType: "market",
  sz: "0.01",
});
console.log(result);
```

Credentials go in `accounts`, not as top-level `apiKey` on WebsocketAPIClient. You can call `connectWSAPI()` early if you want the socket warm before the first order. Otherwise the client opens it on demand.

### Reliable WebSocket Stream Management {#reliable-websocket-stream-management}

The SDK already heartbeats the socket, tears down a dead connection, reconnects, re-auths, and resubscribes. You do not need to send manual pings on top of that. Hook the client events so your process knows when the link bounced.

Private fills and balances come from WebsocketClient (the stream client), not from WebsocketAPIClient (the order-entry client). Subscribe to account and position channels:

```ts title="Imported example"
import { WebsocketClient } from "okx-api";

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

ws.on("update", (data) => {
  console.log("ws update", JSON.stringify(data));
});
ws.on("reconnect", ({ wsKey }) => {
  console.log("reconnecting", wsKey);
});
ws.on("reconnected", (data) => {
  console.log("reconnected", data?.wsKey);
});
ws.on("exception", (data) => {
  console.error("ws exception", data);
});

ws.subscribe([
  { channel: "account" },
  { channel: "positions", instType: "ANY" },
]);
```

That is the same pattern as the SDK demo-trading example. For reconnect architecture notes, see the [Siebly guide on WebSocket reconnection](/blog). Full client docs: [OKX Node.js SDK documentation](/sdk/okx/javascript).

WebSocket order entry shares OKX trading rate limits with REST. The SDK will not queue or delay those calls for you.

## Best Practices for Production OKX Integrations {#best-practices-for-production-okx-integrations}

Live traffic needs more than a working script. Plan for disconnects, exchange limits, and bad fills. The patterns below are the minimum safety layer around V5.

### Rate Limiting and Throttling Strategies {#rate-limiting-and-throttling-strategies}

okx-api does not rate-limit. A token bucket or priority queue in your process should wrap both RestClient and WebsocketAPIClient.

Limits differ by endpoint. Place, cancel, and amend are commonly 60 requests per 2 seconds per instrument. Balance and position reads are tighter (often 10 per 2 seconds). Public unauthenticated limits are per IP. Private limits are per user. WS and REST trading share the same bucket.

Do not expect `x-ratelimit-remaining` on the object RestClient returns. Successful calls unwrap to `data` only. If you need exchange-side usage for orders, call `getAccountRateLimit()`.

### Safety Boundaries and Testing {#safety-boundaries-and-testing}

Do not ship new execution to live first. Demo trading mirrors V5 with virtual funds.

```ts title="Imported example"
const demo = new RestClient({
  apiKey: process.env.API_KEY_COM,
  apiSecret: process.env.API_SECRET_COM,
  apiPass: process.env.API_PASSPHRASE_COM,
  demoTrading: true,
});
```

That flag is what attaches `x-simulated-trading: 1`. There is no `market: 'demo'`. Use it to exercise partial fills, rejects, and reconnects. For how to split these pieces in a Node.js desk, see [Siebly.io algorithmic trading architecture](/blog/algorithmic-trading-system-architecture-in-nodejs-a-2026-engineering-guide).

Keep withdrawal off on bot keys. Log every request and response you care about for post-trade review. Combined with the [OKX Node.js SDK](/sdk/okx/javascript), that is a workable production baseline.

## Optimizing Your OKX Execution Infrastructure {#optimizing-your-okx-execution-infrastructure}

A working OKX Perpetual Futures API Node.js stack is REST for setup, WebSockets for state, and WebsocketAPIClient for order entry. Get the region right, read `acctLv` before you trade swaps, and use `demoTrading: true` until the path is boring.

[Get started with the Siebly OKX Node.js SDK](/sdk/okx/javascript). It tracks V5. You still own throttling. Start on demo, then move the same client config to live.

## Frequently Asked Questions {#frequently-asked-questions}

### How do I handle OKX V5 API rate limits in Node.js? {#how-do-i-handle-okx-v5-api-rate-limits-in-node-js}

You handle them. okx-api does not throttle. RestClient also does not return rate-limit headers on success, because it returns the unwrapped `data` payload. Put a token bucket in front of RestClient and WebsocketAPIClient. Order place/cancel/amend is often 60 per 2 seconds. Reads such as balance are often 10 per 2 seconds. `getAccountRateLimit()` reports order-entry usage from the exchange.

### What is the difference between OKX REST and WebSocket APIs for futures? {#what-is-the-difference-between-okx-rest-and-websocket-apis-for-futures}

REST is request-response over HTTP. Use it for leverage, position mode, account config, and snapshots. The WebSocket API keeps a socket open for place, amend, and cancel. WebsocketAPIClient makes those operations look like REST (`await submitNewOrder(...)`) without the handshake cost. Market data and account pushes use WebsocketClient subscriptions.

### Can I use the okx-api SDK with TypeScript? {#can-i-use-the-okx-api-sdk-with-typescript}

Yes. The package is TypeScript-first. Request and response types cover V5, including `instId`, `mgnMode`, `tdMode`, and leverage fields. JavaScript works too via `require('okx-api')`.

### How do I securely store my OKX API passphrase in a Node.js app? {#how-do-i-securely-store-my-okx-api-passphrase-in-a-node-js-app}

Environment variables or a secret manager. RestClient reads `apiPass` at runtime. Websocket clients take the same value inside `accounts[].apiPass`. Disable withdrawals on those keys and restrict by IP.

### Does the Siebly OKX SDK support demo trading? {#does-the-siebly-okx-sdk-support-demo-trading}

Yes. Set `demoTrading: true` on RestClient, WebsocketClient, and WebsocketAPIClient. That is the supported path. `market: 'demo'` throws. Demo REST requests get `x-simulated-trading: 1` automatically. Demo keys are separate from live keys in the OKX UI.

### What is the best way to manage WebSocket reconnections for OKX? {#what-is-the-best-way-to-manage-websocket-reconnections-for-okx}

Let the SDK do it. It heartbeats, reconnects, re-authenticates, and resubscribes. Listen for `reconnect`, `reconnected`, and `exception` so your app can pause orders while the socket is down. Do not add a second ping loop on the same connection.

### How do I set leverage for OKX perpetual futures via the API? {#how-do-i-set-leverage-for-okx-perpetual-futures-via-the-api}

Call `setLeverage` with `instId` (for example `BTC-USDT-SWAP`), `lever` as a string, and `mgnMode` of `cross` or `isolated`. Leverage is per instrument, not account-wide. In hedge mode you may also pass `posSide`. Confirm the response, then place the order.

### Why should I use the WebsocketAPIClient instead of standard REST? {#why-should-i-use-the-websocketapiclient-instead-of-standard-rest}

Lower latency on place, amend, and cancel. You keep async/await, but the call rides an already-open socket. Use RestClient for account setup. Use WebsocketClient to subscribe to fills and positions. Use WebsocketAPIClient when the hot path is order entry.

Disclaimer

*Technical and legal disclaimer: Siebly.io provides software development tools, SDKs, documentation, and educational engineering content for crypto exchange API integrations. This content is for software engineering education only and is not financial, investment, legal, tax, accounting, compliance, or trading advice.

Nothing in this article is a recommendation, invitation, or inducement to buy, sell, hold, trade, long, short, or allocate to any cryptoasset, exchange product, strategy, bot, or automated workflow. Examples, code patterns, simulations, backtests, and architecture diagrams are illustrative only and must not be treated as trading signals, investment recommendations, or evidence of future performance.

Cryptoasset markets are high risk and volatile. If you choose to build or operate exchange-connected software, you are responsible for your own legal, regulatory, tax, security, exchange-account, API-key, and risk-management obligations. Use public data, testnet, demo, dry-run, or paper-trading workflows before any live execution. Keep API keys server-side, use least-privilege permissions, and never enable withdrawals for automation keys unless you fully understand and accept the risks.

Siebly.io is not an exchange, custodian, investment adviser, trading-signal provider, or managed trading service. Official exchange documentation remains the source of truth for exchange-specific rules, API behavior, and terms of use. Use of Siebly.io content and software is also subject to the Siebly.io terms and conditions.*

## Related articles

- [Bybit Linear Perpetual API in Node.js: Professional Engineering Guide 2026](/blog/bybit-linear-perpetual-api-in-nodejs-professional-engineering-guide-2026)
- [Bybit Inverse Perpetual API Node.js: A Production Engineering Guide](/blog/bybit-inverse-perpetual-api-nodejs-a-production-engineering-guide)
- [OKX API Wrapper JavaScript: A Production Engineering Guide for 2026](/blog/okx-api-wrapper-javascript-a-production-engineering-guide-for-2026)


## Related Siebly Resources

- [OKX JavaScript SDK](/sdk/okx/javascript)
- [Siebly SDK directory](/sdk)
- [Siebly AI Prompt Framework & Skills](/ai)
- [Exchange State Management](/ai/exchange-state)
- [Runnable exchange API examples](/examples)
