The OKX API differs from other exchanges in a few ways: besides the API Key and Secret Key there is a Passphrase you set yourself and can never recover; a key with trade permission but no IP binding is deleted after 14 days of inactivity; and order rate limits are counted per trading pair rather than as one allowance for the whole account. This guide follows the official OKX API documentation (v5) and help center, with figures as of 2026-09-28; the official pages always prevail. How rebates change a quant strategy's P&L is covered in fee rebates for quant traders; this article is only about connecting your code to OKX. Sign up for OKX with NOVA888 for a 20% auto-rebate; for our exclusive OKX rewards and promotions, contact support.
Three credentials: API Key, Secret Key, Passphrase
When you create a key, the system returns a randomly generated API Key and Secret Key; the Passphrase is a password you type in yourself. The docs state that OKX stores only a salted hash of the Passphrase, so if you forget it, it cannot be recovered and you must delete the key and create a new one. Store all three safely; the Passphrase is not shown again after creation.
Every private request carries four headers: OK-ACCESS-KEY, OK-ACCESS-SIGN (the signature), OK-ACCESS-TIMESTAMP and OK-ACCESS-PASSPHRASE. The timestamp must be UTC in ISO 8601 with millisecond precision; requests more than 30 seconds off server time are rejected (error 50102). The docs note that a local time zone offset is the most common cause and suggest syncing with GET /api/v5/public/time before placing orders.
Creating a key: web, app and sub-accounts
The paths listed in the official OKX API FAQ:
- Web: log in → Profile → "API and connections" → Create API key → name it → choose account and purpose → enter the IP allowlist → select permissions → set the Passphrase.
- App: log in → Menu (⋮⋮⋮) → scroll to API → Create API key, then the same steps.
Common sticking points:
- Asset threshold: OKX states that in certain areas, master accounts and sub-accounts need assets under management above 100 USD to create an API key.
- Sub-accounts need their own keys: create the key under the sub-account that will trade and use that sub-account's permissions and Passphrase; never mix the parent's and the sub-account's Key, Secret or Passphrase.
- The API domain depends on where you registered: US and Australian users registered on app.okx.com use us.okx.com, and EU users registered on my.okx.com use eea.okx.com; the wrong domain returns "50119 API key doesn't exist".
- Account mode must be set on the web or app first: spot, futures, multi-currency margin and portfolio margin modes each need a first-time setup in the interface; placing a futures order via API in spot mode returns 51010.
Permissions: read, trade, withdraw
| Permission | Official definition | Does a quant strategy need it? |
|---|---|---|
| Read | View account info such as bills and order history | Yes |
| Trade | Place and cancel orders, funding transfers, settings that need write permission | Yes |
| Withdraw | Make withdrawals | No. Do not enable it |
Trade permission also has three sub-items: Transfer (move funds between your accounts, available to all), Loan and Earn (visible only if your account is eligible). OKX says keys that already had trade permission get all three switched on automatically; when you create or edit a key, check whether your strategy really needs Loan and Earn.
Even with withdraw permission, an API withdrawal only works if the address was first added on the website with verification exemption ticked, otherwise it returns 58207. OKX adds that hurdle on purpose, and a trading bot never needs to go there: always withdraw by hand on the website or app.
The 14-day rule: keys without an IP binding expire
This is the rule that most sets OKX apart. The API docs state:
- Each key can bind up to 20 IP addresses, in IPv4, IPv6 or network segment format.
- Keys without an IP binding that have trade or withdraw permission expire after 14 days of inactivity (the FAQ says they are deleted automatically). Demo trading keys do not expire.
- "Used" is defined strictly: only calls to private endpoints that require key authentication count; passing key details to a public endpoint does not.
- On WebSocket, only the login counts as using the key; subscribing or placing orders on that connection after login does not.
- Usage records for unbound keys with trade or withdraw permission can be checked in the Security Center.
The last two points matter most for quant setups: a bot that stays on one WebSocket connection placing orders, rarely logs in again and has no IP binding can see its key expire while the strategy is still running.
The simplest fix is to bind your strategy server's fixed IP. A key bound to an IP is not subject to the 14-day inactivity rule and, if leaked, can only be used from your server, which solves stability and security in one step.
Demo trading: run it on virtual funds first
OKX demo trading works over the API. The documented flow: log in to OKX → [Trade] → [Demo Trading] → Personal Center → Demo Trading API → Create Demo Trading API Key. How it differs from production:
| Item | Production | Demo trading |
|---|---|---|
| Key | Key created on the live account | Must be a key created separately in the demo environment |
| REST requests | — | Add the header x-simulated-trading: 1 |
| WebSocket | wss://ws.okx.com:8443 | wss://wspap.okx.com:8443 (public, private and business paths) |
| Unsupported functions | — | Withdrawal, deposit, purchase/redemption and others |
| Key expiry | 14-day rule applies | Does not expire |
A key used in the wrong environment returns "50101 APIKey does not match the current environment": live keys go with x-simulated-trading: 0 (or no header), demo keys with 1. OKX also offers a browser-based Demo Trading Explorer where you can try demo endpoints after signing in, handy for checking parameter formats.
Rate limits: counted per trading pair
OKX does not use a single allowance per account. The docs state: public endpoints are limited by IP; private REST endpoints by User ID (each sub-account has its own User ID); placing, amending and cancelling orders have separate allowances; REST and WebSocket share the same allowance; and order limits are defined per trading pair (Instrument ID). Exceeding a limit returns error 50011. Common endpoints (as of 2026-09-28):
| Endpoint | Limit | Counted by |
|---|---|---|
Place order POST /api/v5/trade/order | 60 requests per 2 seconds | User ID + trading pair |
| Batch orders (up to 20 per request) | 300 orders per 2 seconds | User ID + trading pair |
| Cancel order | 60 requests per 2 seconds | User ID + trading pair |
Balance GET /api/v5/account/balance | 10 requests per 2 seconds | User ID |
Fee rates GET /api/v5/account/trade-fee | 5 requests per 2 seconds | User ID |
| Lead trader's lead instruments | 4 requests per 2 seconds | — |
On top of the per-pair limits there is a sub-account cap of 1,000 new and amend order requests per 2 seconds (each order in a batch counts), returning 50061 when exceeded. Both layers apply at once. The docs' own best practice: if you need more throughput, split strategies across sub-accounts so each uses its full allowance.
Accounts at fee tier VIP5 and above also get fill-ratio tiers: each day the system computes a ratio from the past 7 days of traded volume versus new and amend requests, and the top tier allows 10,000 requests per 2 seconds; a falling ratio comes with a one-day grace period. Spot and margin orders are exempt from the sub-account cap. GET /api/v5/trade/account-rate-limit shows your current allowance.
WebSocket: connections, subscriptions and heartbeat
- Connecting: up to 3 connection requests per second per IP. Public channels use the public address, private channels the private one.
- Subscriptions: subscribe, unsubscribe and login requests are capped at 480 per hour per connection in total.
- Heartbeat: a connection closes automatically if no subscription is established or no data is pushed for over 30 seconds. OKX suggests resetting a timer under 30 seconds on every message, sending the string
pingwhen it fires, and reconnecting if nopongarrives. - Private channel connections: channels such as orders, account and positions allow up to 30 connections per channel per sub-account; beyond that the newest one is usually rejected. Placing, amending and cancelling orders over WebSocket is not affected.
The OKX FAQ adds a practical detail: 8, 16 and 24 o'clock each day are funding fee collection times with heavy server load (the FAQ does not name a time zone), when "50004 API endpoint request timeout" can appear. A 50004 does not mean the order failed or succeeded; query the actual result instead of resending the same order.
If you worry about orders resting on the book after a crash or disconnect, POST /api/v5/trade/cancel-all-after sets a countdown: if it is not reset in time, all pending orders are cancelled (limited to 1 request per second).
Code sample: sign a request and query fee rates
The signature is built by signing the string "timestamp + method (uppercase) + request path + body" with the Secret Key using HMAC SHA256, then Base64-encoding the result. GET parameters count as part of the path. The sample queries the BTC-USDT spot fee rate in demo trading, which only needs read permission; all three credentials come from environment variables.
import base64, hashlib, hmac, os
from datetime import datetime, timezone
import requests
key = os.environ["OKX_API_KEY"]
secret = os.environ["OKX_SECRET_KEY"]
passphrase = os.environ["OKX_PASSPHRASE"]
path = "/api/v5/account/trade-fee?instType=SPOT&instId=BTC-USDT"
ts = datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
prehash = ts + "GET" + path
sign = base64.b64encode(hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()).decode()
headers = {
"OK-ACCESS-KEY": key,
"OK-ACCESS-SIGN": sign,
"OK-ACCESS-TIMESTAMP": ts,
"OK-ACCESS-PASSPHRASE": passphrase,
"x-simulated-trading": "1",
}
r = requests.get("https://openapi.okx.com" + path, headers=headers, timeout=10)
print(r.status_code, r.json())
To go live, switch to a key from the live account and drop the x-simulated-trading header; US, Australian and EU users must also switch to their own API domain.
Fees on API orders and maker-only orders
Rather than relying on the public fee table, query your account's actual current rate with GET /api/v5/account/trade-fee, as in the sample above. The official docs note that for spot and margin you should pass instId to get the correct applicable rate (for example, market-maker rates for users in incentive programs). Public rates by tier are in OKX VIP fee tiers.
To stay maker-only, set ordType to post_only. The docs define it as an order that can only provide liquidity and be a maker; if it would execute on placement, it is cancelled instead. The difference between maker and taker and what it saves is in maker and taker fees explained.
API trading and rebates: what the OKX rules say
We read the OKX Affiliate Program rules (updated 2026-09-07) and the broker rules (updated 2026-08-05). The affiliate rules say the inviter earns a share of every trading fee paid by invitees across spot, futures and options. They do not say separately whether your own API orders are included or excluded, so for that part rely on your Quant Nova daily settlement records. What the rules do state, and what matters to algorithmic traders:
- Trading through a broker: the broker rules state that for users who registered via an affiliate invitation and then trade through a broker (API broker or OAuth broker), rebates go separately to both the affiliate and the broker.
- When no share is generated: the traded coin charges no fee; fees are offset with rebate cards, futures credits or vouchers; the trader has a special fee rate; the trader is a market maker or broker; a managed sub-account is used; the trader's fee tier is VIP7 or above.
In other words, accounts in the OKX market maker program or running strategies in managed sub-accounts are stated to be outside the scope, so check before you start.
Sign up for OKX with NOVA888 through Quant Nova for a 20% auto-rebate; for our exclusive OKX rewards and promotions, contact support. Binding needs only your UID; you never hand an API key to anyone. The code and sign-up link are in OKX referral code NOVA888, how the rebate is calculated in the OKX fee rebate guide, and for an existing account start with the OKX rebind guide. Quant teams that are already VIP elsewhere or trade large volume are welcome to contact Quant Nova support; we work directly with the exchange's official team to seek benefits such as VIP tier trials for you (final terms are set by the exchange).
Security and scams: never hand over your key
The OKX API Agreement (updated 2026-07-28) is explicit: you alone are responsible for generating, safekeeping, rotating and revoking your keys, you must not share API keys with unauthorized persons, and you must promptly revoke any key that may be compromised. It also lists granting API access or credentials to unauthorized third parties as prohibited conduct, and bars using the API to operate accounts or place orders on behalf of third parties without OKX's prior written approval.
When connecting a third-party bot or trading platform:
- Prefer OAuth authorization: the OKX broker rules explain that OAuth brokers are authorized through the OKX app or website, so users do not have to hand over their own API keys.
- If you must paste a key, grant only read and trade, bind the server IPs the provider publishes, and check whether sub-items like Loan and Earn are really needed.
- When reporting a problem to support, the OKX FAQ says never to send your Secret, Passphrase, verification codes or an unredacted signature.
"Managed trading" is the most common scam: someone claiming to be a quant team or trader asks you to create a key for them and promises a fixed monthly return. Never hand over a key with withdraw permission, whoever they are and whatever they promise; even with trade permission alone, they can wipe out your margin with high leverage.
When Taiwan's Financial Supervisory Commission published its VASP registration list on 2025-09-22, it again reminded the public that scammers lure people into buying virtual assets with lines such as "guaranteed profit, no loss" and "high return, low risk", then demand unfreezing fees, deposits or taxes before any payout can be withdrawn. (FSC press release, Chinese)
For users in Taiwan: as of 2026-09-28 OKX is not on the FSC list of virtual asset service providers that have completed AML registration. How to check the list and the status of each exchange is covered in Taiwan FSC VASP registration list.
FAQ
I forgot my OKX Passphrase. What now?
It cannot be recovered. OKX stores only a hash of the Passphrase, so delete the key and create a new one.
Why did my OKX API key suddenly stop working?
The most common cause is a key with trade or withdraw permission and no IP binding that sat inactive for 14 days and was deleted. On WebSocket only the login counts as use, not orders on the connection; binding a fixed IP takes the key out of this rule.
How many IPs can one key bind?
Up to 20, in IPv4, IPv6 or network segment format.
What are the OKX order rate limits?
60 single-order requests and 300 batch orders per 2 seconds, both counted by User ID plus trading pair, plus a cap of 1,000 new and amend requests per 2 seconds per sub-account. REST and WebSocket share the allowance.
How do I use the demo trading API?
Create a separate key in the demo trading Personal Center, add x-simulated-trading: 1 to REST headers and connect WebSocket to wspap.okx.com. Demo keys do not expire from inactivity.
Can API trading earn rebates?
The OKX affiliate rules share every trading fee paid by invitees and do not separately mention your own API orders, so rely on your settlement records; the broker rules state that when an affiliate's invitee trades through a broker, rebates go to both the affiliate and the broker. Market makers, managed sub-accounts and VIP7 and above generate no share.