Python OKX API Trading Bot Tutorial

·

Creating a trading bot using Python and the OKX API is an effective way to automate cryptocurrency trading strategies. This tutorial provides a step-by-step guide to building a basic trading bot, including authentication, market data retrieval, and order placement.


Step 1: Setting Up Your Environment

Prerequisites


Step 2: Obtaining Your OKX API Keys

  1. Sign Up/Log In: Create an account on OKX if you don’t have one.
  2. Generate API Keys:

    • Navigate to API Management in your account settings.
    • Create a new key with permissions for trading and market data.
    • Securely store the API Key, Secret Key, and Passphrase.

Step 3: Understanding the OKX API Endpoints

The OKX API offers endpoints for:

👉 Explore OKX API Documentation


Step 4: Building the Trading Bot

Example Code

import requests
import hashlib
import hmac
import time

API_KEY = "your_api_key"
SECRET_KEY = "your_secret_key"
PASSPHRASE = "your_passphrase"
BASE_URL = "https://www.okx.com/join/BLOCKSTARapi/v5/"

def get_signature(timestamp, method, endpoint, body=""):
    message = timestamp + method + endpoint + body
    return hmac.new(SECRET_KEY.encode(), message.encode(), hashlib.sha256).hexdigest()

def get_current_price(symbol):
    endpoint = "market/ticker?instId=" + symbol
    response = requests.get(BASE_URL + endpoint)
    return float(response.json()["data"][0]["last"])

def place_order(symbol, side, price, size):
    endpoint = "trade/order"
    timestamp = str(time.time())
    body = {
        "instId": symbol,
        "tdMode": "cash",
        "side": side,
        "ordType": "limit",
        "px": str(price),
        "sz": str(size)
    }
    headers = {
        "OK-ACCESS-KEY": API_KEY,
        "OK-ACCESS-SIGN": get_signature(timestamp, "POST", "/api/v5/" + endpoint, str(body)),
        "OK-ACCESS-TIMESTAMP": timestamp,
        "OK-ACCESS-PASSPHRASE": PASSPHRASE
    }
    response = requests.post(BASE_URL + endpoint, json=body, headers=headers)
    return response.json()

# Main Logic
symbol = "BTC-USDT"
threshold_price = 60000  # Example threshold

current_price = get_current_price(symbol)
if current_price < threshold_price:
    place_order(symbol, "buy", current_price, 0.001)

Key Features

  1. Authentication: Uses HMAC-SHA256 for secure API requests.
  2. Price Check: Fetches live market data via market/ticker.
  3. Order Placement: Submits limit orders through trade/order.

Step 5: Testing and Deployment


Risk Management Tips


FAQs

Q1: How do I secure my API keys?

A: Never hardcode keys in scripts. Use environment variables or encrypted secrets.

Q2: Can I backtest this bot?

A: Yes! Use historical data from OKX’s API or third-party datasets.

Q3: What’s the rate limit for OKX API?

A: Up to 20 requests/second. Monitor headers for rate limits.

Q4: How do I handle API errors?

A: Check HTTP status codes and OKX’s error message formats.

Q5: Is Python the best language for trading bots?

A: Python is great for prototyping. For low latency, consider C++ or Go.


👉 Ready to start trading? Explore OKX’s advanced features


### Summary