STOCKAP DEVELOPER GUIDES
Export crypto OHLCV data to CSV with Python
By StockAP · Updated November 25, 2026
Download BTCUSDT daily candles to CSV using Python’s standard library, with duplicate checks and preserved missing values.
Export stored Bitcoin candles for a spreadsheet or chart pipeline with one authenticated request. This tutorial uses Python 3.9 or later, without pandas or other dependencies. BTCUSDT prices are quoted in USDT, not converted USD.
Prepare and run
Create an API key and set STOCKAP_API_KEY in your server environment. Download the script, then run it from a writable directory:
curl --fail -O https://stockap.com/examples/export-crypto-candles.py python3 export-crypto-candles.py
It creates btcusdt-daily.csv. If that file exists, move it or choose another output name; the script will not replace it.
"""Python 3.9+, standard library only. One API request; preserves missing values."""
import csv
import json
import os
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
def export(payload, destination):
data = payload.get('data', {})
bars = data.get('bars')
if not isinstance(bars, list) or not bars:
raise ValueError('No candles returned; no output overwritten.')
if any(not isinstance(b, dict) or not isinstance(b.get('time'), (int, float)) for b in bars):
raise ValueError('Invalid candle time; inspect the response.')
bars = sorted(bars, key=lambda b: b['time'])
if len({b['time'] for b in bars}) != len(bars):
raise ValueError('Duplicate timestamps; inspect the source before export.')
fields = ['time', 'open', 'high', 'low', 'close', 'volume', 'closed', 'partial']
# Exclusive creation avoids accidentally replacing an earlier export.
with Path(destination).open('x', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fields, extrasaction='ignore')
writer.writeheader()
writer.writerows(bars)
return len(bars)
if __name__ == '__main__':
key = os.environ.get('STOCKAP_API_KEY')
if not key:
raise SystemExit('Set STOCKAP_API_KEY in your server environment.')
request = Request('https://stockap.com/v1/candles?market=crypto&symbol=BTCUSDT&interval=1d',
headers={'Authorization': 'Bearer ' + key})
try:
with urlopen(request, timeout=30) as response:
payload = json.load(response)
count = export(payload, 'btcusdt-daily.csv')
print(f'Exported {count} candles; source: {payload["data"].get("source", "unknown")}')
except HTTPError as error:
raise SystemExit(f'HTTP {error.code}: check account access or back off; no automatic retries.')
except (URLError, ValueError, OSError) as error:
raise SystemExit(f'Export failed ({type(error).__name__}); keep previous files.')
Read the CSV correctly
time is the source candle timestamp in Unix seconds. Rows are sorted and duplicate timestamps are rejected. Empty fields mean unavailable, not zero. The closed and partial fields are preserved when supplied; blank finality flags must not be interpreted as a completed candle.
Volume retains the source units. It is not automatically USD turnover or trailing 24-hour volume. Available dates vary by instrument; this endpoint exports returned stored history and does not promise every exchange’s full history or a date-range pagination contract.
Validate before research
Inspect the first and last dates and exclude forming or partial candles when your analysis requires completed observations. Preserve the source name printed by the script. A successful export is not independent verification of market prices.
Crypto API coverage and access · OHLCV and missing-data guide