AllTick
Mastering Market Data: A Guide to the Alltick Historical Kline API
quantitative tradingBacktestingfinancial data apiHistorical Market Data

Mastering Market Data: A Guide to the Alltick Historical Kline API

Learn how to use the AllTick Historical Kline API to retrieve historical candlestick data, handle pagination, validate timestamps, and build reliable datasets for quantitative trading backtests.

AllTick2 min read

For quantitative traders, a backtest is only as reliable as the historical data behind it. Missing candles, inconsistent time intervals, or incorrect timestamps can distort technical indicators and make a strategy appear more profitable than it would be in live trading.

The AllTick Historical Kline API lets traders retrieve historical candlestick data through an HTTP GET request. This guide focuses on the practical details that matter when preparing data for quantitative research: selecting a timeframe, requesting historical bars, handling pagination, and checking data before using it in a backtest.

How the AllTick Kline API Works

The Kline endpoint returns candlestick data for a specified instrument. Each bar contains a timestamp, open price, high price, low price, close price, volume, and turnover fields where provided.

The endpoint depends on the asset class:

  • Forex, precious metals, cryptocurrencies, and supported commodities use the /quote-b-api/kline endpoint.
  • Stocks, including supported US and Hong Kong listings, use /quote-stock-b-api/kline.

Both endpoints use HTTP GET requests. Authentication is provided through a token query parameter, while the request details are passed in a URL-encoded JSON string through the query parameter.

Choose the Right Kline Parameters

The request contains a unique trace identifier and a data object. The following parameters determine which candles are returned.

ParameterPurposeImportant detail
codeIdentifies the instrumentMatch the symbol and capitalization used in the product list
kline_typeSets the candle interval1 = 1 minute, 2 = 5 minutes, 5 = 1 hour, 8 = daily
kline_timestamp_endSets the historical query boundary0 requests data from the latest available trading period
query_kline_numSets the number of candlesMaximum 500 candles per request
adjust_typeSpecifies stock price adjustmentCurrently, 0 is supported for stock instruments

Stocks do not support the two-hour and four-hour intervals. Timestamp-based historical queries are also asset-dependent: the documented timestamp cursor is supported for forex, precious metals, and cryptocurrencies, but not for stock codes.

These restrictions matter when designing a backtesting pipeline. A request that works for one asset class should not automatically be assumed to work for another.

Retrieve Historical Kline Data with Python

The following example requests 100 five-minute EUR/USD candles. It uses the forex endpoint and reads the API token from an environment variable rather than embedding credentials in the source code.

text
import json
import os
import uuid
import requests

BASE_URL = "https://quote.alltick.co/quote-b-api"
TOKEN = os.environ["ALLTICK_API_TOKEN"]

def fetch_kline(code="EURUSD", interval=2, count=100, end_ts=0):
    query = {
        "trace": str(uuid.uuid4()),
        "data": {
            "code": code,
            "kline_type": interval,
            "kline_timestamp_end": end_ts,
            "query_kline_num": count,
            "adjust_type": 0
        }
    }

    response = requests.get(
        f"{BASE_URL}/kline",
        params={
            "token": TOKEN,
            "query": json.dumps(query)
        },
        timeout=15
    )
    response.raise_for_status()

    result = response.json()
    if result.get("ret") != 200:
        raise RuntimeError(
            f"API error: {result.get('msg', 'Unknown error')}"
        )

    return result.get("data", {}).get("kline_list", [])

candles = fetch_kline()
print(f"Retrieved {len(candles)} candles")

Before running the example, install the requests package and configure ALLTICK_API_TOKEN with your own API token.

The example checks the API's return code and reports the number of candles received. It does not assume that every successful HTTP response contains the full requested history. For production use, also record the instrument, interval, query parameters, and response metadata for troubleshooting.

Build a Reliable Historical Dataset

Retrieving candles is only the first part of preparing data for quantitative trading. The data must also be consistent with the strategy being tested.

Check timestamps and ordering. Convert returned timestamps using the correct Unix time unit, then sort the bars chronologically before calculating indicators. Do not assume the response order without checking it.

Handle incomplete results. A request for 100 bars may return fewer. Check the actual response length and determine whether the difference reflects market hours, available history, subscription limits, or a request issue. Missing intervals should not automatically be filled with fabricated prices.

Request older data carefully. The API supports up to 500 candles per request. For supported instruments, you can use timestamp-based requests to retrieve earlier bars, while tracking the earliest timestamp returned and removing duplicate candles at page boundaries. Stop when no additional history is returned or the cursor stops advancing. Stock instruments require a different retrieval approach because the timestamp cursor is not supported for them.

Store the data locally. For repeated backtests, save validated candles in a database or partitioned files keyed by instrument and interval. Fetch historical data in advance, then update the stored dataset as new bars become available. This reduces unnecessary repeated requests and helps preserve reproducible research inputs.

Check Data Coverage Before Backtesting

Historical availability depends on the instrument, subscription, and applicable API limits. Do not assume that every asset has the same look-back period or that a particular plan guarantees a fixed number of years of data. Confirm the current coverage for your chosen instruments before building a long-horizon backtest.

The maximum of 500 candles is a per-request limit, not a guarantee of historical depth. For example, 500 five-minute candles cover far less calendar time than 500 daily candles, and market sessions affect the actual time span.

Finally, validate the dataset against your strategy's requirements. Check for duplicate timestamps, unexpected gaps, invalid OHLC relationships, and changes in instrument availability. For stock strategies, confirm how corporate actions and the supported adjustment settings affect historical prices.

Put Historical Kline Data to Work

For quantitative traders, the value of a historical Kline API lies in more than retrieving candles. It provides a repeatable way to prepare market data for indicator calculations, strategy evaluation, and historical charting.

AllTick provides a single request structure for supported instruments within each asset-class endpoint. By checking symbol conventions, interval support, historical coverage, and response quality before running a backtest, you can build a more dependable data pipeline and avoid drawing conclusions from incomplete or unsuitable data.

Before deployment, consult the official AllTick Kline API documentation for the current parameter definitions, endpoint restrictions, and request limits.

Start streaming market data today

Generate a free API key in seconds and connect to every market from one endpoint.