Python Script Framework for Simple Trading Operations on OKX

·

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:

  1. Create an OKX Account
    Visit the official OKX website and complete registration, including identity verification (KYC), which is required for most trading features.
  2. Navigate to API Management
    Once logged in:

    • Go to your Account Settings
    • Select API Management
    • Click Create API Key
  3. 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
  4. Securely Store Your Credentials
    You’ll receive three critical pieces:

    • API Key
    • Secret Key
    • Passphrase

👉 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 requests

Optional (for real-time data streaming):

pip install websockets

Or use a unified crypto trading library:

pip install ccxt

While 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


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:

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.