Kraken OHLCV Fetch
Fetch and store OHLCV candlestick data from Kraken using the official API with proper error handling, retry logic, and support for both spot and futures markets across all available trading pairs.
Kraken Market Data Acquisition Framework
This notebook establishes a standardized protocol for interfacing with the Kraken REST API to retrieve historical OHLCV candle data. It is structured to facilitate programmatic data extraction, transformation, and initial validation for quantitative analysis.
1. Dependency Management and Library Integration
The requests library handles API calls for Kraken. The following imports provide the necessary toolkit
for data manipulation (pandas), temporal management (datetime), and
API client connectivity (requests).
You can find information about Kraken's API and how to obtain API keys here: Kraken API Documentation
1. Dependency Installation
!pip install requests pandasRequirement already satisfied: requests in /usr/local/lib/python3.12/dist-packages (2.32.4) Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (2.2.2) Requirement already satisfied: charset_normalizer<4,>=2 in /usr/local/lib/python3.12/dist-packages (from requests) (3.4.7) Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.12/dist-packages (from requests) (3.18) Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.12/dist-packages (from requests) (2.5.0) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.12/dist-packages (from requests) (2026.5.20) Requirement already satisfied: numpy>=1.26.0 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.0.2) Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.9.0.post0) Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.2) Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas) (2026.2) Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)
2. Library Imports
import warnings
warnings.filterwarnings("ignore")
import requests
import pandas as pd
from datetime import datetimeCode Logic
warnings.filterwarnings("ignore"): Suppresses non-critical runtime warnings to maintain clean output.requests: Handles HTTP communication with the Kraken Futures public REST endpoint.pandas: Provides the DataFrame structure for tabular OHLCV data.datetime: Supplies naive UTC datetime objects for Unix second timestamp derivation.
3. Configuration
SYMBOL = "PI_XBTUSD"
START_DATETIME = datetime(2024, 1, 1)
END_DATETIME = datetime(2024, 1, 31, 23, 59, 59)
BASE_URL = "https://futures.kraken.com/api/charts/v1/trade/{symbol}/1m"Code Logic
SYMBOL: Kraken Futures instrument ticker. Common formats:PI_XBTUSD(BTC perpetual inverse),PF_XBTUSD(BTC perpetual multi-collateral).START_DATETIME / END_DATETIME: Naive UTC datetimes defining the retrieval window. The window width determines the number of 1-minute candles returned — a 6-minute span yields 5 candles.BASE_URL: Public Kraken Futures historical candles endpoint. No API key is required. The{symbol}placeholder is resolved at call time.
4. Data Extraction Function
The fetch_ohlc function performs a single HTTP GET request to the Kraken
Futures charts endpoint, maps the response to a standardized OHLCV schema,
and applies precision-safe type casting.
def fetch_ohlc(symbol, start_datetime, end_datetime):
url = BASE_URL.format(symbol=symbol)
params = {
"from": int(start_datetime.timestamp()),
"to": int(end_datetime.timestamp()),
}
response = requests.get(url, headers={"Accept": "application/json"}, params=params, timeout=30)
response.raise_for_status()
candles = response.json().get("candles", [])
if not candles:
return pd.DataFrame()
df = pd.DataFrame(candles)
# Convert 'time' (which is in milliseconds from Kraken) directly to datetime
df["timestamp"] = pd.to_datetime(df["time"], unit='ms')
df = df[["timestamp", "open", "high", "low", "close", "volume"]]
df = df.astype({
"timestamp": "datetime64[ns]",
"open": "float64",
"high": "float64",
"low": "float64",
"close": "float64",
"volume": "float64",
})
return df.sort_values("timestamp", ignore_index=True)Code Logic
BASE_URL.format(symbol=symbol): Resolves the{symbol}placeholder in the URL template using the configured instrument ticker.int(start_datetime.timestamp()): Converts the naive UTC datetime to a Unix second integer. Kraken Futuresfrom/toparameters are in seconds, not milliseconds.headers={"Accept": "application/json"}: Explicitly declares the expected response content type as required by the Kraken Futures API specification.response.raise_for_status(): Raises anHTTPErroron any non-2xx response code, ensuring silent failures are surfaced immediately.response.json().get("candles", []): Extracts the candle array from the Kraken response envelope; defaults to an empty list if the key is absent.pd.DataFrame(candles): Constructs a structured DataFrame from the raw list of candle dictionaries. Kraken returns each candle as a named-key object.df["timestamp"] = pd.to_datetime(df["time"], unit='ms'): Maps Kraken's nativetimefield (milliseconds) to the standardizedtimestampcolumn and converts it todatetime64[ns].df[["timestamp", "open", "high", "low", "close", "volume"]]: Discards all auxiliary columns not required for OHLCV analysis..astype({...}): Casts all string-encoded or mixed-type API values to numeric types required for arithmetic computation, includingtimestamptodatetime64[ns]..sort_values("timestamp", ignore_index=True): Ensures chronological ordering of the output DataFrame.
5. Execution
print("Re-fetching data with updated date range...")
df = fetch_ohlc(SYMBOL, START_DATETIME, END_DATETIME)Re-fetching data with updated date range...
Code Logic
fetch_ohlc(SYMBOL, START_DATETIME, END_DATETIME): Executes a single API call using the globally defined configuration parameters and returns a typed OHLCV DataFrame.
6. Integrity Verification and Data Inspection
print("--- Fetched OHLCV Data ---")
print("--- Tail of the DataFrame (showing varied data) ---")
display(df.tail())
print("\n--- Schema Summary ---")
df.info()--- Fetched OHLCV Data --- --- Tail of the DataFrame (showing varied data) ---
| timestamp | open | high | low | close | volume | |
|---|---|---|---|---|---|---|
| 1995 | 2024-01-02 09:15:00 | 45773.0 | 45806.0 | 45773.0 | 45806.0 | 1006.0 |
| 1996 | 2024-01-02 09:16:00 | 45806.0 | 45806.0 | 45806.0 | 45806.0 | 0.0 |
| 1997 | 2024-01-02 09:17:00 | 45806.0 | 45844.0 | 45806.0 | 45844.0 | 1000.0 |
| 1998 | 2024-01-02 09:18:00 | 45844.0 | 45858.0 | 45844.0 | 45845.0 | 1012.0 |
| 1999 | 2024-01-02 09:19:00 | 45845.0 | 45845.0 | 45799.0 | 45799.0 | 2500.0 |
--- Schema Summary --- <class 'pandas.core.frame.DataFrame'> RangeIndex: 2000 entries, 0 to 1999 Data columns (total 6 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 timestamp 2000 non-null datetime64[ns] 1 open 2000 non-null float64 2 high 2000 non-null float64 3 low 2000 non-null float64 4 close 2000 non-null float64 5 volume 2000 non-null float64 dtypes: datetime64[ns](1), float64(5) memory usage: 93.9 KB