OKX Local and Real-Time Market Candle Server

·

The OKX local and real-time market candle server is a powerful Python-based tool designed for traders, developers, and quantitative analysts who require efficient access to historical and live market data from the OKX exchange. Built with performance and usability in mind, this solution supports multiple trading products including spot, perpetual swaps, futures, and options, making it ideal for both backtesting strategies and executing real-time trading decisions.

While the original okx_candle project has been discontinued and its functionality merged into a broader framework (pyted/okx), its core design principles live on—offering fast data retrieval, robust validation, and seamless integration with existing quant workflows.


Key Features and Use Cases

1. Historical K-Line Data for Backtesting

Accurate historical candlestick (K-line) data is essential for developing and testing algorithmic trading strategies. The server enables:

This makes it perfect for simulating trading strategies without relying on live API calls, reducing latency and dependency on network conditions.

👉 Discover how top traders access real-time market data securely

2. Real-Time Market Data Caching

For live trading applications, having up-to-date price information is crucial. The system provides:

By maintaining a candle_map dictionary updated in real time, traders can build responsive systems that react instantly to market changes.


Getting Started with the Candle Server

Installation

Although the standalone okx_candle package is no longer maintained, its successor integrates directly into the unified pyted/okx ecosystem. You can install it via pip:

pip install okx-candle

Ensure you have dependencies like numpy, pandas, and candlelite properly configured for optimal performance.

Quick Start Examples

Maintain Real-Time Candle Data (candle_map)

Use run_candle_map() to asynchronously update a dictionary of live K-line data:

from okx_candle import CandleServer
import pprint

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

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

Each entry in candle_map follows the format:

candle_map[symbol] = np.ndarray([[timestamp, open, high, low, close, vol, ...], ...])

This structure ensures high-speed numerical operations during strategy execution.

Daily Automated K-Line Downloads

Schedule automatic downloads of yesterday’s full-day K-line data:

from okx_candle import CandleServer

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

This function runs asynchronously and respects your configured timezone (default: Asia/Shanghai), ensuring complete and accurate daily datasets.

Fetch Live Market Ticker Information

Retrieve real-time price data for all perpetual swap pairs:

book_ticker_map = candle_server.market.get_tickersMap()
pprint.pprint(book_ticker_map)

Output includes bid/ask prices, 24h volume, price change, and more—ideal for monitoring market sentiment.


Understanding K-Line Data Structure

Data Format and Performance Optimization

To maximize speed and efficiency:

Storage Architecture

Historical K-lines are stored in daily CSV files, split by date and product type. Each file covers:

This approach allows easy sharing of datasets across multiple projects and avoids database setup complexity.

Data Integrity Checks

Every K-line undergoes strict validation:

These safeguards prevent corrupted or incomplete data from affecting your analysis.


Customizing Behavior with CandleRule

The CandleRule class lets you tailor the server’s behavior to your specific needs.

Example: Configure 5-Minute Bars for USDT Pairs

from okx_candle import CandleServer, CandleRule

CandleRule.BAR = '5m'
CandleRule.SYMBOLS_ENDSWITH = 'USDT'
candle_server = CandleServer('SPOT', CandleRule)

Now only USDT-denominated spot pairs will be processed at 5-minute intervals.

Core Configuration Options

ParameterDescription
BARTime granularity (1m, 5h, 1d)
SYMBOLSList of symbols or 'all'
SYMBOLS_ENDSWITHFilter symbols ending with specific string
TIMEZONETimezone for file naming and date splitting
CANDLE_DIRRoot directory for storing historical data
DOWNLOAD_TIMEWhen to fetch yesterday's data (e.g., '00:10:00')
⚠️ Avoid setting DOWNLOAD_TIME too early (like '00:00:00')—OKX may not have finalized the last bar of the day.

Managing Real-Time Candle Updates

Using run_candle_map()

This method:

Use close_run_candle_map() to safely shut down the service without corrupting saved data.

Secure Access with get_candle_security()

Since exchange APIs may lag by up to 2 minutes, always validate freshness before acting:

secure_candle = candle_server.get_candle_security('BTC-USDT-SWAP', security_seconds=60)
if len(secure_candle) > 0:
    print("Data is current")
else:
    print("Data outdated or unavailable")

This ensures your logic doesn’t act on stale information.


Advanced Data Management with OkxLite

What Is OkxLite?

A lightweight I/O layer built on top of candlelite, allowing direct reading/writing of local K-line files without needing a database.

Load Historical Data by Date Range

from okx_candle import OkxLite
okx_lite = OkxLite()

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

Convert to DataFrame for analysis:

from okx_candle.utils import candle_to_df
df = candle_to_df(candle)

👉 Access high-frequency trading tools trusted by professionals


Frequently Asked Questions (FAQ)

Q1: Is the okx_candle library still supported?

No, active development has ceased. Its features are now integrated into the broader pyted/okx framework. Users should migrate to the new package for ongoing updates and support.

Q2: Can I use this with other exchanges like Binance?

Yes! The interface is nearly identical to binance_candle, minimizing learning curves for multi-exchange quant traders. This consistency simplifies building cross-platform strategies.

Q3: Does it require an API key?

No. Market data retrieval does not require authentication. However, private account data or trading functions will need valid OKX API credentials.

Q4: How is data stored locally?

In date-partitioned CSV files under a structured folder hierarchy (e.g., /OKX/SPOT/BTC-USDT/2023-02-05.csv). No external database is needed.

Q5: Can I share data between different projects?

Yes. By setting a global base directory (via CANDLE_BASE_DIR), multiple local projects can reuse the same cached K-line data—saving bandwidth and storage.

Q6: What timezones are supported?

Any valid IANA timezone (e.g., Asia/Shanghai, America/New_York). Default is set to 'Asia/Shanghai'.


Final Thoughts

Whether you're building a backtesting engine or deploying a live trading bot, the OKX local candle server delivers reliable, high-performance access to critical market data. With flexible configuration, strong validation, and clean integration into Python quant stacks, it remains a valuable asset in any trader’s toolkit—even as it evolves into more advanced frameworks.

👉 Start leveraging real-time crypto market data today