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:
- API Key: Your unique identifier for API access.
- Secret Key: Used to sign requests; never shared.
- Passphrase: A user-defined password used during authentication.
🔐 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:
Read: View account balances, order history, and bills.Trade: Place, amend, and cancel orders; manage positions.Withdraw: Initiate fund withdrawals (use with extreme caution).
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:
OK-ACCESS-KEY: Your API key.OK-ACCESS-SIGN: Base64-encoded HMAC-SHA256 signature.OK-ACCESS-TIMESTAMP: UTC timestamp in ISO format (e.g.,2020-12-08T09:08:57.715Z).OK-ACCESS-PASSPHRASE: The passphrase set during key creation.
How to Generate the Signature
The OK-ACCESS-SIGN header is created as follows:
- Concatenate:
timestamp + method + requestPath + body - Use your SecretKey to sign the string using HMAC-SHA256.
- 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
- Public Channels: No authentication needed (e.g., tickers, order books).
- Private Channels: Require login (e.g., account, orders).
Use these URLs:
- Public:
wss://wseea.okx.com:8443/ws/v5/public - Private:
wss://wseea.okx.com:8443/ws/v5/private
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:
- Tickers
- K-lines (candlesticks)
- Order book
- Mark price
Private channels include:
- Account updates
- Order status
- Position changes
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:
- Spot Mode
- Futures Mode
- Multi-currency Margin
- Portfolio Margin
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:
- REST:
https://eea.okx.com - WebSocket:
wss://wseeapap.okx.com:8443/ws/v5/public
Enable demo mode by adding the header:
x-simulated-trading: 1To get started:
- Log into OKX
- Go to Trade → Demo Trading
- Create a Demo API Key
- 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: 1597026383085If the server time exceeds expTime, the request is discarded. Supported on:
- Place order
- Amend order
- Batch operations
Useful for high-frequency strategies where latency matters.
Rate Limiting and Performance Optimization
OKX applies rate limits to ensure platform stability.
Key Rules
- REST Public Endpoints: Limited by IP address.
- REST Private Endpoints: Limited by User ID.
- WebSocket: Limits apply per connection or User ID.
- Trading Operations: Shared across REST and WebSocket.
For example:
- Single order placement: 60 requests/2s per instrument.
- Batch orders: Up to 300 orders/2s.
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:
- Sub-account fill ratio: Trade volume ÷ (request count × symbol multiplier)
- 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=SPOTIncludes details like leverage, tick size, lot size, and contract value.
Retrieve Account Balance
Get real-time balance data:
GET /api/v5/account/balanceOptionally filter by currency (ccy=USDT,BTC). Returns equity, available balance, frozen amounts, and unrealized P&L.
Access Transaction History
Two options:
- Last 7 days:
GET /api/v5/account/bills - Last 3 months:
GET /api/v5/account/bills-archive
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=Q4Files are CSV-formatted with full transaction metadata.
Check Trading Fees
Understand cost structure:
GET /api/v5/account/trade-fee?instType=SPOT&instId=BTC-USDTReturns 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:
- Timestamp is within 30 seconds of server time.
- Signature includes exact concatenation: timestamp + method + path + body.
- Secret key and passphrase are correctly entered.
- Content-Type is set to
application/json.
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:
- Immediately upon events (order fill, transfer).
- At regular intervals if no changes (configurable via
updateInterval).
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