Home › Guides › OKX API with Python
OKX API with Python: Your First Script (2026)
You get 20% of your trading fees back with this code; the site owner earns a commission at no extra cost to you. Not for residents of restricted regions (incl. U.S., Canada). Rewards vary by region and are not guaranteed. Independent guide, not an official OKX site.
Short answer: you can call the OKX v5 API from Python with nothing but the standard library. Public market data (like a ticker) needs no key; account and order endpoints need four headers, including an HMAC SHA256 signature of timestamp + method + path + body. Start in demo trading with a read-only demo key, add the x-simulated-trading: 1 header to every request, and build position limits, a daily loss limit and a kill switch into the code before it ever sees a live key.
OKX API for Python at a glance
| Item | What OKX's docs say |
|---|---|
| API | v5, REST and WebSocket. Paths start with /api/v5/. |
| REST host | The docs list https://openapi.okx.com, and say US and Australian users use us.okx.com and EEA users eea.okx.com. Use the host the docs show for your region. |
| Auth headers | OK-ACCESS-KEY, OK-ACCESS-SIGN, OK-ACCESS-TIMESTAMP, OK-ACCESS-PASSPHRASE. |
| Signature | Base64( HMAC SHA256( timestamp + METHOD + requestPath + body, secret ) ). Query strings are part of requestPath. |
| Timestamp | UTC, ISO 8601 with milliseconds, e.g. 2020-12-08T09:08:57.715Z. More than 30 seconds off server time → error 50102. |
| Demo trading | Separate demo API key plus header x-simulated-trading: 1. Demo and live keys can't be swapped (error 50101). Demo keys don't expire. |
| Key permissions | Read, Trade, Withdraw (plus Transfer, and Loan/Earn where eligible). A Read-only key can't place orders. |
| IP binding | Up to 20 IP addresses per key, strongly recommended. Unbound keys with trade or withdraw permission are deleted after 14 days of inactivity. |
| Rate limits | Set per endpoint (e.g. account balance: 10 requests per 2 seconds per user ID). Exceeding one returns error 50011. |
| Key creation rule | In some regions, only accounts with assets above 100 USDT can create API keys. |
Should you write your own OKX script at all?
A script is good for pulling data, logging your trades, and running rules exactly as written. It is not a shortcut to profit. Most of the work is error handling and safety, and a bug can place orders faster than you can react. If you mainly want automation without code, OKX's built-in bots may be simpler; see OKX trading bots explained. Reasons to wait: you can't yet read a stack trace, you plan to start with leverage, or you'd run it on money you can't afford to lose.
How to run your first OKX API script, step by step
- Open demo trading. You need an OKX account; demo is inside it. See OKX demo trading for where it is and what it can't teach you.
- Create a demo API key from the Demo trading area. Give it Read only for now. Write down the passphrase you set: OKX can't recover it.
- Store the key outside your code. Put it in environment variables (
OKX_API_KEY,OKX_SECRET_KEY,OKX_PASSPHRASE), never in a file you commit or share. - Run the public part first. With no key set, the script below only fetches the BTC-USDT ticker and checks your clock against OKX server time.
- Add the key and run a signed read. The script fetches your demo USDT balance. If it fails, use the error table further down.
- Test one demo order (optional). Give the demo key Trade permission, set
PLACE_DEMO_ORDER=1, and the script places one small limit buy far below the market, checkssCode, then cancels it. - Review before you build more. Look at the order in the demo web interface and confirm it matches what your code sent.
The script: market data, a signed read and one demo order
Standard library only (Python 3.9+). It never sends a request without the demo header, so it can't touch live funds. It is a learning skeleton, not a trading strategy.
import base64, datetime, hashlib, hmac, json, os, sys, time, urllib.error, urllib.request
BASE = os.environ.get("OKX_BASE_URL", "https://openapi.okx.com") # check the host for your region in the docs
KEY, SECRET, PASSPHRASE = (os.environ.get(k, "") for k in ("OKX_API_KEY", "OKX_SECRET_KEY", "OKX_PASSPHRASE"))
DEMO = True # this script never talks to live trading
MAX_ORDER_USDT = 20 # position-size cap per order
DAILY_MAX_LOSS_USDT = 50 # stop for the day after this drawdown
KILL_FILE = "STOP" # create a file named STOP to halt everything
def sign(ts, method, path, body=""):
msg = f"{ts}{method}{path}{body}".encode()
return base64.b64encode(hmac.new(SECRET.encode(), msg, hashlib.sha256).digest()).decode()
def call(method, path, body=None, private=False):
if os.path.exists(KILL_FILE):
sys.exit("Kill switch file found, stopping.")
data = json.dumps(body) if body else ""
headers = {"Content-Type": "application/json"}
if private:
ts = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
headers.update({"OK-ACCESS-KEY": KEY, "OK-ACCESS-SIGN": sign(ts, method, path, data),
"OK-ACCESS-TIMESTAMP": ts, "OK-ACCESS-PASSPHRASE": PASSPHRASE})
if DEMO:
headers["x-simulated-trading"] = "1"
req = urllib.request.Request(BASE + path, data=data.encode() or None, headers=headers, method=method)
for attempt in range(3):
try:
with urllib.request.urlopen(req, timeout=10) as r:
res = json.load(r)
except urllib.error.HTTPError as e: # OKX still sends a JSON error body
res = json.loads(e.read() or b"{}")
if res.get("code") == "50011" and method == "GET": # rate limited: back off, retry reads only
time.sleep(2 * (attempt + 1))
continue
return res
return res
def main():
t = call("GET", "/api/v5/market/ticker?instId=BTC-USDT")["data"][0]
print("BTC-USDT last", t["last"], "bid", t["bidPx"], "ask", t["askPx"])
server_ms = int(call("GET", "/api/v5/public/time")["data"][0]["ts"])
drift = abs(server_ms - time.time() * 1000) / 1000
print(f"clock drift {drift:.1f}s")
if drift > 5:
sys.exit("Fix your system clock first (OKX rejects requests more than 30 s off).")
if not KEY:
return print("No key set: public data only. Done.")
bal = call("GET", "/api/v5/account/balance?ccy=USDT", private=True)
if bal["code"] != "0":
sys.exit(f"Error {bal['code']}: {bal['msg']}")
equity = float(bal["data"][0]["totalEq"] or 0)
print("demo equity (USD)", equity)
if os.environ.get("PLACE_DEMO_ORDER") != "1":
return print("Read-only run. Set PLACE_DEMO_ORDER=1 to test one demo order.")
start = float(os.environ.get("START_EQUITY", equity))
if start - equity > DAILY_MAX_LOSS_USDT:
sys.exit("Daily max loss reached, no new orders today.")
px = round(float(t["last"]) * 0.5, 1) # far below market: should rest, not fill
sz = f"{MAX_ORDER_USDT / px:.5f}"
order = {"instId": "BTC-USDT", "tdMode": "cash", "side": "buy", "ordType": "limit",
"px": str(px), "sz": sz, "clOrdId": f"test{int(time.time())}"}
res = call("POST", "/api/v5/trade/order", order, private=True)
item = (res.get("data") or [{}])[0]
if res["code"] != "0" or item.get("sCode") != "0":
sys.exit(f"Order rejected: {res['code']} {item.get('sCode')} {item.get('sMsg') or res.get('msg')}")
print("demo order placed", item["ordId"])
print(call("POST", "/api/v5/trade/cancel-order", {"instId": "BTC-USDT", "ordId": item["ordId"]}, private=True))
if __name__ == "__main__":
main()
What the guards do:
DEMO = Trueaddsx-simulated-trading: 1to every call. A live key would be rejected (50101), which is what you want here.MAX_ORDER_USDTcaps order size.DAILY_MAX_LOSS_USDTcompares current equity withSTART_EQUITY(set it once each morning) and refuses new orders after that drawdown.- A file named
STOPin the working folder is a kill switch: every call checks for it first. - Only GET requests are retried after a rate-limit error. Orders are never retried blindly (see below).
Check your signing code with a test vector
Signature bugs are the most common reason a first private call fails. Before you debug against OKX, check your sign() function offline with these made-up values (not a real key):
| Secret | TEST_SECRET_DO_NOT_USE |
| Timestamp | 2026-11-06T12:00:00.000Z |
| Method + path | GET /api/v5/account/balance?ccy=USDT (empty body) |
| Expected OK-ACCESS-SIGN | QI1MQ2jpIOHMh8s37iv1iy8fdhJ5ns1h7xhZamOe9PU= |
If you get a different string, check for: a lowercase method, a missing query string, a body serialised differently from what you send, or a timestamp without milliseconds. We computed this value with Python's hmac and hashlib using the formula in OKX's docs.
Common problems: what if the API returns an error?
| You see | What it means (per OKX) | What to do |
|---|---|---|
| 50102 | Timestamp more than 30 seconds from server time | Use UTC, sync your clock, compare with /api/v5/public/time. |
| 50101 | Key doesn't match the environment | Demo key → demo header. Live key → no demo header. |
| 50011 | Rate limit reached | Slow down; back off and retry reads. Check the endpoint's own limit. |
| 50061 | Sub-account order rate limit reached | Several bots share one sub-account's cap; spread or slow them. |
| 50123 | Key lacks permission to trade | Add Trade to the demo key, or keep it read-only on purpose. |
code is "0" but sCode isn't | Request accepted, but this order was rejected | Read sMsg. Always check both levels. |
| Key suddenly gone | Unbound trade/withdraw keys are deleted after 14 idle days | Bind it to your IP, or create a new key. |
| Nothing works from your region | Some regions use a different host | Set OKX_BASE_URL to the host the docs list for you. |
What if an order request times out?
Don't simply send it again: the first one may have gone through, and a retry can open the same order twice. Give each order your own clOrdId (up to 32 letters and numbers), then look it up with the order-details endpoint before you decide to resend.
Risk section: read this before any live key
Demo first. Run your script in demo until it has handled errors, restarts and rate limits without surprises. Demo fills are simulated, so a script that "works" in demo can still behave differently live.
Fees compound with trade frequency
Illustrative numbers, not OKX's fee schedule. Assume 200 USDT per trade and a 0.10% fee on each side (0.40 USDT per round trip). Use your own rate from OKX fees explained or the fee calculator.
| Round trips per day | Fees per day | Fees per 30 days | After a 20% rebate (30 days) |
|---|---|---|---|
| 5 | 2.00 USDT | 60 USDT | 48 USDT |
| 20 | 8.00 USDT | 240 USDT | 192 USDT |
| 50 | 20.00 USDT | 600 USDT | 480 USDT |
On a 1,000 USDT account, 50 round trips a day costs about 2% of the account every day before slippage or a single losing trade. The 20% rebate with code 33746534 lowers the fee line; it doesn't make a losing strategy profitable.
Liquidation, if your code ever touches leverage
Simplified illustration. With 1,000 USDT of margin at 10x, you control a 10,000 USDT position. A 10% move against you is a 1,000 USDT loss, which is all of your margin. In practice liquidation comes earlier, because the exchange closes the position before margin reaches zero (maintenance margin) and fees also count. At 50x, about a 2% move is enough. A script can open leveraged positions much faster than you can notice a bug. Derivatives are also unavailable in some countries (for example, for retail users in the UK and Australia).
Limits to build into the code
- Position sizing: a hard cap per order and per symbol, far below your account size.
- Daily max loss: stop opening orders after a fixed drawdown, and don't override it the same day.
- Kill switch: one action (a file, a flag, a command) that halts the loop, plus a way to cancel open orders.
- Backtests and demo ≠ live: real slippage, latency, outages and your own reactions are missing from both.
API key safety
- Never enable Withdraw on a key used by a script or bot.
- Bind every key to your IP addresses.
- Keep keys in environment variables; never paste them into code, chats, screenshots or AI tools.
- Never share the key, secret or passphrase with anyone, including "support". OKX says not to send them when asking for help.
- Consider a separate sub-account for each bot, with its own key, so a bug can only reach that balance.
Honest limits and costs
- No profit is implied. This guide shows plumbing, not a strategy. Crypto is volatile and you can lose some or all of your money.
- Maintenance. Endpoints, hosts and limits change. Re-check the docs when something breaks.
- Availability. API access, products and hosts vary by region. Check whether OKX is available in your country first.
- Not advice. Educational information only, not financial, legal or tax advice.
Official sources
FAQ
Can I use the OKX API with Python?
Yes. The OKX v5 API is a REST (and WebSocket) API, so Python can call it with any HTTP library, including the standard library used in this guide. Public market data needs no key; account and trading endpoints need a signed request.
How do I sign an OKX API request in Python?
Join the timestamp, the uppercase method, the request path (including the query string) and the body, sign that string with HMAC SHA256 using your secret key, and Base64-encode the result. Send it as OK-ACCESS-SIGN together with OK-ACCESS-KEY, OK-ACCESS-TIMESTAMP and OK-ACCESS-PASSPHRASE.
Why does the OKX API return error 50102?
Your request timestamp is more than 30 seconds away from OKX server time. Use UTC in ISO 8601 format with milliseconds, sync your system clock, and compare against GET /api/v5/public/time.
What permissions should an OKX API key for a script have?
Start with Read only. Add Trade only when you are ready to place orders, and never enable Withdraw for a script or bot. Bind the key to your IP addresses and keep it in environment variables, not in your code.
What are the OKX API rate limits?
They differ by endpoint, so check the limit printed on each endpoint in the docs. For example, the balance endpoint allows 10 requests per 2 seconds per user ID. When you exceed a limit, OKX returns error code 50011.
Why does my OKX demo API key return error 50101?
The key and the environment don't match. Demo keys only work with the x-simulated-trading: 1 header, and live keys only work without it. Create the key inside Demo trading if you want to test in demo.
Can the script in this guide trade with real money?
No. It always sends the demo header, places at most one small demo order far below the market only when you opt in, and cancels it. Moving to live trading is a separate decision you should make only after reviewing demo results and the risk section.
Is using the OKX API allowed in my country?
It depends on where you live. OKX's products, including API trading and derivatives, are not available everywhere, and some regions use a different OKX host. Check OKX's terms for your region first. This guide is not financial or legal advice.