OKX Local and Real-Time Market Candle Server

·

The OKX local and real-time market candle server is a powerful Python-based tool designed to streamline access to historical and live market data from the OKX exchange. Whether you're building a backtesting engine, running live trading algorithms, or analyzing price trends, this server provides efficient data retrieval, storage, and real-time updates across multiple product types—including spot, perpetual swaps, futures, and options.

Built with scalability and ease of use in mind, the tool supports automated downloads, multi-threaded updates, and flexible configuration to suit various trading strategies.


Core Features and Use Cases

1. Historical Data for Local Backtesting

Accurate historical K-line (candlestick) data is essential for strategy validation. This server enables seamless downloading and management of historical data for:

Data is stored in daily CSV files for fast access and minimal disk overhead—no external databases required.

2. Real-Time Market Data for Live Trading

Stay ahead with real-time candle updates and live market feeds. The server:

👉 Discover how to integrate real-time trading signals today


Getting Started

Installation

Install the package via pip:

pip install okx-candle
Note: The original GitHub repository has been deprecated. All functionality is now consolidated under the unified okx package.

Quick Start Guide

1. Maintain Real-Time Candle Data (candle_map)

Use run_candle_map() to continuously update candle data in real time using multithreading.

from okx_candle import CandleServer
from pprint import pprint

candleServer = CandleServer('SWAP')  # For perpetual contracts
candleServer.run_candle_map()

# Access real-time data
pprint(candleServer.candle_map)

Output example:

{
  'BTC-USD-SWAP': array([
    [1.67556558e+12, 23318.0, 23318.1, ..., 1.9299, 45000, 1.0],
    [1.67556564e+12, 23317.8, 23317.8, ..., 0.7122, 16600, 1.0],
    ...
  ])
}

Each row represents a candle with fields: [timestamp, open, high, low, close, volume, turnover, confirm].


2. Daily Historical K-Line Downloads

Automatically download yesterday’s data at a scheduled time.

from okx_candle import CandleServer

candleServer = CandleServer('SPOT')  # For spot trading
candleServer.download_daily()

This runs asynchronously and respects your configured timezone and bar intervals.


3. Fetch Real-Time Market Tickers

Get live price data across all instruments.

bookTickerMap = candleServer.market.get_tickersMap()
pprint(bookTickerMap)

Returns bid/ask prices, 24h volume, price change, and more—perfect for monitoring opportunities.


Data Structure and Storage

K-Line Format

Candles are stored as np.ndarray (NumPy arrays) using float64 for high-speed numerical operations. This ensures fast processing during backtesting and live trading.

⚠️ Note: While float types are safe for analysis, always use strings when submitting order parameters (e.g., price, quantity) to avoid floating-point precision issues.

Storage Rules

This structure allows efficient loading and sharing across projects.


Data Integrity Checks

All candles undergo strict validation:

These checks prevent corrupted or incomplete data from affecting your models.


Configuration via CandleRule

Customize behavior using the CandleRule class to fit your strategy needs.

from okx_candle import CandleServer, CandleRule

CandleRule.BAR = '5m'  # Use 5-minute candles
candleServer = CandleServer('SPOT', CandleRule)

Key Rule Parameters

Product Filtering

Example: To track only USDT pairs:

CandleRule.SYMBOLS = 'all'
CandleRule.SYMBOL_ENDSWITH = 'USDT'

Time & Storage Settings

💡 Set DOWNLOAD_TIME after a short delay (e.g., 00:10:00) to avoid missing final bars due to API latency.

Real-Time Updates

👉 Maximize your data pipeline efficiency with smart caching


Advanced Usage

Secure Access to Live Candles

Use get_candle_security() to verify freshness before making trade decisions.

while True:
    for symbol in candleServer.candle_map:
        safe_candle = candleServer.get_candle_security(symbol, security_seconds=60)
        if len(safe_candle) > 0:
            print(f"{symbol}: Valid data available")
    time.sleep(1)

Returns empty array if data lags behind current time by more than threshold.


Manual Historical Data Download

Download specific date ranges:

candleServer.download_candles_by_date(
    start='2023-01-01',
    end='2023-01-10'
)

Supports timestamps, strings (YYYY-MM-DD), or datetime objects—automatically converted using configured timezone.


Close Services Gracefully

Always shut down services properly to avoid file corruption:

candleServer.close_run_candle_map()     # Stop real-time updates
candleServer.close_download_daily()     # Stop scheduled downloads

Both methods wait for ongoing tasks to complete safely.


Market Data Access

Access full market information via the Market module:

from okx_candle import Market

market = Market(instType='SPOT', timezone='Asia/Shanghai')
tickers = market.get_tickersMap()

Available methods include:

All responses follow standard format: {code: '0', data: {...}, msg: ''}


Trading Rules & Instrument Info

Retrieve trading specifications efficiently with built-in caching:

exchange_info = Market('SWAP').get_exchangeInfo('BTC-USDT-SWAP')

Includes:

Cached by default; refresh by setting expire_seconds=0.


Local K-Line Management with OkxLite

Use OkxLite for direct file-level control over stored candles.

from okx_candle import OkxLite

okxLite = OkxLite()
candle = okxLite.load_candle_by_date(
    instType='SWAP',
    symbol='BTC-USDT-SWAP',
    start='2023-02-05',
    end='2023-02-06'
)

Key Functions

Default settings can be viewed and modified via:

candlelite show_settings
candlelite console_settings

Set absolute paths (e.g., /root/CANDLELITE_DATA) to share data across environments.


Frequently Asked Questions (FAQ)

Q: Is authentication required to fetch market data?
A: No. Public endpoints like tickers and K-lines do not require API keys.

Q: Can I use this with Binance as well?
A: Yes! The interface is nearly identical to Binance_candle—ideal for multi-exchange strategies.

Q: How do I prevent missing the last candle of the day?
A: Delay your download time using DOWNLOAD_TIME (e.g., set to 00:10:00) to allow OKX’s servers time to finalize data.

Q: What happens if internet connection drops?
A: The system will retry on reconnect. Local cache helps minimize data loss during brief outages.

Q: Can I change the default storage path?
A: Yes. Modify CANDLE_BASE_DIR via configuration tools or set custom paths in each function call.

Q: Does it support margin trading?
A: No. Margin (cross/isolated) products are not supported at this time.


👉 Start building your next-gen trading system with reliable market data