Managing high-quality historical market data is essential for both backtesting and live trading strategies in cryptocurrency markets. Okx_candle is a powerful Python library designed to streamline the collection, storage, and real-time access of K-line data from the OKX exchange across multiple product types — including spot, perpetual swaps, futures, and options.
Built for speed and reliability, okx_candle supports efficient local data handling using NumPy arrays and CSV-based date-partitioned storage, enabling fast read/write operations without requiring external databases. Whether you're developing quantitative models or maintaining live trading systems, this tool ensures timely and accurate data flow.
Key Features of Okx_candle
The primary objectives behind okx_candle are clear:
- Provide historical K-line data for local backtesting
- Support real-time decision-making with up-to-date market information
- Offer seamless compatibility with Binance_candle (95%+ similarity), reducing learning overhead for multi-exchange traders
This makes it an ideal choice for algorithmic traders who need consistent, reliable data pipelines across exchanges.
👉 Discover how to leverage real-time trading data with powerful tools on OKX
Installation and Setup
Getting started with okx_candle is simple via pip:
pip3 install okx_candleYou can also access the source code and contribute or review implementation details on GitHub (link removed per policy).
Quick Start Guide
1. Maintain Real-Time Historical K-Line Data with candle_map
The CandleServer class allows you to maintain a continuously updated dictionary of real-time K-line data using multithreading.
For perpetual swap contracts:
from okx_candle import CandleServer
from pprint import pprint
candleServer = CandleServer('SWAP') # Supports SPOT, SWAP, FUTURES, OPTION
candleServer.run_candle_map()
pprint(candleServer.candle_map)This returns a dictionary where each key is a trading pair (e.g., BTC-USD-SWAP) and the value is a NumPy array containing K-line data.
2. Daily Scheduled Download of Historical K-Lines
To automatically download yesterday’s K-line data every day (ideal for backtesting):
from okx_candle import CandleServer
candleServer = CandleServer('SPOT')
candleServer.download_daily()This asynchronous function ensures your local dataset stays current without manual intervention.
3. Fetch Real-Time Market Ticker Information
Get up-to-the-second price and volume data across all instruments:
bookTickerMap = candleServer.market.get_tickersMap()
pprint(bookTickerMap)Returns bid/ask prices, 24h volume, last traded price, and more — formatted as a clean dictionary.
Understanding K-Line Data Format
K-line data in okx_candle is stored as np.ndarray (NumPy arrays) for optimal performance during computation.
| Index | Field | Description |
|---|---|---|
| 0 | ts | Open timestamp (milliseconds) |
| 1 | o | Open price |
| 2 | h | High price |
| 3 | l | Low price |
| 4 | c | Close price |
| 5 | vol | Volume in contracts (derivatives) or base currency (spot) |
| 6 | volCcy | Volume in base currency |
| 7 | volCcyQuote | Volume in quote currency (e.g., USDT, USD) |
| 8 | confirm | 1 = completed candle, 0 = incomplete |
All values are converted to float64 for consistency. For order execution, string-based precision is recommended to avoid floating-point errors.
Data Storage Rules and Timezone Handling
Historical K-lines are stored in daily CSV files (YYYY-MM-DD.csv) split by date. Each file covers timestamps from 00:00:00 to 23:59:00, depending on the bar interval (e.g., 1-minute bars end at 23:59:00).
By default, Asia/Shanghai timezone is used to align with OKX's regional conventions, ensuring correct day boundaries regardless of system locale.
Supported Product Types (instType)
When initializing CandleServer, specify one of these supported product categories:
SPOT: Spot tradingSWAP: Perpetual contractsFUTURES: Delivery futuresOPTION: Options
Note: Margin trading (MARGIN) is not supported.Customizing Behavior with CandleRule
Use the CandleRule class to fine-tune behavior based on your strategy needs.
from okx_candle import CandleServer, CandleRule
CandleRule.BAR = '5m' # Set time granularity to 5 minutes
candleServer = CandleServer('SPOT', CandleRule)Symbol Filtering Options
SYMBOLS = 'all': Include all pairsSYMBOLS = ['BTC-USDT', 'ETH-USDT']: Only selected symbolsSYMBOLS_FILTER: Exclude specific symbolsSYMBOL_CONTAINS = 'BTC': Include only those containing "BTC"SYMBOL_ENDSWITH = 'USDT': Filter by quote currency
👉 Explore advanced trading strategies using high-frequency data
K-Line Parameters
BAR: Time intervals supported —'1m','5m','15m','1h','4h','1d'- Configurable defaults via
candlelite show_settings,console_settings, or editing config paths directly
Scheduling & Caching Settings
DOWNLOAD_TIME: Set daily download time (default:'00:10:00') to avoid early fetch failures due to API delaysLOCAL_CANDLE_DAYS: Preload N days of history on startupLENGTH: Number of latest candles retained in memory (default: 2880)UPDATE_INTERVAL_SECONDS: Polling frequency (default: 3 seconds)CACHE_DELAY_SECONDS: Auto-save cache every N seconds (default: 3600)CACHE_DIR: Directory for cached real-time data (./OKX_CACHE)
Managing Real-Time K-Line Dictionary (candle_map)
Using run_candle_map()
Starts an asynchronous thread that:
- Downloads initial historical data
- Updates K-lines in real time
- Validates integrity (interval, length, timestamps)
If any validation fails, the affected symbol is removed from candle_map.
Safe Access with get_candle_security()
Ensures the latest K-line isn't stale:
candle = candleServer.get_candle_security(symbol, security_seconds=60)Returns empty array if data lags behind current time by more than the specified threshold.
Graceful Shutdown
Use close_run_candle_map() to safely terminate background threads and prevent data corruption during writes.
Downloading Historical K-Lines
Bulk Download by Date Range
Use download_candles_by_date() to fetch historical data between two dates:
candleServer.download_candles_by_date(start='2023-01-01', end='2023-01-10')Supports flexible input formats:
- Millisecond timestamps
- ISO date strings (
YYYY-MM-DD) - Pendulum or datetime objects
Data is validated for continuity and correctness before saving.
Daily Automated Downloads
Enable scheduled updates with:
candleServer.download_daily()Automatically downloads prior day’s data at the configured DOWNLOAD_TIME. Use close_download_daily() to stop gracefully.
Accessing Real-Time Market Data
The Market module provides direct access to live exchange data:
from okx_candle import Market
market = Market(instType='SWAP', timezone='Asia/Shanghai')Available methods include:
get_tickers(): List of all market tickersget_tickersMap(): Dictionary indexed by symbolget_ticker(symbol): Single instrument detailsget_books(symbol, sz=10): Order book depthget_books_lite(symbol): Lightweight depth feed
All responses follow standard format: {code: '0', data: {...}, msg: ''}
Exchange Information & Trading Rules
Retrieve comprehensive trading specifications:
get_exchangeInfos(): Full ruleset for all instrumentsget_exchangeInfo(symbol): Details for a single pair (e.g., tick size, lot size)get_symbols_trading_on(): Active tradable symbolsget_symbols_trading_off(): Inactive/non-trading symbols
Results are cached by default (TTL: 300 seconds) to reduce API load and improve response speed.
Local Data Management with OkxLite
For direct file-level control over stored K-lines, use the OkxLite class.
Load Data by Date Range
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'
)Includes automatic validation options (valid_interval, valid_start, etc.).
Load Multiple Instruments at Once
candle_map = okxLite.load_candle_map_by_date(instType='SWAP', start='2023-02-05')Uses multiprocessing (p_num=4) for faster loading of large datasets.
Save Custom Data Ranges
Export processed or filtered data locally:
okxLite.save_candle_by_date(candle, instType, symbol, start, end, base_dir='./custom_data')Supports deduplication, sorting, and overwrite controls.
Frequently Asked Questions (FAQ)
Q: Do I need an API key to use okx_candle?
A: No. Public market and K-line data can be accessed without authentication. API keys are only required for private account endpoints (not used in this library).
Q: Can I use this with other exchanges like Binance?
A: Yes. The design closely mirrors Binance_candle, making it easy to port logic between platforms and build multi-exchange trading systems.
Q: How does data validation work?
A: Every dataset is checked for correct time intervals, proper start/end alignment, and expected row count. Invalid entries are rejected or trigger re-fetching.
Q: Is there support for minute-level and hourly bars?
A: Yes. Supported intervals include 1m, 5m, 15m, 1h, 4h, and 1d — configurable via the BAR parameter.
Q: Can I share data between multiple projects?
A: Absolutely. By setting a shared base directory (e.g., /root/CANDLELITE_DATA), multiple local environments can access the same cached K-line files.
Q: What happens if the internet connection drops?
A: The system relies on cached data when available. Upon reconnect, missing segments can be refetched using date-range download functions.
👉 Maximize your strategy performance with real-time market insights on OKX
Final Thoughts
okx_candle bridges the gap between raw exchange APIs and practical algorithmic trading needs. With robust local storage, real-time synchronization, flexible filtering, and efficient memory usage, it empowers developers to focus on strategy logic rather than infrastructure challenges.
Whether you're conducting deep historical analysis or running live bots on OKX, this library delivers the performance and reliability needed for success in today’s fast-moving crypto markets.