Automating trading activities through APIs has become a cornerstone of modern cryptocurrency trading—especially for those leveraging quantitative strategies. This guide walks you through building a lightweight yet powerful Python script to interact with the OKX exchange, enabling essential operations like fetching account balances and placing trades programmatically.
Whether you're a developer exploring algorithmic trading or a trader aiming to automate repetitive tasks, this tutorial provides a clear, secure, and functional foundation using native Python libraries.
Step 1: Register and Generate Your API Keys
Before any code can interact with OKX, you must authenticate your requests using API credentials. Here's how to set it up securely:
- Create an OKX Account
Visit the official OKX website and complete registration, including identity verification (KYC), which is required for most trading features. Navigate to API Management
Once logged in:- Go to your Account Settings
- Select API Management
- Click Create API Key
Configure Your API Permissions
During creation, define access rights carefully:- Read-only: View balances and market data
- Trade permission: Place and cancel orders
- Withdrawal permission: Not recommended unless absolutely necessary
Securely Store Your Credentials
You’ll receive three critical pieces:API KeySecret KeyPassphrase
👉 Secure your API keys now and start automated trading safely with a trusted platform.
🔐 Best Practice: Never hardcode these values directly into your scripts. Use environment variables or encrypted config files to prevent accidental exposure.
Step 2: Install Required Python Libraries
To communicate with the OKX REST API, install the following packages via pip:
pip install requestsrequests: Handles HTTP/HTTPS communication with the OKX server.
Optional (for real-time data streaming):
pip install websocketsOr use a unified crypto trading library:
pip install ccxtWhile ccxt simplifies cross-exchange compatibility, this guide uses requests for transparency and control over API interactions.
Step 3: Build the Core Script Framework
Below is a complete, modular Python script that demonstrates secure authentication and two fundamental trading functions: retrieving account balance and placing orders.
import requests
import hmac
import hashlib
import time
import json
import os
# Load sensitive data from environment variables (recommended)
API_KEY = os.getenv('OKX_API_KEY')
SECRET_KEY = os.getenv('OKX_SECRET_KEY')
PASSPHRASE = os.getenv('OKX_PASSPHRASE')
# OKX API Base URL
BASE_URL = 'https://api.okx.com'
def generate_signature(params: dict, secret_key: str) -> str:
"""
Generate HMAC-SHA256 signature for request authentication.
"""
# Sort parameters alphabetically and concatenate as key-value pairs
sorted_params = ''.join(f"{k}{v}" for k, v in sorted(params.items()))
return hmac.new(
secret_key.encode(),
sorted_params.encode(),
hashlib.sha256
).hexdigest()
def get_account_balance(account_type='spot'):
"""
Fetch current account balance.
:param account_type: 'spot', 'futures', 'margin'
:return: JSON response from OKX API
"""
endpoint = '/api/v5/account/balance'
timestamp = str(int(time.time() * 1000))
params = {
'apiKey': API_KEY,
'timestamp': timestamp,
'passphrase': PASSPHRASE,
'ccy': '' # Optional: filter by currency (e.g., 'BTC')
}
# Add type-specific query if needed
url = f"{BASE_URL}{endpoint}?type={account_type}"
# Generate signature
signature = generate_signature(params, SECRET_KEY)
headers = {
'OK-ACCESS-KEY': API_KEY,
'OK-ACCESS-SIGN': signature,
'OK-ACCESS-TIMESTAMP': timestamp,
'OK-ACCESS-PASSPHRASE': PASSPHRASE,
'Content-Type': 'application/json'
}
response = requests.get(url, headers=headers)
return response.json()
def place_order(symbol, side, order_type, size, price=None):
"""
Place a new trade order on OKX.
:param symbol: Trading pair (e.g., 'BTC-USDT')
:param side: 'buy' or 'sell'
:param order_type: 'market', 'limit', etc.
:param size: Amount of base asset to trade
:param price: Limit price (ignored for market orders)
:return: API response in JSON format
"""
endpoint = '/api/v5/trade/order'
timestamp = str(int(time.time() * 1000))
# Prepare request body
data = {
"instId": symbol,
"tdMode": "cash", # For spot trading; use "cross" or "isolated" for margin/futures
"side": side,
"ordType": order_type,
"sz": str(size)
}
if order_type == "limit":
data["px"] = str(price)
# Convert to JSON string for signing
body_str = json.dumps(data)
# Generate signature based on concatenated components
message = timestamp + "POST" + endpoint + body_str
signature = hmac.new(
SECRET_KEY.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
headers = {
'OK-ACCESS-KEY': API_KEY,
'OK-ACCESS-SIGN': signature,
'OK-ACCESS-TIMESTAMP': timestamp,
'OK-ACCESS-PASSPHRASE': PASSPHRASE,
'Content-Type': 'application/json'
}
response = requests.post(f"{BASE_URL}{endpoint}", headers=headers, data=body_str)
return response.json()
# Example usage
if __name__ == "__main__":
# Get balance
balance = get_account_balance('spot')
print("Account Balance:", json.dumps(balance, indent=2))
# Place a limit buy order for 0.001 BTC at $30,000
order_response = place_order('BTC-USDT', 'buy', 'limit', 0.001, 30000)
print("Order Response:", json.dumps(order_response, indent=2))👉 Generate highly efficient trading scripts powered by real-time market access.
Key Technical Notes
- Timestamp Format: Must be in milliseconds since Unix epoch.
- Request Signing: The signature combines timestamp, HTTP method, endpoint, and request body (for POST).
- Headers: All authenticated endpoints require specific
OK-ACCESS-*headers. - Rate Limits: OKX enforces rate limits; avoid aggressive polling.
Frequently Asked Questions (FAQ)
Q: Can I use this script for futures trading?
A: Yes. Modify the tdMode parameter to "cross" or "isolated" and ensure your API key has futures trading permissions enabled.
Q: Why am I getting “Invalid signature” errors?
A: Double-check that all parameters are correctly ordered and encoded. Ensure you're signing the exact string format expected by OKX—especially for POST requests where the body must be included in the signature.
Q: Is it safe to run automated scripts with live funds?
A: Always test in demo or paper trading mode first. Use separate API keys with minimal permissions and monitor logs closely before going live.
Q: How do I handle API rate limits?
A: Implement exponential backoff logic and respect OKX’s documented limits. Consider caching responses when possible.
Q: Can I fetch real-time price data with this setup?
A: Yes—extend the script using WebSocket connections via the websockets library for live ticker updates.
Q: What should I do if my API key is compromised?
A: Immediately revoke it via the OKX dashboard and generate a new one. Rotate credentials regularly as part of security hygiene.
Final Recommendations
This script serves as a clean starting point for integrating algorithmic logic into your trading workflow. From here, you can expand functionality by adding:
- Order status checks
- Error handling and retry mechanisms
- Logging and alerting systems
- Integration with technical indicators (e.g., moving averages)
Automation brings efficiency—but also responsibility. Always prioritize security, validate inputs, and test thoroughly in sandbox environments.
👉 Take your strategy live with reliable infrastructure and low-latency execution.