Integrating with the OKX v5 API opens powerful opportunities for traders, developers, and automated systems to access real-time market data, execute trades, manage accounts, and more. However, even experienced users often encounter common hurdles—ranging from authentication errors to incorrect timestamp formats—that can disrupt workflows.
This comprehensive guide walks you through essential setup requirements, frequent error codes, troubleshooting strategies, and best practices for seamless interaction with the OKX v5 API. Whether you're building a trading bot or analyzing candlestick data, this resource ensures you avoid pitfalls and optimize your integration.
Understanding OKX v5 API Request Structure
All authenticated requests to the OKX v5 API require specific headers to validate identity and ensure security. These headers must be included for private endpoints (i.e., those requiring user authorization).
Required Headers for Authenticated Requests
OK-ACCESS-KEY: Your unique API key string.OK-ACCESS-SIGN: A Base64-encoded HMAC SHA256 signature generated using your secret key.OK-ACCESS-TIMESTAMP: The request time in ISO format (UTC), e.g.,2020-12-08T09:08:57.715Z.OK-ACCESS-PASSPHRASE: The passphrase set when creating the API key.
Note: Public endpoints (like market data) do not require authentication headers.
All request bodies must be valid JSON with the content type application/json.
👉 Discover how to securely generate your API credentials and start integrating today.
How to Generate the OK-ACCESS-SIGN Signature
The signature is critical for verifying each request. It is created using the following formula:
sign = Base64(HMAC_SHA256(timestamp + method + requestPath + body, SecretKey))Components Explained
- timestamp: Must match the
OK-ACCESS-TIMESTAMPheader value in ISO format. - method: Uppercase HTTP method (
GET,POST, etc.). - requestPath: Full path of the endpoint (e.g.,
/api/v5/account/balance). - body: Stringified JSON body (omit if empty, as with most GET requests).
- SecretKey: The private key issued during API setup.
Example: Signing a GET Request
For a request to:
GET /api/v5/trade/order?ordId=2510789768709120&instId=BTC-USDTThe signing string becomes:
"2020-12-08T09:08:57.715ZGET/api/v5/trade/order?ordId=2510789768709120&instId=BTC-USDT"No body is included in GET requests.
Example: Signing a POST Request
For a POST request to /api/v5/account/set-leverage with body:
{"instId":"BTC-USDT","lever":"5","mgnMode":"isolated"}The signing string becomes:
"2020-12-08T09:08:57.715ZPOST/api/v5/account/set-leverage{\"instId\":\"BTC-USDT\",\"lever\":\"5\",\"mgnMode\":\"isolated\"}"Use json.dumps() without extra whitespace to ensure consistency between signature and actual payload.
Frequently Encountered Errors & Solutions
Even small mistakes can lead to failed requests. Below are some of the most common issues developers face—with clear fixes.
❌ "Bad Request" When Fetching Historical Candles
Request:
GET /api/v5/market/history-candles?instId=BTC-USDT-210924&bar=5m&after=2021-08-03T01:14:22.934ZResponse:
{"code": "-1", "msg": "Bad Request", "data": null}Cause: Incorrect timestamp format in after parameter.
While the OK-ACCESS-TIMESTAMP uses ISO format, the after parameter expects Unix timestamps in milliseconds (e.g., 1597026383085).
✅ Fix:
GET /api/v5/market/history-candles?instId=BTC-USDT-210924&bar=5m&after=1597026383085Always verify which timestamp format an endpoint expects—ISO vs Unix milliseconds.
❌ "OK-ACCESS-KEY can't be empty"
Error Response:
{"msg": "Request header \"OK-ACCESS-KEY\" can't be empty.", "code": "50103"}Cause: Missing or malformed OK-ACCESS-KEY header.
This occurs when making private requests (e.g., fetching trade fees or account balance) without including the required API key.
✅ Solution:
Ensure the header is correctly set:
OK-ACCESS-KEY: your_api_key_hereDouble-check for typos and confirm that the endpoint requires authentication (private: 1).
❌ "Please add a withdrawal address"
Error Response:
{"code": "58203", "data": [], "msg": "Please add a withdrawal address."}Cause: Attempting internal transfers between OKX accounts where the recipient isn't in the sender’s address book—or requires manual verification.
✅ Solution:
Add the recipient account as a whitelisted withdrawal address with no verification required.
If the address exists but still fails:
{"code": "58207", "msg": "Withdrawal failed due to address error"}→ Recheck settings and disable 2FA/email confirmation for that address if possible.
👉 Learn how to securely manage API permissions and withdrawal settings within your dashboard.
❌ Persistent Positions After Closing (Full vs Isolated Margin)
After closing isolated margin positions, some users report that positions still appear in responses from:
GET /api/v5/account/positionsEven though the position is closed, it may remain visible—especially if both cross-margin and isolated-margin trading were used on the same instrument.
✅ Workaround:
Wait up to 24 hours for stale data to clear. Full-margin positions typically appear after isolated ones in the response list. Avoid manual interference unless necessary.
Common Error Code Reference
Below is a curated list of frequently seen error codes across general and API-specific categories.
General System Errors
| Error Message | Code | Meaning |
|---|---|---|
| Operation successful | 0 | Request processed successfully |
| Body cannot be empty | 50000 | Missing required request body |
| Invalid JSON data | 50002 | Malformed JSON payload |
| Invalid Content-Type | 50006 | Must use application/json |
| Rate limit exceeded | 50011 | Too many requests in a short time |
| System busy | 50013 | Temporary overload; retry later |
| Mandatory parameter missing | 50014 | One or more required fields not provided |
Authentication & API Errors
| Error Message | Code | Cause |
|---|---|---|
| API frozen | 50100 | Contact support |
| APIKey environment mismatch | 50101 | Using testnet key on mainnet or vice versa |
| Timestamp expired | 50102 | Clock skew >30 seconds |
| OK-ACCESS-KEY missing | 50103 | Header not sent |
| Invalid signature | 50113 | Mismatched HMAC-SHA256 calculation |
Ensure your system clock is synchronized using NTP to prevent timestamp-related failures.
FAQ: Quick Answers to Common Questions
Q: What timestamp format does OKX v5 API use?
A: The OK-ACCESS-TIMESTAMP header uses ISO 8601 format (UTC), while certain parameters like after or before expect Unix time in milliseconds.
Q: Can I use dictionaries directly in POST requests?
A: No. Always convert the body to a JSON string using json.dumps() before sending. Unlike some APIs (e.g., Binance), OKX requires raw string payloads.
Q: Why do I get “Invalid signature” even with correct inputs?
A: Double-check that there’s no extra whitespace in the body, and that the exact same string used for signing is sent in the request. Also ensure UTC time alignment.
Q: How often can I make API requests?
A: Rate limits vary by endpoint. Public endpoints allow higher frequency; private ones are stricter. Exceeding limits returns code 50011.
Q: Can I transfer funds between subaccounts via API?
A: Yes, but only if the destination subaccount is added as a trusted withdrawal address without verification enabled.
Q: Does OKX support WebSockets for real-time data?
A: Yes. Use the WebSocket API for live order books, trades, and balance updates—more efficient than polling REST endpoints.
👉 Explore advanced features like WebSocket streaming and algorithmic order execution.
Final Tips for Smooth Integration
To maximize reliability and performance when working with the OKX v5 API:
- ✅ Always use UTC time and synchronize your system clock.
- ✅ Validate JSON structure before sending.
- ✅ Handle pagination properly using
before,after, andlimitparameters. - ✅ Store your
SecretKeyandPassphrasesecurely—never expose them in client-side code. - ✅ Test thoroughly in demo (sandbox) mode before going live.
By mastering these fundamentals, you’ll minimize errors and build robust applications capable of high-frequency trading, portfolio analysis, or automated risk management—all powered by real-time blockchain and market data.
Whether you're troubleshooting signature mismatches or decoding obscure error codes, this guide equips you with the knowledge to navigate the OKX v5 API confidently.
Core Keywords:
OKX v5 API, API authentication, HMAC SHA256 signature, timestamp format, error code 50103, withdrawal address setup, rate limiting, REST API integration