How to Fetch Historical Mark Price Candlestick Data Using OKX API and CCXT

·

Cryptocurrency traders and developers often rely on accurate historical data to backtest strategies, analyze market trends, and build automated trading systems. One critical data type is the mark price, which helps prevent manipulation in derivative markets by reflecting a fair value based on underlying spot prices across exchanges.

When working with the OKX exchange via the popular CCXT library, you might encounter a challenge: the fetch_mark_ohlcv method calls the /api/v5/market/mark-price-candles endpoint, but this only returns recent mark price data—not extended historical records.

So how do you access historical mark price candlesticks for assets like ETH/USDT using Python and CCXT? Let’s dive into the solution.

Understanding the Difference: Real-Time vs. Historical Mark Price Endpoints

OKX provides two distinct REST API endpoints for mark price data:

While CCXT’s built-in fetch_mark_ohlcv() method maps to the first endpoint, it does not automatically use the historical one—leaving developers needing longer-term data without direct support.

👉 Access full market data APIs and advanced trading tools with OKX.

Using CCXT to Call the Hidden Historical Endpoint

Even though CCXT doesn’t expose a dedicated fetch_history_mark_ohlcv() function, you can still access the history-mark-price-candles endpoint using CCXT’s implicit API methods.

Here’s how:

import ccxt.pro as ccxt
import asyncio
import time

async def fetch_historical_mark_price():
    exchange = ccxt.okx({
        'enableRateLimit': True,
        'options': {
            'defaultType': 'future',  # or 'swap' depending on contract type
        }
    })

    # Define parameters
    symbol = 'ETH/USDT'
    timeframe = '1m'
    limit = 100

    # Convert to OKX format (e.g., ETH-USDT)
    instId = symbol.replace('/', '-')

    # Optional: set since timestamp (e.g., 24 hours ago)
    since = int(time.time() - 24 * 60 * 60) * 1000  # milliseconds

    # Use implicit method to call the historical endpoint
    response = await exchange.public_get_market_history_mark_price_candles({
        'instId': instId,
        'bar': timeframe,
        'limit': limit,
        # 'after': since,  # optional pagination
    })

    await exchange.close()
    return response

# Run the async function
result = asyncio.run(fetch_historical_mark_price())
print(result)
✅ This approach uses public_get_market_history_mark_price_candles, an implicitly generated method in CCXT that directly maps to OKX’s /history-mark-price-candles API route.

Key Parameters for Historical Mark Price Requests

To ensure your requests return meaningful data, understand these required and optional parameters:

These allow precise control over date ranges and avoid rate limits through proper pagination.

Why Use Mark Price Instead of Last Traded Price?

In perpetual futures markets, mark price is crucial because:

Using last traded price for strategy evaluation can lead to misleading results—especially during volatility spikes.

Therefore, when backtesting or analyzing perpetual contracts, always prefer mark price OHLCV over regular price data.

👉 Start leveraging real-time and historical crypto data with powerful trading APIs.

Common Issues and Troubleshooting

❌ Empty Data Response ("data": [])

If your request returns an empty array:

⚠️ Rate Limiting

OKX enforces rate limits:

Best Practices for Working with Historical Data

  1. Paginate Properly: Use after or before to move through large datasets.
  2. Cache Responses: Avoid repeated API calls; store results locally.
  3. Validate Symbol Types: Make sure you're querying swap or future instruments.
  4. Handle Errors Gracefully: Wrap API calls in try-except blocks.

Core Keywords Summary

This guide focuses on key terms essential for developers and traders:

These keywords reflect high-intent searches related to algorithmic trading, data analysis, and exchange integration.

👉 Unlock deep market insights with professional-grade crypto trading tools.

Frequently Asked Questions (FAQ)

Q: Does CCXT natively support fetching historical mark price candles?
A: No, CCXT does not have a built-in method like fetch_history_mark_ohlcv. You must use the implicit public_get_market_history_mark_price_candles() method instead.

Q: What’s the difference between /mark-price-candles and /history-mark-price-candles?
A: The former returns recent data only (usually up to a few hundred candles), while the latter allows retrieval of older, archived mark price data for long-term analysis.

Q: Can I use this method for spot markets?
A: No. Mark price is primarily used in derivatives (futures/perpetuals). For spot OHLCV, use fetch_ohlcv() instead.

Q: Is authentication required for historical mark price data?
A: No. Both endpoints are public and do not require API keys.

Q: How far back can I retrieve historical mark price data?
A: OKX typically retains several months to a year of historical data, but exact depth may vary. Always paginate using timestamps to explore full availability.

Q: Why am I getting empty responses even with valid parameters?
A: Double-check timestamp units (must be milliseconds), correct instrument ID format (e.g., ETH-USDT), and network connectivity. Also, ensure the contract was active during the requested period.


By combining CCXT’s flexibility with OKX’s robust API structure, you can efficiently retrieve reliable historical mark price data—essential for serious quantitative analysis and strategy development.