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.
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:
- API Key – Your public identifier.
- Secret Key – Used to sign requests; never share this.
- Passphrase – A user-defined password used during authentication.
⚠️ 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:
Read– View account balances, order history, and transaction records.Trade– Place, amend, and cancel orders; manage positions.Withdraw– Initiate fund withdrawals (use with extreme caution).
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:
- Only
tradeandwithdrawoperations are counted as "key usage." - For WebSocket connections, only login attempts count toward key activity.
- Unbound keys with trading permissions should be monitored closely via the Security Center.
Authentication: REST & WebSocket
REST API Authentication
All private REST endpoints require these headers:
| Header | Description |
|---|---|
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
Construct the pre-hash string as follows:
timestamp + method + requestPath + bodyThen 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:
- Ultra-low latency (as low as 2-byte overhead per message).
- Bidirectional data flow without repeated handshakes.
- Efficient resource usage compared to polling REST APIs.
Connection Basics
- Public Channels: Accessible without authentication (e.g., tickers, order books).
- Private Channels: Require login (e.g., account updates, order status).
Connection Limits
- Max 3 connection attempts per second per IP.
- Up to 30 concurrent WebSocket connections per channel per sub-account.
- Subscription/unsubscription allowed up to 480 times per hour per connection.
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"}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:
- Spot Mode – Simple buy/sell of assets.
- Futures Mode – Isolated futures trading.
- Multi-Currency Margin – Cross-margin across multiple assets.
- 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=SPOTReturns 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/balanceIncludes total equity, available funds, frozen amounts, and unrealized PnL.
Get Transaction History
Access bills from the last 7 days or 3 months:
/api/v5/account/bills(last 7 days)/api/v5/account/bills-archive(last 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:
- Per User ID – For private REST calls.
- Per IP – For public endpoints.
- Per Instrument ID – For trading actions (except options).
- Sub-Account Level – Max 1,000 order requests every 2 seconds.
VIP5+ users benefit from fill-ratio-based rate limits, where efficient traders receive higher thresholds based on execution quality.
Avoiding Throttling
To maximize throughput:
- Distribute load across multiple sub-accounts.
- Implement exponential backoff on error code
50011. - Use batch endpoints when placing many orders.
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.