CCXT fetch_ohlcv Pagination: Download Full Candle History
CCXT fetch_ohlcv pagination means looping with since set to the last candle timestamp plus one timeframe and an explicit limit. Stop on an empty page or no progress, not on a short page. Dedupe, sort and save every page.
- Advance since to last_ts + timeframe_ms, never last_ts, or every page repeats its boundary candle.
- Stop on an empty batch, no timestamp progress, or an end bound, never on len(batch) < limit.
- Retry only ccxt.NetworkError (which includes RateLimitExceeded) with backoff and jitter, and retry the same since.
- Store timestamps as UTC millisecond integers under a unique (symbol, timeframe, ts) key so restarts resume from max(ts) + tf_ms.
- Validate afterwards by checking that diff of timestamps equals the timeframe in ms, and use bulk dumps when REST would need thousands of requests.
Why does fetch_ohlcv return only 500 to 1000 candles?
Every exchange caps how many candles one OHLCV request can return, and when you omit since the exchange returns the most recent page. That is the 'only the latest few hundred candles' symptom. The cap protects the exchange's database, so history has to be pulled one page at a time.
CCXT does not expose the maximum uniformly. Check exchange.has['fetchOHLCV'] to confirm support, then pass limit explicitly, because the default is often smaller than the maximum. If you request more than the cap, most exchanges silently clamp it and a few raise an error. The values below are commonly seen, but they change, so confirm them against the exchange's own API reference (the first of the two official-source mentions here).
| Exchange | Typical max per request | Notes |
|---|---|---|
| Binance spot | 1000 | Futures endpoints allow up to 1500 |
| Bybit | 1000 spot/linear, 200 on some endpoints | Limit depends on market type |
| OKX | 100 to 300 | Differs between the recent and history endpoints |
| Kraken | 720 | Pages can be shorter than the cap |
| Coinbase | 300 | Short pages are normal |
| KuCoin | 1500 | Spot candle endpoint |
How does CCXT fetch_ohlcv pagination work with the since parameter?
The loop is simple, but the details decide whether you get gaps or duplicates. since is an inclusive millisecond timestamp of a candle open time, so reusing the last timestamp returns that candle again. Setting since = last_ts + timeframe_ms lands exactly on the next candle.
Get the timeframe in milliseconds from exchange.parse_timeframe(timeframe) * 1000, which handles '1m', '4h', '1d' and so on. For '1M' months the length varies, so month bars need a calendar-aware step instead.
- Compute tf_ms and an exclusive end bound: the current time floored to a timeframe boundary, so the still-forming candle is excluded.
- Call fetch_ohlcv(symbol, timeframe, since=cursor, limit=limit).
- Sort the batch ascending and discard rows outside [cursor, end).
- If nothing is left, or the last timestamp is below the cursor, stop.
- Yield or save the batch, then set cursor = last_ts + tf_ms and repeat.
What does a complete, resumable fetch_all_ohlcv look like?
The generator below handles retries, newest-first responses, the forming candle and the no-progress check. The SQLite part writes per page with INSERT OR IGNORE, so a crash loses at most one batch and a rerun resumes from max(ts) + tf_ms.
Timestamps stay as UTC millisecond integers in storage. Convert to datetime only inside pandas.
import random, sqlite3, time
import ccxt
import pandas as pd
RETRYABLE = (ccxt.NetworkError,) # includes RateLimitExceeded, RequestTimeout
# BadSymbol and AuthenticationError are not NetworkError: they propagate.
def _fetch_page(ex, symbol, tf, since, limit, params, max_retries=8):
for attempt in range(max_retries):
try:
return ex.fetch_ohlcv(symbol, tf, since, limit, params)
except RETRYABLE:
if attempt == max_retries - 1:
raise
delay = min(60, 2 ** attempt) + random.uniform(0, 1)
time.sleep(delay) # then retry the SAME since
def fetch_all_ohlcv(ex, symbol, timeframe, since, until=None,
limit=1000, params=None):
tf_ms = ex.parse_timeframe(timeframe) * 1000
now_floor = (ex.milliseconds() // tf_ms) * tf_ms # open of forming candle
end = min(until, now_floor) if until else now_floor # exclusive
cursor = since
while cursor < end:
raw = _fetch_page(ex, symbol, timeframe, cursor, limit, params or {})
batch = sorted(c for c in (raw or []) if cursor <= c[0] < end)
if not batch:
break # empty page or nothing in range
yield batch
last_ts = batch[-1][0]
if last_ts < cursor: # defensive: no progress
break
cursor = last_ts + tf_ms
def open_db(path):
db = sqlite3.connect(path)
db.execute('''CREATE TABLE IF NOT EXISTS candles (
symbol TEXT, timeframe TEXT, ts INTEGER,
open REAL, high REAL, low REAL, close REAL, volume REAL,
PRIMARY KEY (symbol, timeframe, ts))''')
return db
def download(ex, db, symbol, timeframe, start_ms, until=None, limit=1000):
tf_ms = ex.parse_timeframe(timeframe) * 1000
row = db.execute('SELECT MAX(ts) FROM candles WHERE symbol=? AND timeframe=?',
(symbol, timeframe)).fetchone()
since = row[0] + tf_ms if row[0] is not None else start_ms
for batch in fetch_all_ohlcv(ex, symbol, timeframe, since, until, limit):
db.executemany(
'INSERT OR IGNORE INTO candles VALUES (?,?,?,?,?,?,?,?)',
[(symbol, timeframe, *c[:6]) for c in batch])
db.commit() # one commit per page
def load_df(db, symbol, timeframe):
df = pd.read_sql('SELECT ts AS timestamp, open, high, low, close, volume '
'FROM candles WHERE symbol=? AND timeframe=? ORDER BY ts',
db, params=(symbol, timeframe))
df['dt'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True)
return df
ex = ccxt.binance({'enableRateLimit': True})
db = open_db('ohlcv.sqlite')
download(ex, db, 'BTC/USDT', '1h', start_ms=0) # since=0: see start-point notesWhich edge cases cause gaps, duplicates or infinite loops?
Most broken downloaders fail on one of the cases below. Each has a reason rooted in how exchanges implement their candle endpoints.
The most common mistake is stopping when len(batch) < limit. Kraken, OKX and Coinbase can return pages smaller than the limit mid-history, and new listings have genuine holes, so you would quit early and miss years of data.
| Symptom | Cause | Fix |
|---|---|---|
| Duplicate candle at every page boundary | since reused as last_ts | Use last_ts + tf_ms; also dedupe by primary key |
| Download ends after a few pages | Stopped on len(batch) < limit | Stop only on empty page, no progress or end bound |
| Same page returned forever | Exchange ignores since, or returns latest data | Filter to cursor <= ts < end and break when nothing is in range |
| Data is reversed or only the newest window arrives | Newest-first or backward-paginating endpoint (Bitfinex, BitMEX, some Bybit and OKX history endpoints) | Sort each batch; pass the end bound such as params={'until': end_ms} or the exchange's endTime, and walk backward |
| Empty result with an early since | Pair listed later; some exchanges return empty, Binance jumps to the first candle, others return the latest data | Probe with since=0 and limit=1, take the first timestamp, and treat empty as 'before listing' |
| Overlapping stored rows after a crash | Page inserted twice on rerun | Unique (symbol, timeframe, ts) with INSERT OR IGNORE |
How do rate limits and retries work, and how long will it take?
Set enableRateLimit=True so CCXT spaces requests by exchange.rateLimit milliseconds. That is a per-instance throttle, so two processes using the same IP can still exceed the exchange's weight limit. Do not set it to False to go faster, because a ban or temporary block costs more time than it saves.
On ccxt.RateLimitExceeded, ccxt.RequestTimeout and other ccxt.NetworkError cases, back off exponentially with jitter and retry the same since. Never advance the cursor after a failure, or you create a silent gap. ccxt.BadSymbol and ccxt.AuthenticationError are permanent, so retrying them just wastes time.
Estimate the work before you start. Requests are roughly ceil(candles / limit), and time is roughly requests * max(rateLimit, latency). Five years of 1m candles is about 2.6 million candles, which is about 2,600 requests at 1000 each.
import math
def estimate(ex, timeframe, years, limit):
tf_ms = ex.parse_timeframe(timeframe) * 1000
candles = years * 365 * 24 * 3600 * 1000 // tf_ms
requests = math.ceil(candles / limit)
seconds = requests * max(ex.rateLimit, 150) / 1000 # 150 ms assumed latency floor
return candles, requests, seconds
print(estimate(ccxt.binance(), '1m', 5, 1000))
# (2628000, 2628, ~394 s at 150 ms per request)How do I verify there are no gaps or duplicates?
After the download, check that consecutive timestamps differ by exactly the timeframe in milliseconds. Any larger diff is a gap, and a zero or negative diff is a duplicate or ordering bug.
Gaps are not always errors. Exchange downtime and illiquid pairs with no trades both produce missing bars, and some exchanges skip empty bars while others fill them with the previous close and zero volume. Decide which behavior your backtest expects. The Missing Bars audit article on this site covers classifying and repairing those gaps in depth.
def check_gaps(df, tf_ms):
ts = df['timestamp']
assert ts.is_monotonic_increasing and ts.is_unique, 'order or duplicates'
d = ts.diff().iloc[1:]
bad = d[d != tf_ms]
gaps = pd.DataFrame({
'after': pd.to_datetime(ts.shift(1)[bad.index], unit='ms', utc=True),
'missing_bars': (bad // tf_ms - 1).astype(int)})
return gaps
df = load_df(db, 'BTC/USDT', '1h')
print(check_gaps(df, 3_600_000)) Can async or bulk downloads make this faster?
Within one symbol, pagination is sequential because each page's cursor depends on the previous page. Using ccxt.async_support or ccxt.pro does not speed up a single series. It helps across symbols, using asyncio.Semaphore (for example 3 to 5 concurrent tasks) so the shared rate limiter is respected. You can also split one range into disjoint windows with explicit since and until, as long as each window is deduped on insert. Always call await exchange.close() in a finally block, or aiohttp sessions leak and warn.
When REST would take hours, use bulk files. Binance publishes monthly and daily kline zips on data.binance.vision, covering years of 1m bars much faster than REST. Other exchanges offer their own history downloads. Verify timestamp units after loading, since some recent files use microseconds instead of milliseconds, so check the digit count.
Semantics also differ per exchange. The timestamp is normally the candle open time, but confirm that. Volume may be base or quote currency, and fields such as trade counts are not in the CCXT six-column format. Normalize these before merging sources.
Common questions
Does fetch_ohlcv return the currently forming candle?
Usually yes, the last row is the candle that is still open, and its values change until it closes. Exclude it by bounding the loop at the current time floored to the timeframe, or drop the last row before saving.
Why do I get duplicate candles between pages?
since is inclusive, so passing the last timestamp returns that candle again as the first row of the next page. Set since = last_ts + timeframe_ms and add a unique key on (symbol, timeframe, ts) as a second safeguard.
How do I find the first available candle for a symbol?
Call fetch_ohlcv(symbol, timeframe, since=0, limit=1) and read the first timestamp. Exchanges differ: Binance jumps to the first candle, some return empty and some return the latest data, so check that the result is plausible and handle empty results.
Should I use paginate=True or write my own loop?
paginate=True is fine for quick pulls on exchanges where CCXT implements it. For multi-year, resumable, incrementally saved datasets, a custom loop gives you retries, per-page commits and explicit termination rules.
Can I store the data as Parquet instead of SQLite?
Yes. Write one file per page or per month partition, and on restart read the maximum timestamp from the existing partitions to compute the resume point. Dedupe on timestamp when combining files, since Parquet has no primary key to enforce uniqueness.