HomePhase 2: Binance & TestnetLesson 7
Lesson 7 of 24Phase 2: Binance & TestnetBeginner

Downloading Years of Historical Crypto Prices

Build a Python command-line downloader that fetches multi-year 1-minute crypto candlestick histories from Binance and saves them to CSV.

Bitfoster Team
December 3, 2026
10 Min Read
lesson-07-historical-price-downloader/
Downloading Years of Historical Crypto Prices

Hands-On Deliverable

A command-line downloader that saves multi-year 1-minute candle histories to your computer.

Before you ever trust a trading idea—even with fake money—you want to test it against the past. Did your strategy make money during a bull run? Did it survive a sudden flash crash? To answer those questions, you need historical candlestick data (also called OHLCV data: Open, High, Low, Close, and Volume).

Here is the catch: Binance will not hand you two years of 1-minute candles in a single request. Each API call is capped at 1,000 candles. Since there are 1,440 minutes in a single day, downloading just one year of 1-minute candles requires over 525 separate requests stitched together in order without gaps or duplicates.

In this lesson, you will build a reusable command-line downloader that handles that pagination automatically and saves clean CSV files right to your computer.

Testnet vs. Public Historical Data (And Staying Safe)

Just like in Lesson 6, we practice safely with Binance Spot Testnet (https://testnet.binance.vision) and fake money whenever we interact with an account, and we never enable withdrawal permissions on any API key.

One helpful detail to know about candlestick data:

  • Candlestick prices are public. You do not even need API keys to download historical candles!
  • Spot Testnet resets periodically, so it usually only stores a few weeks of recent test candles.
  • If you want to test the script safely against Testnet first, pass --testnet. When you want true multi-year history (like 2023–2026) for backtesting, you can pull from Binance's public read-only market data endpoint (no API key required, zero risk to any account).

Prerequisites

Install python-binance and pandas so we can fetch candles cleanly and export them to CSV:

pip install python-binance pandas

The Command-Line Historical Price Downloader

Save this script as download_candles.py. It lets you pick any trading pair (BTCUSDT, ETHUSDT), timeframe (1m, 15m, 1h, 1d), and date range right from your terminal.

import argparse
import os
import time
from datetime import datetime, timezone
import pandas as pd
from binance.client import Client
from binance.exceptions import BinanceAPIException


# Exact column names returned by Binance's klines (candlestick) endpoint
KLINE_COLUMNS = [
    "open_time",
    "open",
    "high",
    "low",
    "close",
    "volume",
    "close_time",
    "quote_asset_volume",
    "number_of_trades",
    "taker_buy_base_volume",
    "taker_buy_quote_volume",
    "ignore",
]


def fetch_all_candles(client, symbol, interval, start_str, end_str=None):
    """
    Download historical candles in chunks of 1,000 (Binance's per-request limit)
    until the full date range is covered.
    """
    print(f"Fetching {symbol} ({interval}) candles from {start_str} to {end_str or 'now'}...")

    # python-binance's get_historical_klines handles the 1,000-candle pagination loop
    raw_klines = client.get_historical_klines(
        symbol=symbol,
        interval=interval,
        start_str=start_str,
        end_str=end_str,
        limit=1000,
    )

    if not raw_klines:
        return pd.DataFrame()

    df = pd.DataFrame(raw_klines, columns=KLINE_COLUMNS)

    # Convert millisecond timestamps into readable UTC datetimes
    df["open_time"] = pd.to_datetime(df["open_time"], unit="ms", utc=True)
    df["close_time"] = pd.to_datetime(df["close_time"], unit="ms", utc=True)

    # Convert price and volume columns from strings to numbers
    numeric_cols = ["open", "high", "low", "close", "volume"]
    for col in numeric_cols:
        df[col] = df[col].astype(float)

    # Keep the core OHLCV columns for clean backtesting CSVs
    clean_df = df[["open_time", "open", "high", "low", "close", "volume"]].copy()

    # Remove any duplicate timestamps just in case a boundary overlapped
    clean_df = clean_df.drop_duplicates(subset=["open_time"]).sort_values("open_time")
    return clean_df


def main():
    parser = argparse.ArgumentParser(
        description="Download historical crypto candlestick data from Binance to CSV."
    )
    parser.add_argument("--symbol", default="BTCUSDT", help="Trading pair, e.g. BTCUSDT")
    parser.add_argument("--interval", default="1m", help="Candle size: 1m, 5m, 15m, 1h, 1d")
    parser.add_argument("--start", default="7 days ago UTC", help="Start date, e.g. '2024-01-01'")
    parser.add_argument("--end", default=None, help="Optional end date, e.g. '2025-01-01'")
    parser.add_argument(
        "--testnet",
        action="store_true",
        help="Use Binance Spot Testnet (https://testnet.binance.vision)",
    )
    parser.add_argument("--out-dir", default="data", help="Folder where CSV files are saved")
    args = parser.parse_args()

    # Public market data does NOT require API keys (never risk keys when you don't need them)
    client = Client(api_key="", api_secret="", testnet=args.testnet)
    source = "Binance Spot Testnet" if args.testnet else "Binance Public Market Data"
    print(f"Connected to: {source}")

    started_at = time.time()
    try:
        df = fetch_all_candles(
            client=client,
            symbol=args.symbol.upper(),
            interval=args.interval,
            start_str=args.start,
            end_str=args.end,
        )
    except BinanceAPIException as exc:
        print(f"Binance API Error ({exc.code}): {exc.message}")
        return

    if df.empty:
        print("No candles returned. Check your symbol or date range.")
        return

    os.makedirs(args.out_dir, exist_ok=True)
    stamp = datetime.now(timezone.utc).strftime("%Y%m%d")
    filename = f"{args.symbol.upper()}_{args.interval}_{stamp}.csv"
    filepath = os.path.join(args.out_dir, filename)

    df.to_csv(filepath, index=False)
    elapsed = time.time() - started_at

    print(f"\nSaved {len(df):,} candles to: {filepath}")
    print(f"First candle : {df['open_time'].iloc[0]}")
    print(f"Last candle  : {df['open_time'].iloc[-1]}")
    print(f"Completed in : {elapsed:.2f} seconds")


if __name__ == "__main__":
    main()

Run it first on Binance Spot Testnet to test the flow:

python download_candles.py --symbol BTCUSDT --interval 1m --start "2 days ago UTC" --testnet

When you are ready to download a full multi-year 1-minute dataset for backtesting (using public read-only data):

python download_candles.py --symbol BTCUSDT --interval 1m --start "2024-01-01" --end "2026-01-01"

Expected Terminal Output

Connected to: Binance Spot Testnet
Fetching BTCUSDT (1m) candles from 2 days ago UTC to now...

Saved 2,880 candles to: data/BTCUSDT_1m_20261203.csv
First candle : 2026-12-01 11:54:00+00:00
Last candle  : 2026-12-03 11:53:00+00:00
Completed in : 1.42 seconds

Common Beginner Mistake: Asking for 3 years of 1-minute candles on the Spot Testnet and wondering why only a few days come back, or hitting Binance's rate limit by firing dozens of download scripts at once. Remember: Testnet resets periodically and only keeps short recent history. For multi-year 1-minute history, omit --testnet (it uses public read-only market data with zero account risk) and download one symbol at a time so you stay comfortably under Binance's API request weight limits.

Study & Practice Recap

  • Why pagination matters: Binance caps every candlestick request at 1,000 bars, so multi-year histories must be downloaded in sequential chunks and stitched together.
  • Keep timestamps in UTC: Converting millisecond timestamps to UTC prevents daylight-saving bugs when you later compare trades against price charts.
  • Public data needs no keys: You never have to expose API keys just to read historical market prices.

Tiny Hands-On Exercise: Run download_candles.py for ETHUSDT at the 15m interval over the last 7 days on --testnet, then open the generated CSV file and verify the open, high, low, close, and volume columns look right.

Topics:#Binance#Testnet#Historical Data#Candlesticks#Python