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:
- Historical Data Management: Download, store, and manage historical K-line data across OKX’s major product types: Spot (SPOT), Perpetual Swaps (SWAP), Futures (FUTURES), and Options (OPTION).
- Real-Time Market Feeds: Continuously update cached K-line data for real-time strategy execution and analysis.
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 Type | Use Case |
|---|---|
| SPOT | Spot trading backtesting & monitoring |
| SWAP | Perpetual contract analysis |
| FUTURES | Expiry-based derivatives modeling |
| OPTION | Options 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_candleFor 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
| Index | Field | Description | Example Value |
|---|---|---|---|
| 0 | ts | Open timestamp (milliseconds) | 1675565580000 |
| 1 | o | Open price | 23318.0 |
| 2 | h | Highest price | 23318.1 |
| 3 | l | Lowest price | 23307.8 |
| 4 | c | Close price | 22885.1 |
| 5 | vol | Volume in contracts or base currency | 45000 |
| 6 | volCcy | Volume in quote currency | 100.2 |
| 7 | volCcyQuote | Volume in settled currency (e.g., USDT/USD) | 98.7 |
| 8 | confirm | 1 = closed bar; 0 = incomplete | 1.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:
- A
1mbar file contains 1440 entries from00:00:00to23:59:00. - A
1hbar file ends at23:00:00.
This structure ensures fast I/O operations and easy manual inspection.
Built-In Data Validation
Okx_candle enforces strict validation rules:
- Time interval consistency (
valid_interval) - Correct start/end timestamps (
valid_start,valid_end) - Expected length verification (
valid_length)
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
SYMBOLS: List specific pairs or set'all'SYMBOLS_FILTER: Exclude certain symbolsSYMBOL_CONTAINS: Include only those containing a substring (case-sensitive)SYMBOL_ENDSWITH: Filter by suffix (e.g.,'USDT')
Time & Storage Settings
BAR: Time granularity (1m,5m,1h,1d)TIMEZONE: Controls file naming and daily boundariesCANDLE_DIR: Root directory for stored dataDOWNLOAD_TIME: When to fetch yesterday’s data (default:00:10:00)
Real-Time Updates
UPDATE_INTERVAL_SECONDS: Polling frequency (default: 3 seconds)CACHE_DELAY_SECONDS: Auto-save cache every N seconds (default: 3600)CACHE_DIR: Location of cachedcandle_map
Logging
Logs are split by date and level under LOG_DIRPATH. Default levels:
- File:
'INFO' - Console:
'DEBUG'
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
get_tickers(): List format of all tickersget_tickersMap(): Dictionary keyed by symbolget_ticker(symbol): Single instrument details
Order Book Depth
get_books(symbol, sz=10): Full depth up to N levelsget_books_lite(symbol): Lightweight snapshot
Trading Rules & Instrument Metadata
get_exchangeInfos(): Full exchange configurationget_exchangeInfo(symbol): Rules for a specific pairget_symbols_trading_on(): Active instruments listget_symbols_trading_off(): Inactive/inactive pairs
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