Okx_candle: Python Tool for OKX Historical and Real-Time K-Line Data Management

·

The Okx_candle library is a powerful Python tool designed for developers, traders, and quantitative analysts who need efficient access to historical and real-time K-line data from the OKX exchange. Built with performance and usability in mind, this tool supports multiple trading products — including spot, perpetual swaps, futures, and options — and enables seamless integration into local backtesting systems or live trading strategies.

Whether you're building a high-frequency trading bot or analyzing long-term market trends, Okx_candle simplifies data handling with fast storage, retrieval, and real-time synchronization features.

👉 Discover how to power your trading strategy with reliable market data

Core Features of Okx_candle

Okx_candle is engineered for both local simulation trading and live decision-making, offering two primary use cases:

Designed to mirror the interface of Binance_candle, it reduces the learning curve for multi-exchange algorithmic traders, ensuring a consistent workflow across platforms.

Supported Products and Use Cases

Product TypeUse Case
SPOTSpot trading backtesting & monitoring
SWAPPerpetual contract analysis
FUTURESExpiry-based derivatives modeling
OPTIONOptions pricing and volatility studies
⚠️ Note: Margin (leveraged spot) trading is currently not supported.

Installation and Setup

Getting started with Okx_candle is straightforward using pip:

pip3 install okx_candle

For source access or contribution, visit the official repository on GitHub. No API keys are required for public market data access, though authenticated endpoints can be added if needed.

Once installed, you can begin fetching data immediately.

👉 Start integrating real-time K-lines into your strategy today


Quick Start Guide

1. Maintain Real-Time K-Line Data with candle_map

Use run_candle_map() to asynchronously maintain an up-to-date dictionary of K-line data for any supported product type.

from okx_candle import CandleServer
from pprint import pprint

# Initialize for perpetual swap contracts
candleServer = CandleServer('SWAP')
candleServer.run_candle_map()

# Access live K-line data
pprint(candleServer.candle_map)

This creates a candle_map dictionary where each key is a trading pair (e.g., BTC-USD-SWAP) and the value is a NumPy array containing time-series K-line data.


2. Schedule Daily Historical Data Downloads

Automate daily downloads of previous day’s K-line data for backtesting purposes.

from okx_candle import CandleServer

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

This function runs asynchronously and uses configurable timing (DOWNLOAD_TIME) to fetch complete daily bars after market close.


3. Fetch Real-Time Market Tickers

Retrieve live ticker information such as best bid/ask, 24-hour volume, and price changes.

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

Ideal for monitoring price movements or validating trade signals across multiple instruments.


Understanding K-Line Data Format

To maximize performance, all K-line data is stored as np.ndarray with optimized memory layout.

Column Structure of K-Line Arrays

IndexFieldDescriptionExample Value
0tsOpen timestamp (milliseconds)1675565580000
1oOpen price23318.0
2hHighest price23318.1
3lLowest price23307.8
4cClose price22885.1
5volVolume in contracts or base currency45000
6volCcyVolume in quote currency100.2
7volCcyQuoteVolume in settled currency (e.g., USDT/USD)98.7
8confirm1 = closed bar; 0 = incomplete1.0

All numeric values are converted to float64 for consistency during computation. However, when placing orders via APIs, string-based precision is recommended to avoid floating-point errors.


Local Storage & Data Integrity

Date-Based CSV Storage

Historical K-lines are split by date and saved as CSV files. Each file covers one full calendar day based on the configured timezone (Asia/Shanghai by default). For example:

This structure ensures fast I/O operations and easy manual inspection.

Built-In Data Validation

Okx_candle enforces strict validation rules:

These checks ensure that only accurate, complete datasets are used in analysis or live trading systems.


Customizing Behavior with CandleRule

The CandleRule class allows fine-grained control over data behavior.

Example: Configure 5-Minute Bars for Specific Symbols

from okx_candle import CandleServer, CandleRule

CandleRule.BAR = '5m'
CandleRule.SYMBOLS = ['BTC-USDT', 'ETH-USDT']
candleServer = CandleServer('SPOT', CandleRule)

Key Configuration Options

Symbol Filtering

Time & Storage Settings

Real-Time Updates

Logging

Logs are split by date and level under LOG_DIRPATH. Default levels:


Advanced Data Management

Download Historical Data by Date Range

Use download_candles_by_date() to fetch custom date ranges:

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

Supports various input formats: timestamps, strings, or Python date objects.


Load Historical Data Locally with OkxLite

Use the lightweight OkxLite module to read pre-downloaded data:

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'
)

You can also load all symbols at once using load_candle_map_by_date() with optional filters.


Save Data Programmatically

Export processed or filtered data using:

okxLite.save_candle_by_date(
    candle=candle,
    instType='SWAP',
    symbol='BTC-USDT-SWAP',
    start='2023-02-05',
    base_dir='./backup'
)

Includes options for deduplication, sorting, and validation.


Accessing Market Information

Beyond K-lines, Okx_candle provides rich market data APIs:

Ticker Data

Order Book Depth

Trading Rules & Instrument Metadata

Cached responses improve speed without sacrificing accuracy.


Frequently Asked Questions (FAQ)

Q: Can I use Okx_candle without an API key?
A: Yes! Public market data like K-lines and tickers do not require authentication.

Q: Is margin trading supported?
A: No. Only SPOT, SWAP, FUTURES, and OPTION are currently supported.

Q: How does timezone affect data storage?
A: The TIMEZONE setting determines how days are split. By default, 'Asia/Shanghai' is used to align with Asian market hours.

Q: What happens if I set DOWNLOAD_TIME too early?
A: You may miss the final bar due to exchange-side delays (typically 0–2 minutes). Set it after 00:02:00 for reliability.

Q: Can multiple projects share the same historical data?
A: Yes. Configure a shared CANDLE_BASE_DIR path so different scripts can access the same dataset.

Q: How do I ensure data safety during service restarts?
A: Use the built-in caching (CACHE_DELAY_SECONDS) and graceful shutdown methods like close_run_candle_map().


Final Thoughts

Okx_candle bridges the gap between raw exchange data and actionable insights. With robust support for historical downloads, real-time updates, and flexible configuration, it empowers developers to build reliable quantitative systems on top of OKX market data.

Its design prioritizes speed, correctness, and ease of use — making it ideal for backtesting engines, live trading bots, and research pipelines alike.

👉 Unlock advanced market analytics with OKX’s comprehensive data ecosystem