Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

OKX REST API: The Complete Practical Guide for Automated Crypto Trading

If you've ever watched a trade slip past you by seconds — or stayed glued to charts at 3 AM trying to catch a breakout — you already understand why the OKX REST API exists. It's not a toy for developers. It's the infrastructure behind serious trading strategies: bots, market makers, DCA automators, data pipelines, and everything in between.

This guide covers everything you need to actually use it: getting your API key set up, nailing authentication, making your first requests, placing orders, handling errors, and understanding rate limits. We'll go end to end, with working Python code throughout.

By the end, you'll have a clear picture of how the OKX REST API fits into your trading stack — and why OKX's unified v5 architecture makes it one of the cleaner exchange APIs to build on.


What Is the OKX REST API — and Why Does It Matter?

The OKX REST API is a programmatic interface that lets you interact with OKX through standard HTTP requests. It's ideal for account management, placing orders, and accessing historical data. It also supports block trading through the Request-for-Quote (RFQ) process, facilitating large-sized spot trades, derivatives, and complex multi-leg structures.

In plain terms: anything you can do manually on the OKX platform, you can do via the REST API — faster, 24/7, without you sitting at a keyboard.

The OKX API provides programmatic access to the exchange, allowing you to execute trades automatically without manual intervention, access real-time market data for informed decision-making, and build custom trading applications or integrate OKX features into existing platforms.

The current production version is API v5. It introduced a unified account model — meaning one API layer handles spot, futures, options, and swaps. Compare that to Binance, where spot and futures live on separate API paths with different authentication flows. OKX got the unified approach right, and it shows in how much cleaner the developer experience feels.


REST API vs. WebSocket: Picking the Right Tool

Before diving into the REST API, it's worth knowing when not to use it.

REST APIs require an HTTP request to be sent for every response you get. It's the best when you just want the current state of a resource and do not want or require ongoing updates. WebSocket APIs do not follow a request-response message pattern — once a TCP connection has been established, the WebSocket channel can send updates continuously without receiving another request.

Use Case Best Choice
Account balance, order history REST API
Place/cancel orders (non-latency critical) REST API
Historical candlestick data REST API
Real-time order book, live price feeds WebSocket
Live position and P&L updates WebSocket
High-frequency order management WebSocket

Public WebSocket channels don't require authentication and provide market data to anyone. Private channels require API keys and give real-time updates on your account and orders.

For most traders starting with automation, the REST API is the entry point. WebSockets come into play once latency matters.


Step 1 — Getting Your OKX API Key

You need an OKX account first. If you haven't created one yet, you can 👉 register on OKX with invitation code CASH20 — new users get a 20% fee commission rebate, which compounds nicely over time if you're actively trading.

Once logged in, here's the setup process:

  1. Go to Profile → API Management
  2. Click Create API Key and give it a label (e.g., trading-bot-prod)
  3. Set permissions: Read and Trade to start — never enable Withdraw unless your strategy requires it
  4. Add an IP whitelist — this is non-negotiable for anything you'll run in production
  5. Set a passphrase (you won't be able to recover this later — store it somewhere secure)
  6. Copy the API key and secret key immediately — the secret is shown only once

Common trap: "OKX API key doesn't exist." This almost always means you created your key on the demo trading environment but you're hitting the live API (or vice versa). OKX maintains completely separate keys for live and demo environments. Check which environment your key belongs to before wasting an hour debugging.

Store credentials in environment variables, not in your code:

bash export OKX_API_KEY="your-api-key-here" export OKX_SECRET_KEY="your-secret-key-here" export OKX_PASSPHRASE="your-passphrase-here"

For security reasons, it is strongly recommended to bind API keys to specific IP addresses. A key that isn't IP-whitelisted is a key that can be used from anywhere — including from someone else's server if it ever leaks.


Step 2 — Understanding REST Authentication

Every authenticated request to the OKX REST API requires four headers: your API key, a cryptographic signature, a timestamp, and your passphrase. The signature uses HMAC SHA256 and is computed over the timestamp, HTTP method, request path, and body.

The request will expire 30 seconds after the timestamp. The server rejects requests where this differs from server time by more than 30 seconds (error 50102). If you're getting timestamp errors, the fix is almost always to sync your server clock with NTP.

Here's a complete Python authentication helper you can drop into any project:

python import os import time import hmac import hashlib import base64 import requests

API_KEY = os.environ['OKX_API_KEY'] SECRET_KEY = os.environ['OKX_SECRET_KEY'] PASSPHRASE = os.environ['OKX_PASSPHRASE'] BASE_URL = 'https://www.okx.com'

def get_timestamp(): return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())

def sign_request(timestamp, method, path, body=''): message = timestamp + method.upper() + path + body mac = hmac.new( SECRET_KEY.encode('utf-8'), message.encode('utf-8'), hashlib.sha256 ) return base64.b64encode(mac.digest()).decode('utf-8')

def okx_request(method, endpoint, body=''): timestamp = get_timestamp() signature = sign_request(timestamp, method, endpoint, body) headers = { 'OK-ACCESS-KEY': API_KEY, 'OK-ACCESS-SIGN': signature, 'OK-ACCESS-TIMESTAMP': timestamp, 'OK-ACCESS-PASSPHRASE': PASSPHRASE, 'Content-Type': 'application/json' } url = BASE_URL + endpoint if method == 'GET': resp = requests.get(url, headers=headers) else: resp = requests.post(url, headers=headers, data=body) return resp.json()

The endpoint structure is consistent throughout the entire API: /api/v5/{category}/{action}. Account endpoints live under /api/v5/account/, market data under /api/v5/market/, trading under /api/v5/trade/. Once this pattern clicks, navigating the docs becomes fast.

For public endpoints (market data, instrument info), no authentication headers are needed at all. You can test public REST APIs directly in your browser — for example, by visiting https://www.okx.com/api/v5/public/instruments?instType=SPOT.


Step 3 — Your First REST API Calls

Fetch Account Balance

This is typically the first authenticated call developers make — it confirms your key works and shows what you're working with:

python result = okx_request('GET', '/api/v5/account/balance') if result['code'] == '0': for detail in result['data'][0]['details']: ccy = detail['ccy'] available = detail['availBal'] print(f'{ccy}: {available}') else: print(f"Error {result['code']}: {result['msg']}")

Fetch Current Ticker

Public endpoint, no auth required:

python import requests response = requests.get('https://www.okx.com/api/v5/market/ticker?instId=BTC-USDT') data = response.json() if data['code'] == '0': price = data['data'][0]['last'] print(f"BTC-USDT: ${price}")

Get Open Positions

python result = okx_request('GET', '/api/v5/account/positions') if result['code'] == '0': for pos in result['data']: print(f"{pos['instId']}: {pos['pos']} @ {pos['avgPx']}")


Step 4 — Placing and Managing Orders

This is where things get interesting. The OKX REST API order endpoint is /api/v5/trade/order, and the tdMode parameter is what makes OKX's unified account model shine:

python import json

def place_limit_order(inst_id, side, size, price, mode='cash'): endpoint = '/api/v5/trade/order' body = json.dumps({ 'instId': inst_id, 'tdMode': mode, # 'cash' for spot, 'cross'/'isolated' for margin 'side': side, # 'buy' or 'sell' 'ordType': 'limit', 'sz': str(size), 'px': str(price) }) result = okx_request('POST', endpoint, body) if result['code'] == '0': order_id = result['data'][0]['ordId'] print(f'Order placed: {order_id}') return order_id else: error_msg = result['data'][0].get('sMsg', result['msg']) print(f'Order failed: {error_msg}') return None

Place a limit buy for 0.001 BTC at $60,000

order_id = place_limit_order('BTC-USDT', 'buy', '0.001', '60000')

One endpoint, one authentication flow — whether you're trading spot, margin, or perpetual futures. The tdMode parameter handles the routing.

Placing a Market Order

python def place_market_order(inst_id, side, size): endpoint = '/api/v5/trade/order' body = json.dumps({ 'instId': inst_id, 'tdMode': 'cash', 'side': side, 'ordType': 'market', 'sz': str(size) }) return okx_request('POST', endpoint, body)

Cancelling an Order

python def cancel_order(inst_id, order_id): endpoint = '/api/v5/trade/cancel-order' body = json.dumps({'instId': inst_id, 'ordId': order_id}) return okx_request('POST', endpoint, body)

Always run new order logic through OKX's demo trading environment first. Use https://www.okx.com with the header 'x-simulated-trading: 1' or create a separate demo API key. One bad loop in production and your account balance pays the tuition.


Step 5 — Rate Limits: What You Need to Know

OKX uses rate limits to protect its APIs against malicious usage so the trading platform can operate reliably and fairly. When a request is rejected due to rate limits, the system returns error code 50011.

Public unauthenticated REST rate limits are based on IP address. Private REST rate limits are based on User ID, with sub-accounts having individual User IDs. For trading-related APIs (place order, cancel order, amend order), rate limits are shared across REST and WebSocket channels.

Most trading endpoints allow 60 requests per 2 seconds, while market data endpoints are more generous. If you're running multiple strategies on one key, consider splitting them across separate API keys to avoid rate limit collisions.

A simple retry-with-backoff implementation:

python import time

def okx_request_with_retry(method, endpoint, body='', max_retries=3): for attempt in range(max_retries): result = okx_request(method, endpoint, body) if result.get('code') == '50026': # Rate limit wait = (2 ** attempt) * 0.5 # 0.5s, 1s, 2s print(f"Rate limited. Waiting {wait}s...") time.sleep(wait) continue return result return {'code': 'MAX_RETRIES', 'msg': 'Max retries exceeded'}


Step 6 — Common Error Codes (and What to Actually Do)

Error Code What It Means Fix
50001 API key doesn't exist or is invalid Verify key; check live vs. demo environment
50102 Timestamp expired Sync your server clock with NTP
50013 IP not whitelisted Add your server IP to API key settings
50026 Rate limit exceeded Implement exponential backoff
51008 Insufficient balance Check available funds before placing orders
51010 Order size too small Check minimum order size for the instrument

When error code is '0', the request succeeded. OKX always returns a code field — build your error handling around it.


Step 7 — Available API Modules at a Glance

The OKX REST API v5 is organized into clear functional categories. Here's what's available and what each covers:

Module Endpoint Prefix What You Can Do
Trading Account /api/v5/account/ Balances, positions, leverage, fees, risk state
Order Book Trading /api/v5/trade/ Place, cancel, amend orders; order history
Market Data /api/v5/market/ Tickers, candlesticks, order books, recent trades
Public Data /api/v5/public/ Instruments, delivery history, funding rates
Funding Account /api/v5/asset/ Deposits, withdrawals, transfer between accounts
Algo Trading /api/v5/trade/ (algo) Stop-loss, take-profit, trailing stop, grid bots
Copy Trading /api/v5/copytrading/ Follow lead traders, manage copy positions
Sub-Accounts /api/v5/users/subaccount/ Manage sub-accounts, transfer, API key CRUD
Block Trading (RFQ) /api/v5/rfq/ Large-sized OTC trades, multi-leg structures

The Python SDK maps these cleanly: api.account.* for trading account operations, api.marketdata.* for order book market data, api.trade.* for execution, api.algotrade.* for algo orders, api.copytrade.* for copy trading, and more.


Step 8 — OKX Trading Fees (and How the API Fits In)

Understanding the fee structure matters when you're running a bot — small fee differences at scale add up fast.

OKX applies maker and taker fees of 0.08% and 0.10% on spot trades, and 0.02% and 0.05% on futures. These are the base (Regular tier) rates.

Your VIP tier is determined by 30-day trading volume and daily asset balance across all primary and sub-accounts. The fee level of your primary account is applied to all sub-accounts.

Tier Spot Maker Spot Taker Futures Maker Futures Taker
Regular 0.08% 0.10% 0.02% 0.05%
VIP 1 0.07% 0.09% 0.015% 0.04%
VIP 2 0.06% 0.08% 0.01% 0.035%
VIP 3+ Negotiated Negotiated Negotiated Negotiated

You can query your current fee rates directly via the REST API at /api/v5/account/trade-fee, so your bot always knows exactly what it's paying.

If you're just getting started, using invitation code CASH20 when you 👉 sign up on OKX gives you a 20% commission rebate on trading fees — a meaningful edge over paying standard rates from day one.


Building a Simple BTC Price Monitor + Auto-Buy Bot

Here's a practical example that ties everything together — a script that monitors BTC price and places a buy when it drops below a target:

python import time import json import requests

TARGET_PRICE = 58000 # Buy if BTC drops below this ORDER_SIZE = 0.001 # 0.001 BTC per order CHECK_INTERVAL = 60 # Check every 60 seconds order_placed = False

def get_btc_price(): resp = requests.get('https://www.okx.com/api/v5/market/ticker?instId=BTC-USDT') data = resp.json() if data['code'] == '0': return float(data['data'][0]['last']) return None

while not order_placed: price = get_btc_price() if price: print(f"BTC-USDT: ${price:,.2f}") if price < TARGET_PRICE: print(f"Price below ${TARGET_PRICE:,}. Placing buy order...") result = place_market_order('BTC-USDT', 'buy', str(ORDER_SIZE)) if result['code'] == '0': print(f"Order placed: {result['data'][0]['ordId']}") order_placed = True else: print(f"Order failed: {result['msg']}") time.sleep(CHECK_INTERVAL)

This is the scaffolding for a DCA bot, a price alert system, or a simple breakout strategy. From here, the complexity scales as needed.


Python SDK vs. Raw HTTP: Which Should You Use?

Both approaches are valid. The choice depends on your use case.

Raw HTTP (what we've used above):

  • Full control over every request
  • No dependency management issues
  • Easiest to debug and inspect
  • Best for learning the API deeply

Official Python SDK:

  • Faster to prototype
  • Less boilerplate code

The Python SDK (okx-sdk on PyPI) implements all REST API endpoints, with the naming convention mapping /api/v5/AAA/BBB to api.AAA.BBB() method calls.

python from okx import OkxRestClient

api = OkxRestClient('---API-KEY---', '---API-SECRET---', '---PASS-PHRASE---') tickers = api.public.get_tickers(instType="SPOT") balance = api.account.get_account_balance()

For production systems, raw HTTP with a well-tested request helper typically gives you more control over error handling, retries, and rate limit management.


OKX Agent Trade Kit: AI-Assisted API Trading

Worth mentioning: OKX launched the Agent Trade Kit, which lets you control your OKX account through natural language commands or an LLM-powered interface.

It supports demo mode (simulated funds) and read-only mode (data queries only). Built-in rate limiting prevents overloading the OKX API, and credentials are kept in a local config file rather than shared with any AI model.

The OKX API Services include the REST API, WebSocket API, SBE (Simple Binary Encoding), Fast API, and Agent Trade Kit — all as part of the same programmatic access framework.

It's not a replacement for building your own bot, but it's useful for ad-hoc trading, quick analysis, and testing strategies in plain English before coding them up.


Getting Started: The Fast Path

Here's the shortest route from zero to a working OKX REST API integration:

  1. Create your account👉 Sign up with code CASH20 to get a 20% fee rebate right from the start
  2. Generate your API key — Profile → API Management → Create API Key (Read + Trade permissions, IP whitelist required)
  3. Test a public endpoint — No auth needed: curl https://www.okx.com/api/v5/market/ticker?instId=BTC-USDT
  4. Test authentication — Fetch your account balance using the Python helper above
  5. Use demo first — Add header x-simulated-trading: 1 or create a dedicated demo key before touching real funds
  6. Build incrementally — Start with reads, add order placement, layer in error handling, then optimize

The OKX REST API documentation at docs.okx.com is comprehensive and actively maintained. The unified v5 structure means that once you understand one endpoint category, the rest follow the same patterns.


Final Thoughts

The OKX REST API is one of the more developer-friendly interfaces in the crypto exchange space. The unified account model, consistent endpoint patterns, and solid documentation make it accessible whether you're building your first trading script or scaling a production system.

The key habits that separate working bots from broken ones: always test in demo first, store credentials in environment variables never in code, whitelist your server's IP, and build rate limit handling in from the beginning — not as an afterthought.

If you're starting fresh, 👉 create your OKX account with invitation code CASH20 and lock in a 20% trading fee rebate before your first trade. It's one of those small decisions that quietly pays dividends across thousands of future API calls.


All API endpoints and code examples reference OKX API v5. Rate limits and fee structures are subject to change — always verify against the official OKX API documentation before deploying to production.

About

OKX REST API: The Complete Practical Guide for Automated Crypto Trading

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors