Quant Trading: Creating Signatures & Fetching Ticker/Kline Data from OKEx

·

Introduction to Quant Trading

Quantitative trading leverages mathematical models, algorithms, and market data to execute trades systematically. This guide explores how to:


1. Creating a Trade Signature

Why Signatures Matter

APIs often require cryptographic signatures to verify request authenticity. Below is a Python function to generate an MD5 signature:

import hashlib

def create_trade_sign(params, api_key, secret_key):
    """
    Generate an MD5 signature for API authentication.
    :param params: Request parameters (e.g., {'symbol': 'btc_usdt'})
    :param api_key: Your exchange API key.
    :param secret_key: Your exchange secret key.
    :return: MD5 hash as a hexadecimal string.
    """
    sign = ''
    for key in sorted(params.keys()):
        sign += '&' + key + '=' + str(params[key])
    return hashlib.md5(sign.encode('utf-8')).hexdigest()

Example Usage

params = {'symbol': 'btc_usdt'}
api_key = "your_api_key_here"
secret_key = "your_secret_key_here"
print(create_trade_sign(params, api_key, secret_key))

👉 Learn more about API security best practices


2. Fetching Ticker Data from OKEx

Code Implementation

import pandas as pd

def get_ticker_from_okex(symbol_list):
    """
    Fetch ticker data (last price, bid/ask, volume) for given symbols.
    :param symbol_list: List of trading pairs (e.g., ['btc_usdt', 'eth_usdt']).
    :return: DataFrame with ticker metrics.
    """
    df = pd.DataFrame()
    base_url = 'https://www.okex.com/api/v1/ticker.do?symbol='
    for symbol in symbol_list:
        url = base_url + symbol
        json_data = get_url_data(url)  # Assume get_url_data() fetches JSON
        if json_data:
            _df = pd.DataFrame(json_data['ticker'], dtype='float')
            _df['symbol'] = symbol
            df = pd.concat([df, _df], ignore_index=True)
    return df[['symbol', 'last', 'buy', 'sell', 'high', 'low', 'vol']]

Output Example

symbollastbuysellhighlowvol
btc_usdt42000419504201042500418001200.5

3. Retrieving Kline (Candlestick) Data

Python Function

def get_candle_from_okex(symbol, kline_type='1min'):
    url = f'https://www.okex.com/api/v1/kline.do?symbol={symbol}&type={kline_type}'
    json_data = get_url_data(url)
    if json_data:
        df = pd.DataFrame(json_data, columns=[
            'timestamp', 'Open', 'High', 'Low', 'Close', 'Volume'
        ])
        df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
        return df

Sample Data

timestampOpenHighLowCloseVolume
2025-03-17 12:004190042050418004200045.2

👉 Explore advanced candlestick analysis techniques


FAQs

Q1: Why use MD5 for API signatures?

MD5 ensures data integrity. However, some platforms now use HMAC-SHA256 for enhanced security.

Q2: How often should I fetch ticker data?

For high-frequency strategies, poll every 1–5 seconds. For long-term analysis, hourly/daily updates suffice.

Q3: Can I backtest with Kline data?

Yes! Historical Kline data is ideal for backtesting trading algorithms.

Q4: What’s the rate limit for OKEx’s API?

OKEx allows up to 20 requests per second. Exceeding this may result in temporary bans.


Conclusion

This guide covered essential quant trading tasks:

  1. API authentication via MD5 signatures.
  2. Real-time price tracking with ticker data.
  3. Historical analysis using candlestick datasets.

For further reading, check out our quant trading strategies section.