Navigating the OKX API can be a powerful way to automate trading, manage assets, and access real-time market data. Whether you're a developer integrating with OKX for the first time or an experienced trader refining your strategy, understanding key API functionalities is essential. This guide answers the most common questions about OKX API usage, from setup and authentication to error handling and advanced order types.
What Is a Passphrase?
A passphrase is the password you set when creating your API key on OKX. It acts as an additional layer of security during API authentication. Unlike your account password, the passphrase is not recoverable—if lost, you'll need to generate a new API key.
🔑 Important: Store your passphrase securely. Without it, you cannot authenticate API requests, even if you have the API key.
👉 Discover how to securely manage your API credentials today
How Do You Create a Demo Account API Key?
To test strategies without risking real funds, OKX offers a demo trading environment. To use the API with demo trading:
- Log in to your OKX account
- Go to Trade > Demo Trading
- Access Personal Center
- Click Create Demo Account API Key
- Start executing trades via API in the simulated environment
This allows developers and traders to validate their algorithms, bots, or scripts before going live.
Does the API Key Expire?
Yes—under certain conditions.
- Active keys: API keys with trading or withdrawal permissions that are not bound to an IP address will expire after 14 days of inactivity.
- What counts as activity? Any authenticated request to private or account-related endpoints (e.g., checking balance, viewing order history, placing orders).
- Non-expiring keys: Read-only API keys that are IP-restricted or have limited permissions do not expire.
💡 Pro Tip: To keep your key active, schedule regular health-check calls (e.g., balance fetch) every few days.
Can You Place Orders in USDT or Currency Units via the API?
No. For contract trading, the OKX API requires orders to be placed in number of contracts, not in USDT or base currency amounts.
However, you can convert between contract size and fiat/crypto value using the contract value interface:
- Use
ctVal(contract value) to determine how much one contract is worth in the underlying asset. - Multiply by the number of contracts to get total exposure.
For example:
If ctVal = 0.001 BTC and you buy 100 contracts → Total BTC exposure = 0.1 BTCYou can retrieve this data via the Get Trading Product Info endpoint.
How to Calculate Price Change Percentage via API?
The OKX API doesn’t return price change percentage directly, but you can compute it using available market data.
Use this formula:
Price Change % = (Last Price - 24h Open Price) / 24h Open Price × 100%You can obtain both values through the Market Data API:
last: latest traded priceopen24h: opening price 24 hours ago
👉 Learn how to build real-time price trackers with OKX API
Why Do I Get Error "51000 Parameter posSide Error"?
This error relates to your account mode and position management settings.
First, check your current mode using:
GET /api/v5/account/posModeKey Rules:
- In Long/Short Mode (One-Way Mode): You must specify
posSideas eitherlongorshortwhen placing an order. - In Hedge Mode (Dual Position Mode):
posSidesupportsnet,long, orshort. - For spot or margin trading, only
netor empty values are accepted.
Ensure your request includes the correct posSide based on your account’s position mode.
How to Find Contract Value and Minimum Order Size?
Use the Get Instrument Details endpoint to retrieve essential product information:
ctVal: Nominal value per contractminSz: Minimum order quantity (in contracts)
These fields help prevent validation errors when placing orders and allow precise position sizing.
What Is the instId Format?
The instId identifies a specific trading instrument. Supported formats include:
- Spot Trading:
BTC-USDT - Perpetual Contracts (USDⓈ-M):
BTC-USDT-SWAP - Perpetual Contracts (Coin-M):
BTC-USD-SWAP Futures Contracts:
- Coin-M:
BTC-USD-210326 - USDⓈ-M:
BTC-USDT-210326
(Format: YYMMDD)
- Coin-M:
Options:
- Call:
BTC-USD-210326-2000-C - Put:
BTC-USD-210326-2000-P
- Call:
📌 All characters must be uppercase.
How to Set Stop-Loss and Take-Profit?
There are two methods:
1. Attached Algo Orders
When placing a primary order, use the attachAlgoOrds parameter array to include take-profit and stop-loss triggers:
"attachAlgoOrds": [
{ "tpTriggerPx": "50000", "tpOrdPx": "50000" },
{ "slTriggerPx": "45000", "slOrdPx": "45000" }
]2. Standalone Algo Orders
Use the Algo Order Placement Interface for independent stop-loss orders not tied to an initial trade.
Why Do I Get Errors 51046, 51047, 51048, or 51049 When Setting TP/SL?
These errors occur due to incorrect trigger price logic relative to the current market price.
Rules:
| Trade Direction | Take-Profit Trigger | Stop-Loss Trigger |
|---|---|---|
| Buy (Long) | < Last Price | > Last Price |
| Sell (Short) | > Last Price | < Last Price |
Example:
If last price is $48,000:
- Long TP must be < $48,000
- Long SL must be > $48,000
Adjust accordingly to avoid rejection.
What Does "Interface Error: 50102 Timestamp Request Expired" Mean?
This means your request timestamp is too far out of sync with the server time.
✅ Fix: Synchronize your system clock with OKX’s server time using:
GET /api/v5/public/timeKeep your local time within ±30 seconds of the server. Also note:
- Request headers use UTC+0
- Server time response uses UTC+8
Use NTP services to maintain accuracy.
What Does "Interface Error: 50101 APIKey Does Not Match Current Environment"?
This indicates a mismatch between your API key and the trading environment.
| Environment | Required API Key | x-simulated-trading Header |
|---|---|---|
| Live Trading | Real Account Key | 0 |
| Demo Trading | Demo Account Key | 1 |
Ensure you’re using the correct key type and header setting.
What Does "Interface Error: 51010 Request Unsupported Under Current Account Mode"?
Your current account mode doesn't support the requested operation.
For example:
- Margin or single-currency margin requires non-spot modes.
- Switch via Account Settings → Account Mode
You can update this via:
- Web/App UI: Trading page → Account Mode
- API: Use
/api/v5/account/set-account-mode
What Does "Order Quantity Must Be a Multiple of Lot Size" Mean?
Contract orders must be in multiples of the minimum lot size (minSz). You can find this via the product info endpoint.
For example:
- If
minSz = 1, order sizes must be whole numbers - If
minSz = 0.1, valid sizes: 1.0, 1.1, 1.2…
Always validate input against this value before submitting.
Why Does Withdrawal Fail with "Address Not Whitelisted for Verification Exemption"?
Even if you disable withdrawal verification on the website, API withdrawals require explicit allowlist approval.
✅ Solution:
- Go to the withdrawal page
- Add the destination address
- Select "Not verified by Visa" (or equivalent trust option)
Only then can that address be used via API.
What Does "API Endpoint Request Timeout (50004)" Mean?
Error 50004 indicates server overload, often during high-traffic periods like funding fee settlements at 00:08, 08:08, and 16:08 UTC.
⚠️ Note: A timeout does not mean failure—the request may have succeeded silently.
✅ Best Practice:
- Retry with exponential backoff
- Check actual order/fund status afterward
- Avoid peak times for critical operations
👉 Optimize your trading bot performance with OKX API tools
FAQ Section
Q: Can I recover a lost passphrase?
No. If you lose your passphrase, you must create a new API key. Always store passphrases securely using encrypted vaults or password managers.
Q: Are there rate limits on the OKX API?
Yes. Public endpoints allow higher frequency; private endpoints are more restricted. Exceeding limits results in temporary bans. Refer to official docs for exact thresholds.
Q: How do I know if my order succeeded after a timeout error?
Check via /api/v5/trade/order with your order ID. Never assume failure after a timeout—duplicate orders may result.
Q: Can I use one API key for both live and demo trading?
No. You must use separate keys for live and demo environments. Mixing them causes authentication errors.
Q: Is IP binding required?
Not required, but strongly recommended for security—especially for withdrawal-enabled keys.
Q: Where can I get real-time support for API issues?
While direct chat isn't available here, official documentation and developer communities offer robust resources for troubleshooting.
By mastering these fundamentals, you’ll enhance reliability, avoid common pitfalls, and unlock advanced automation capabilities through the OKX API. Always refer to updated endpoints and test thoroughly in demo mode first.