OKX API Guide: Complete Integration and Usage Tutorial

·

Welcome to the comprehensive OKX API guide, your go-to resource for integrating with one of the most powerful digital asset trading platforms. Whether you're a developer building algorithmic trading bots, a market maker, or a fintech innovator, OKX offers robust REST and WebSocket APIs designed for speed, reliability, and scalability. This guide walks you through everything from API key setup to advanced usage patterns—ensuring you can build, test, and deploy efficiently.

API Key Creation and Security Best Practices

Before making any authenticated requests, you must generate an API key. Navigate to the My API page to create your credentials. Upon creation, securely store the following:

🔐 Security Note: The passphrase is hashed and cannot be recovered. If lost, you'll need to generate a new API key pair.

API Key Permissions

You can assign one or more of the following permissions when creating your key:

For enhanced security, bind your API key to up to 20 trusted IP addresses (supports IPv4/IPv6 and CIDR notation). This restricts usage to known locations.

👉 Discover how to maximize your trading efficiency using secure API integrations

REST API Authentication Process

All private REST endpoints require four headers:

How to Generate the Signature

The OK-ACCESS-SIGN header is created as follows:

  1. Concatenate: timestamp + method + requestPath + body
  2. Use your SecretKey to sign the string using HMAC-SHA256.
  3. Encode the result in Base64.

Example:

sign = CryptoJS.enc.Base64.stringify(
  CryptoJS.HmacSHA256("2020-12-08T09:08:57.715ZGET/api/v5/account/balance", SecretKey)
)

Ensure request bodies are JSON-formatted with content type application/json.

Real-Time Data with WebSocket API

WebSocket enables full-duplex communication for real-time market data and account updates.

Connection Basics

Use these URLs:

Rate limit: 3 connection attempts per second per IP.

Logging In via WebSocket

Send a login request with your credentials:

{
  "op": "login",
  "args": [{
    "apiKey": "your-api-key",
    "passphrase": "your-passphrase",
    "timestamp": "1704876947",
    "sign": "generated-signature"
  }]
}

The signature follows the same logic as REST but uses a fixed path: /users/self/verify.

Subscribing to Channels

Subscribe to real-time data streams:

{
  "op": "subscribe",
  "args": [{
    "channel": "tickers",
    "instId": "BTC-USDT"
  }]
}

Supported public channels include:

Private channels include:

Unsubscribe using the unsubscribe operation with matching arguments.

Handling Connection Limits

OKX enforces a limit of 30 WebSocket connections per channel per sub-account. Exceeding this results in a channel-conn-count-error. Use the channel-conn-count event to monitor active connections.

Account and Trading Modes

Set your preferred trading mode before executing trades:

Each mode affects margin handling, risk exposure, and available features.

Demo Trading Environment

Test your strategies risk-free using the demo trading API.

Demo URLs:

Enable demo mode by adding the header:

x-simulated-trading: 1

To get started:

  1. Log into OKX
  2. Go to Trade → Demo Trading
  3. Create a Demo API Key
  4. Begin testing

This environment supports most trading functions except deposits, withdrawals, and redemptions.

Managing Request Timeouts

Prevent stale order execution by setting an expiry time (expTime) in milliseconds (Unix timestamp):

expTime: 1597026383085

If the server time exceeds expTime, the request is discarded. Supported on:

Useful for high-frequency strategies where latency matters.

Rate Limiting and Performance Optimization

OKX applies rate limits to ensure platform stability.

Key Rules

For example:

Sub-Account Rate Limits

Each sub-account allows up to 1,000 order requests every 2 seconds. This includes new and amend requests. Exceeding triggers error code 50061.

High-volume traders can distribute load across multiple sub-accounts.

Fill Ratio-Based Tier Upgrades (VIP5+)

Advanced users with high fill ratios receive elevated rate limits. The system evaluates:

  1. Sub-account fill ratio: Trade volume ÷ (request count × symbol multiplier)
  2. Master account aggregated fill ratio

Higher fill efficiency = higher throughput. Updates occur daily at 08:00 UTC with a grace period for downgrades.

Use the GET /account/rate-limit endpoint to check your current tier and performance metrics.

👉 Unlock advanced trading capabilities with optimized API access

Essential REST Endpoints for Developers

Get Available Instruments

Fetch tradable instruments:

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

Includes details like leverage, tick size, lot size, and contract value.

Retrieve Account Balance

Get real-time balance data:

GET /api/v5/account/balance

Optionally filter by currency (ccy=USDT,BTC). Returns equity, available balance, frozen amounts, and unrealized P&L.

Access Transaction History

Two options:

For historical data beyond three months, use:

POST /api/v5/account/bills-history-archive
{
  "year": "2023",
  "quarter": "Q4"
}

Then retrieve the download link via:

GET /api/v5/account/bills-history-archive?year=2023&quarter=Q4

Files are CSV-formatted with full transaction metadata.

Check Trading Fees

Understand cost structure:

GET /api/v5/account/trade-fee?instType=SPOT&instId=BTC-USDT

Returns maker/taker rates based on your fee tier.

Frequently Asked Questions (FAQ)

What is the difference between REST and WebSocket APIs?

REST is ideal for one-off requests like placing an order or checking a balance. WebSocket is best for real-time data such as live price feeds or instant account updates.

How do I troubleshoot authentication errors?

Ensure:

Can I use the same API key for both live and demo trading?

Yes, but avoid using production keys in test environments. Instead, create separate keys for demo use to prevent accidental trades.

How often are account updates pushed over WebSocket?

Account channel updates occur:

Set "updateInterval": "0" for event-driven updates only.

Is there a way to increase my rate limit?

Yes. For non-VIP users, distribute traffic across multiple sub-accounts. VIP5+ users benefit from dynamic increases based on trading efficiency (fill ratio).

What happens if I exceed WebSocket connection limits?

New subscriptions will be rejected with a channel-conn-count-error. Existing connections remain unaffected unless under exceptional conditions. Monitor via the channel-conn-count event.

👉 Start building smarter trading systems today with powerful API tools