CryptoPerks Guide

Home › Guides › OKX API with Python

OKX API with Python: Your First Script (2026)

Disclosure: this site uses affiliate links. If you sign up with our OKX code, we earn a share of the trading fees you pay; your 20% rebate is not reduced. Details.

OKX referral code · 20% fee rebateAffiliate link
Join OKX ↗

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

ItemWhat OKX's docs say
APIv5, REST and WebSocket. Paths start with /api/v5/.
REST hostThe 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 headersOK-ACCESS-KEY, OK-ACCESS-SIGN, OK-ACCESS-TIMESTAMP, OK-ACCESS-PASSPHRASE.
SignatureBase64( HMAC SHA256( timestamp + METHOD + requestPath + body, secret ) ). Query strings are part of requestPath.
TimestampUTC, ISO 8601 with milliseconds, e.g. 2020-12-08T09:08:57.715Z. More than 30 seconds off server time → error 50102.
Demo tradingSeparate 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 permissionsRead, Trade, Withdraw (plus Transfer, and Loan/Earn where eligible). A Read-only key can't place orders.
IP bindingUp to 20 IP addresses per key, strongly recommended. Unbound keys with trade or withdraw permission are deleted after 14 days of inactivity.
Rate limitsSet per endpoint (e.g. account balance: 10 requests per 2 seconds per user ID). Exceeding one returns error 50011.
Key creation ruleIn some regions, only accounts with assets above 100 USDT can create API keys.

Last verified: November 6, 2026, against the OKX API v5 documentation and the OKX API FAQ. Hosts, limits and permissions change; the docs win if they differ from this table.

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. Add the key and run a signed read. The script fetches your demo USDT balance. If it fails, use the error table further down.
  6. 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, checks sCode, then cancels it.
  7. 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:

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):

SecretTEST_SECRET_DO_NOT_USE
Timestamp2026-11-06T12:00:00.000Z
Method + pathGET /api/v5/account/balance?ccy=USDT (empty body)
Expected OK-ACCESS-SIGNQI1MQ2jpIOHMh8s37iv1iy8fdhJ5ns1h7xhZamOe9PU=

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 seeWhat it means (per OKX)What to do
50102Timestamp more than 30 seconds from server timeUse UTC, sync your clock, compare with /api/v5/public/time.
50101Key doesn't match the environmentDemo key → demo header. Live key → no demo header.
50011Rate limit reachedSlow down; back off and retry reads. Check the endpoint's own limit.
50061Sub-account order rate limit reachedSeveral bots share one sub-account's cap; spread or slow them.
50123Key lacks permission to tradeAdd Trade to the demo key, or keep it read-only on purpose.
code is "0" but sCode isn'tRequest accepted, but this order was rejectedRead sMsg. Always check both levels.
Key suddenly goneUnbound trade/withdraw keys are deleted after 14 idle daysBind it to your IP, or create a new key.
Nothing works from your regionSome regions use a different hostSet 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 dayFees per dayFees per 30 daysAfter a 20% rebate (30 days)
52.00 USDT60 USDT48 USDT
208.00 USDT240 USDT192 USDT
5020.00 USDT600 USDT480 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

API key safety

Honest limits and costs

Official sources

Checked on November 6, 2026: OKX API v5 documentation (REST authentication, demo trading, rate limits, error codes, place order) and the OKX API FAQ (permissions, IP binding, key expiry, demo keys, error codes).

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.

Last reviewed: . OKX changes its API, products and rules by region and over time. If anything here differs from OKX's documentation, the documentation is right. See how we check information.

Join OKX