Data·OHLCV Data Fetching·Beginner

OKX OHLCV Fetch

Fetch and store OHLCV candlestick data from OKX using their REST API, handling rate limits, pagination, and multiple symbol format conventions for reliable automated data collection.

data-engineeringdata-fetching

OKX Market Data Acquisition Framework

This notebook provides a structured protocol for interfacing with the OKX public REST API to retrieve historical OHLCV (Open, High, Low, Close, Volume) candle data. It includes dependency setup, configuration, a single-call data extraction function, and output validation.

1. Install Dependencies

[3]
import requests
import pandas as pd

# Install required libraries: requests for HTTP communication, pandas for data manipulation, and mplfinance for plotting.
%pip install requests pandas mplfinance
Requirement 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)
Collecting mplfinance
  Downloading mplfinance-0.12.10b0-py3-none-any.whl.metadata (19 kB)
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: matplotlib in /usr/local/lib/python3.12/dist-packages (from mplfinance) (3.10.0)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)
Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib->mplfinance) (1.3.3)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib->mplfinance) (0.12.1)
Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib->mplfinance) (4.63.0)
Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib->mplfinance) (1.5.0)
Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib->mplfinance) (26.2)
Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib->mplfinance) (11.3.0)
Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib->mplfinance) (3.3.2)
Downloading mplfinance-0.12.10b0-py3-none-any.whl (75 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 75.0/75.0 kB 3.1 MB/s eta 0:00:00
[?25hInstalling collected packages: mplfinance
Successfully installed mplfinance-0.12.10b0

2. Import Libraries

This section imports all necessary Python libraries for API interaction and data handling.

[4]
import warnings
from datetime import datetime, timezone

# Ignore non-critical runtime warnings to maintain clean output.
warnings.filterwarnings("ignore")

# The requests library handles HTTP communication with the OKX public REST endpoint.
import requests
# The pandas library provides the DataFrame structure for tabular OHLCV data.
import pandas as pd
# datetime and timezone modules supply UTC-aware datetime objects for millisecond timestamp derivation.
from datetime import datetime, timezone

3. Configuration

This section defines the parameters required for data extraction from the OKX API.

[5]
# Define the OKX instrument identifier. Format: {BASE}-{QUOTE}-SWAP for perpetual futures; {BASE}-{QUOTE} for spot.
SYMBOL = "BTC-USDT-SWAP"

# Define the UTC-aware datetime marking the start of the retrieval window.
START_DATETIME = datetime(2024, 1, 1, tzinfo=timezone.utc)

# Define the number of candles to retrieve per API call. The OKX history-candles endpoint supports a maximum of 100 per request.
LIMIT = 5

# Define the public OKX historical candles endpoint. No API key is required for this endpoint.
BASE_URL = "https://www.okx.com/api/v5/market/history-candles"

4. Data Extraction Function

This section defines the fetch_ohlc function, which performs a single HTTP GET request to the OKX history-candles endpoint. It maps the API response to a standardized OHLCV schema and applies precision-safe type casting.

[6]
def fetch_ohlc(symbol, start_datetime, limit):
    """
    Fetches OHLCV (Open, High, Low, Close, Volume) data from the OKX API.

    Input:
    - `symbol` (str): The instrument ID (e.g., "BTC-USDT-SWAP").
    - `start_datetime` (datetime): UTC-aware datetime indicating the start of the data retrieval window.
    - `limit` (int): The number of candles to retrieve (maximum 100).

    Output:
    - `pandas.DataFrame`: A DataFrame containing the OHLCV data, or an empty DataFrame if no data is returned.

    Logic:
    1. Converts the `start_datetime` to a Unix millisecond timestamp, as required by the OKX API.
    2. Constructs request parameters including the instrument ID, bar interval, limit, and cursor for pagination.
    3. Sends an HTTP GET request to the OKX `history-candles` endpoint.
    4. Raises an HTTPError for non-2xx responses.
    5. Extracts candle data from the JSON response.
    6. If data exists, it constructs a pandas DataFrame with specified columns.
    7. Converts the 'timestamp' column to UTC-aware datetime objects and renames it to 'datetime'.
    8. Casts OHLCV columns to float64 for numerical precision.
    9. Sorts the DataFrame by the 'datetime' column in ascending order.
    """
    # Convert the UTC datetime to a Unix millisecond integer, as required by the OKX `after` cursor parameter.
    after_ms = int(start_datetime.timestamp() * 1000)

    # Define parameters for the API request.
    params = {
        "instId": symbol,
        "bar":    "1m",  # Specifies the 1-minute candlestick interval.
        "limit":  limit,
        "after":  str(after_ms), # OKX cursor-based pagination parameter — returns candles with timestamps strictly after the specified value.
    }

    # Send the HTTP GET request to the OKX API.
    response = requests.get(BASE_URL, params=params, timeout=30)
    # Raise an HTTPError on any non-2xx response code, ensuring silent failures are surfaced immediately.
    response.raise_for_status()
    # Extract the candle array from the OKX response envelope; defaults to an empty list if the key is absent.
    data = response.json().get("data", [])

    # Return an empty DataFrame if no data is received.
    if not data:
        return pd.DataFrame()

    # Construct a structured DataFrame from the raw indexed-list response. OKX returns each candle as a positional list.
    df = pd.DataFrame(data, columns=[
        "timestamp", "open", "high", "low", "close", "volume",
        "volCcy", "volCcyQuote", "confirm"
    ])
    # Discard auxiliary columns (`volCcy`, `volCcyQuote`, `confirm`) not required for OHLCV analysis.
    df = df[["timestamp", "open", "high", "low", "close", "volume"]]

    # Convert the Unix millisecond timestamp to a UTC-aware datetime object.
    df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
    # Rename the `timestamp` column to `datetime` for clarity.
    df = df.rename(columns={"timestamp": "datetime"})

    # Cast all string-encoded API values to numeric types required for arithmetic computation.
    df = df.astype({
        "open":      "float64",
        "high":      "float64",
        "low":       "float64",
        "close":     "float64",
        "volume":    "float64",
    })

    # Ensure chronological ordering of the output DataFrame by the `datetime` column.
    return df.sort_values("datetime", ignore_index=True)

5. Execute Data Extraction

This section executes the fetch_ohlc function to retrieve historical OHLCV data using the defined configuration parameters.

[7]
# Execute a single API call using the globally defined configuration parameters
# and store the returned OHLCV data in a pandas DataFrame.
df = fetch_ohlc(SYMBOL, START_DATETIME, LIMIT)

6. Integrity Verification and Data Inspection

This section verifies the integrity of the fetched data and displays a summary of its structure and content.

[8]
print("--- Fetched OHLCV Data Head ---")
# Display the first few rows of the DataFrame to inspect the data.
display(df.head())

print("\n--- Schema Summary ---")
# Print a concise summary of the DataFrame, including data types and non-null values.
df.info()
--- Fetched OHLCV Data Head ---
datetime open high low close volume
0 2023-12-31 23:55:00+00:00 42228.0 42245.0 42227.9 42237.2 4617.0
1 2023-12-31 23:56:00+00:00 42237.1 42248.0 42229.2 42248.0 1962.0
2 2023-12-31 23:57:00+00:00 42247.9 42288.0 42247.9 42287.9 3243.0
3 2023-12-31 23:58:00+00:00 42288.0 42290.9 42287.9 42287.9 3764.0
4 2023-12-31 23:59:00+00:00 42287.9 42297.8 42270.5 42297.7 5195.0

--- Schema Summary ---
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 6 columns):
 #   Column    Non-Null Count  Dtype              
---  ------    --------------  -----              
 0   datetime  5 non-null      datetime64[ns, UTC]
 1   open      5 non-null      float64            
 2   high      5 non-null      float64            
 3   low       5 non-null      float64            
 4   close     5 non-null      float64            
 5   volume    5 non-null      float64            
dtypes: datetime64[ns, UTC](1), float64(5)
memory usage: 372.0 bytes

7. Data Visualization

This section provides a function to visualize the OHLCV data as a candlestick chart using mplfinance.

[9]
import matplotlib.pyplot as plt
import mplfinance as mpf

def plot_ohlc(df, symbol):
    """
    Plots an OHLCV candlestick chart for the given DataFrame.

    Input:
    - `df` (pandas.DataFrame): DataFrame containing OHLCV data with a 'datetime' index.
    - `symbol` (str): The instrument ID for the chart title.
    """
    # Set 'datetime' as the index for mplfinance
    df_plot = df.set_index('datetime')

    fig, axlist = mpf.plot(df_plot,
                            type='candle',
                            volume=True,
                            title=f"{symbol} OHLCV Candlestick Chart",
                            ylabel='Price',
                            ylabel_lower='Volume',
                            style='yahoo',
                            returnfig=True)
    plt.show()
[10]
# Visualize the fetched OHLCV data
plot_ohlc(df, SYMBOL)
cell output

Conclusion

This notebook provides a robust framework for retrieving historical OHLCV data from the OKX public REST API. It covers the essential steps:

  1. Dependency Installation: Ensuring all necessary libraries (requests, pandas) are in place.
  2. Library Imports: Organizing and importing required modules.
  3. Configuration: Setting up key parameters like the trading symbol, start time for data retrieval, and the number of candles per request.
  4. Data Extraction Function: Defining fetch_ohlc to encapsulate the API call logic, including timestamp conversion, HTTP request handling, response parsing, data structuring into a pandas DataFrame, and type casting for numerical precision.
  5. Execution: Demonstrating how to call the fetch_ohlc function with the defined parameters.
  6. Integrity Verification: Providing initial checks on the fetched data, such as displaying the head of the DataFrame and a schema summary to confirm data types and non-null values.

This structured approach ensures that users can reliably and efficiently acquire OKX historical market data for further analysis, strategy development, or backtesting.

OKX OHLCV Fetch · BitPredict