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:
GET /api/v5/market/mark-price-candles
→ Returns recent mark price candles (limited history).GET /api/v5/market/history-mark-price-candles
→ Retrieves historical mark price candles (supports deeper time ranges).
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 usespublic_get_market_history_mark_price_candles, an implicitly generated method in CCXT that directly maps to OKX’s/history-mark-price-candlesAPI route.
Key Parameters for Historical Mark Price Requests
To ensure your requests return meaningful data, understand these required and optional parameters:
instId: Instrument ID (e.g.,ETH-USDT)bar: Timeframe (1m,5m,1H,1D, etc.)limit: Number of candlesticks (max typically 100)after: Pagination filter—returns data after this timestamp (in milliseconds)before: Returns data before this timestamp
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:
- It prevents liquidation abuse due to price manipulation.
- It's derived from a basket of spot prices across major exchanges.
- It ensures fair settlement and funding rate calculations.
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:
- Ensure the
instIdis correctly formatted (use-not/) - Confirm the
barvalue is supported (e.g.,1m,1h) - Check that timestamps are in milliseconds
- Verify the symbol exists as a futures/swap contract on OKX
- Try removing
after/beforefilters temporarily to test connectivity
⚠️ Rate Limiting
OKX enforces rate limits:
- Public endpoints: ~20 requests per 2 seconds per IP
- Use
enableRateLimit: Truein CCXT configuration
Best Practices for Working with Historical Data
- Paginate Properly: Use
afterorbeforeto move through large datasets. - Cache Responses: Avoid repeated API calls; store results locally.
- Validate Symbol Types: Make sure you're querying swap or future instruments.
- Handle Errors Gracefully: Wrap API calls in try-except blocks.
Core Keywords Summary
This guide focuses on key terms essential for developers and traders:
- OKX API
- fetch_mark_ohlcv
- history-mark-price-candles
- CCXT Python
- mark price candlesticks
- historical OHLCV
- crypto market data
- perpetual futures
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.