OKX API Guide

·

Welcome to the comprehensive OKX V5 API guide, your go-to resource for integrating with one of the most advanced trading platforms in the digital asset space. Whether you're building a high-frequency trading bot, managing market-making strategies, or automating your portfolio, this guide provides everything you need to get started and scale efficiently.

This documentation covers REST and WebSocket APIs designed to support spot, margin, derivatives, and options trading. We'll walk through key setup steps, authentication protocols, rate limits, and best practices—all optimized for reliability and performance.

👉 Generate highly click-attractive anchor text here based on article context and anchor link characteristics; no brand names other than 'OKX' may appear here.

API Key Setup & Security

Creating Your API Key

Before making any authenticated requests, generate your API key via the My API page. Upon creation, securely store the following:

⚠️ Important: The passphrase cannot be recovered if lost. If misplaced, you must create a new key pair.

Assigning Permissions

Each API key can be assigned one or more of the following permissions:

We recommend using separate keys for different functions—especially isolating withdrawal keys—and binding them to specific IP addresses whenever possible.

IP Binding for Enhanced Security

You can bind up to 20 IPv4 or IPv6 addresses (including CIDR ranges) to each API key. This ensures that only trusted servers can use your credentials. Note:


Authentication: REST & WebSocket

REST API Authentication

All private REST endpoints require these headers:

HeaderDescription
OK-ACCESS-KEYYour API key
OK-ACCESS-SIGNBase64-encoded HMAC-SHA256 signature
OK-ACCESS-TIMESTAMPUTC timestamp in ISO format (e.g., 2020-12-08T09:08:57.715Z)
OK-ACCESS-PASSPHRASEThe passphrase set during key creation

How to Generate the Signature

Construct the pre-hash string as follows:

timestamp + method + requestPath + body

Then sign it using HMAC-SHA256 with your Secret Key and encode the result in Base64.

Example (JavaScript):

const signature = CryptoJS.enc.Base64.stringify(
  CryptoJS.HmacSHA256(timestamp + 'GET' + '/api/v5/account/balance', secretKey)
);

Ensure request bodies are JSON-formatted and use the correct HTTP method (GET, POST, etc.).


Real-Time Data with WebSocket

Why Use WebSocket?

WebSocket enables full-duplex communication, allowing real-time data streaming from the server to your application. Benefits include:

Connection Basics

Connection Limits

When limits are exceeded, newer connections may be rejected. Monitor channel-conn-count events to track active subscriptions.

Example:
{"event":"channel-conn-count","channel":"orders","connCount":"2","connId":"abcd1234"}

👉 Generate highly click-attractive anchor text here based on article context and anchor link characteristics; no brand names other than 'OKX' may appear here.

Logging In via WebSocket

To access private channels, authenticate using the login operation:

{
  "op": "login",
  "args": [{
    "apiKey": "your_api_key",
    "passphrase": "your_passphrase",
    "timestamp": "1704876947",
    "sign": "generated_signature"
  }]
}

The signature is created using:

HMAC-SHA256(timestamp + 'GET' + '/users/self/verify', secretKey)

Use Unix timestamps in seconds.


Trading Account Management

Supported Account Modes

Set your preferred mode before trading:

  1. Spot Mode – Simple buy/sell of assets.
  2. Futures Mode – Isolated futures trading.
  3. Multi-Currency Margin – Cross-margin across multiple assets.
  4. Portfolio Margin – Advanced risk-based margining for eligible users.

Adjust settings via OKX Web or App.

Core Endpoints Overview

Below are essential REST endpoints for account interaction:

Get Instruments

Fetch tradable instrument details (rate limit: 20 req/2s).

GET /api/v5/account/instruments?instType=SPOT

Returns critical info like tick size, lot size, max leverage, and contract value.

Get Balance

Retrieve real-time balance data (rate limit: 10 req/2s).

GET /api/v5/account/balance

Includes total equity, available funds, frozen amounts, and unrealized PnL.

Get Transaction History

Access bills from the last 7 days or 3 months:

Filter by type (trade, transfer), currency, or time range.


Order Execution & Management

Placing Orders

Use /api/v5/trade/order to place single orders (60 req/2s). Required parameters:

{
  "instId": "BTC-USDT",
  "tdMode": "cash",
  "side": "buy",
  "ordType": "limit",
  "px": "30000",
  "sz": "0.01"
}

Supports market, limit, post-only, IOC, and FOK orders.

For higher throughput, use /trade/batch-orders to submit up to 20 orders at once (300 orders/2s).

Canceling & Amending Orders

Modify open orders with /amend-order. You can update price (newPx) or size (newSz). Use cxlOnFail=true to auto-cancel if amendment fails.

Cancel individual or multiple orders using their ordId or clOrdId.


Rate Limits & Best Practices

Understanding Rate Limits

Rate limiting is enforced at multiple levels:

VIP5+ users benefit from fill-ratio-based rate limits, where efficient traders receive higher thresholds based on execution quality.

Avoiding Throttling

To maximize throughput:


Frequently Asked Questions (FAQ)

How do I generate a valid API signature?

Concatenate the timestamp, HTTP method, request path, and body (if any), then sign with HMAC-SHA256 using your Secret Key. Encode the output in Base64.

Can I use the same API key for both REST and WebSocket?

Yes. Use the same credentials across both interfaces. However, always bind keys to known IPs and avoid sharing secrets.

What happens when I exceed the WebSocket connection limit?

New subscription requests will be rejected with a channel-conn-count-error. Existing connections usually remain active unless under exceptional load.

How often are account updates pushed via WebSocket?

Account channel updates occur either on event triggers (e.g., order fill) or at regular intervals. Use extraParams.updateInterval=0 to receive only event-driven updates.

Is there a way to increase my rate limit?

Yes. High-volume traders (VIP5+) can qualify for dynamic rate limits based on trade fill ratios. Additionally, spreading requests across sub-accounts increases aggregate capacity.

How do I handle expired API keys?

Regenerate a new key pair from the My API page. Update all services immediately and deactivate old keys to prevent unauthorized access.


With robust infrastructure, granular controls, and real-time capabilities, OKX’s V5 API empowers developers and institutions alike. Start building today—optimize execution speed, enhance security, and unlock scalable trading strategies.

👉 Generate highly click-attractive anchor text here based on article context and anchor link characteristics; no brand names other than 'OKX' may appear here.