AllTick
Python Quantitative Trading: How to Access Financial Market Data?
quantitative tradingfinancial market datastock api Algorithmic Trading

Python Quantitative Trading: How to Access Financial Market Data?

Learn how to access financial market data with Python using AllTick. Retrieve historical K-lines, latest quotes, and order book data, stream live updates via WebSocket, and validate data for reliable quantitative backtesting.

AllTick3 min read

For quantitative traders, reliable market data is essential for developing strategies, testing trading signals, and monitoring live market conditions. Python makes it easier to combine historical prices, market quotes, and order book updates in one workflow. However, a successful API request is only the first step. Data consistency, timestamp handling, and the distinction between historical and real-time data also affect the reliability of a strategy.

This guide explains how to access financial market data with Python using AllTick as an example. It covers historical candlesticks, latest quotes, order book data, and WebSocket streaming, with practical examples and checks for quantitative research.

Choose the Right Data for Your Strategy

Different strategies require different levels of market detail.

Data typeQuantitative trading application
Historical K-linesCalculate technical indicators and backtest strategies
Latest market quotesMonitor prices and evaluate current trading signals
Order book dataAnalyze bid and ask prices and available market depth
WebSocket updatesProcess continuous market changes without repeated polling

For example, a moving-average strategy can begin with historical closing prices. A strategy that evaluates liquidity or market depth needs more detailed order book data.

AllTick provides interfaces for these use cases, but the appropriate choice depends on the instruments, data fields, and update frequency a strategy requires.

Retrieve Historical K-Line Data with Python

Historical candlestick data is a practical starting point for quantitative research. Each candle contains open, high, low, and close prices, as well as volume and turnover fields where available.

AllTick's newer REST API supports up to 500 candles per single-instrument K-line request. For stock instruments, supported intervals include 1-minute, 5-minute, 15-minute, 30-minute, hourly, daily, weekly, and monthly candles. Stock products do not support 2-hour or 4-hour candles.

Install the Python dependency:

text
pip install requests

The following example retrieves 100 recent one-minute candles for Tencent Holdings (700.HK).

text
import json
import os
import requests
from urllib.parse import quote

API_KEY = os.environ["ALLTICK_API_KEY"]

query_data = {
    "trace": "quant-kline-demo",
    "data": {
        "code": "700.HK",
        "kline_type": 1,
        "kline_timestamp_end": 0,
        "query_kline_num": 100,
        "adjust_type": 0
    }
}

query_path = quote(
    json.dumps(query_data, separators=(",", ":")),
    safe=""
)

url = (
    "https://quote.alltick.co/"
    "quote-stock-b-api/v1/kline/" + query_path
)

response = requests.get(
    url,
    headers={"X-API-Key": API_KEY},
    timeout=15
)

response.raise_for_status()
result = response.json()

if result.get("ret") != 200:
    raise RuntimeError(
        f"API request failed: {result.get('msg')}"
    )

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

if not candles:
    raise RuntimeError("No candlestick data returned.")

for candle in candles:
    print(
        candle["timestamp"],
        candle["open_price"],
        candle["high_price"],
        candle["low_price"],
        candle["close_price"],
        candle["volume"]
    )

The kline_type parameter specifies the interval: 1 represents one-minute candles, 2 represents five-minute candles, and 8 represents daily candles. A kline_timestamp_end value of 0 requests data backward from the latest trading period. The example uses adjust_type: 0, the currently supported stock adjustment setting documented for this endpoint.

The response contains a kline_list array. Price, volume, and timestamp fields are returned as strings, so convert them to appropriate numeric or datetime types before using them in calculations. For financial calculations that require decimal precision, consider using Python's Decimal rather than relying on floating-point arithmetic.

Keep your API key in an environment variable or secrets manager. Never publish credentials in source code or public repositories.

Retrieve Latest Quotes and Order Book Data

Historical candles help reconstruct past price movements, but a live strategy also needs current market information.

AllTick's market-data interfaces provide access to latest quotes, including fields such as the latest trade price, volume, turnover, trade time, and trade direction. The latest order book interface provides bid and ask prices with their corresponding quantities.

These data types serve different purposes. Latest quotes help a strategy monitor current market conditions, while order book data can help quantify displayed liquidity and evaluate the price levels available on each side of the market.

A critical distinction is that latest quote data is not the same as historical tick-by-tick data. A current quote endpoint should not be treated as a way to reconstruct every past trade.

Before implementing quote or depth requests, select the appropriate AllTick interface version and follow its corresponding request method, authentication format, and parameter structure. AllTick documents both legacy HTTP market-data interfaces and newer /v1 REST endpoints; their request paths and authentication requirements differ.

Subscribe to Live Market Data with WebSocket

Repeated HTTP requests can be inefficient when a strategy needs continuous updates. WebSocket provides a persistent connection for receiving supported market-data messages as they arrive.

The following example subscribes to five levels of order book data for two stocks. It uses the documented stock WebSocket interface and sends an application-level heartbeat every 10 seconds.

Install the client library:

text
pip install websocket-client

Set ALLTICK_WS_TOKEN to your WebSocket authentication token before running the script.

text
import json
import os
import threading
import time
import uuid
from urllib.parse import quote

import websocket


class Feed:
    def __init__(self):
        token = quote(
            os.environ["ALLTICK_WS_TOKEN"],
            safe=""
        )

        self.url = (
            "wss://quote.alltick.co/"
            f"quote-stock-b-ws-api?token={token}"
        )

    def on_open(self, ws):
        subscription = {
            "cmd_id": 22002,
            "seq_id": 1,
            "trace": str(uuid.uuid4()),
            "data": {
                "symbol_list": [
                    {"code": "700.HK", "depth_level": 5},
                    {"code": "UNH.US", "depth_level": 5}
                ]
            }
        }

        ws.send(json.dumps(subscription))

        threading.Thread(
            target=self.heartbeat,
            args=(ws,),
            daemon=True
        ).start()

    def heartbeat(self, ws):
        seq_id = 1000

        while ws.keep_running:
            time.sleep(10)

            if not ws.keep_running:
                break

            try:
                ws.send(json.dumps({
                    "cmd_id": 22000,
                    "seq_id": seq_id,
                    "trace": str(uuid.uuid4()),
                    "data": {}
                }))
                seq_id += 1
            except Exception as exc:
                print("Heartbeat failed:", exc)
                break

    def on_message(self, ws, message):
        try:
            print(json.loads(message))
        except json.JSONDecodeError:
            print("Received a non-JSON message")

    def on_error(self, ws, error):
        print("WebSocket error:", error)

    def on_close(self, ws, status_code, message):
        print("Connection closed:", status_code, message)

    def run(self):
        ws = websocket.WebSocketApp(
            self.url,
            on_open=self.on_open,
            on_message=self.on_message,
            on_error=self.on_error,
            on_close=self.on_close
        )
        ws.run_forever()


if __name__ == "__main__":
    Feed().run()

In this example, cmd_id: 22002 requests order book data, while cmd_id: 22000 sends the heartbeat. AllTick also documents a separate subscription protocol for latest trade prices. Use the corresponding subscription example when your strategy needs trade-price updates rather than order book depth.

For production systems, add automatic reconnection, subscription restoration, structured logging, and validation of incoming messages. A successful connection does not by itself guarantee that a subscription has been accepted or that every update has been processed.

REST and WebSocket authentication also use different request formats: the newer REST API uses the X-API-Key header, while the documented WebSocket connection includes a token in its URL. Follow the instructions for the interface you are integrating.

Validate Market Data Before Backtesting

API access is only part of a reliable quantitative workflow. Before using retrieved data to evaluate a strategy, check three things.

  • Timestamp consistency: Confirm timestamp units, timezone interpretation, and alignment with the relevant trading session.
  • Data quality: Check for missing candles, duplicate records, unexpected gaps, and invalid prices before calculating indicators.
  • Look-ahead bias: Do not use a candle's final closing price to generate a signal before that candle has closed and the value would have been available to the strategy.

Also distinguish historical analysis from live execution. Historical candles support backtesting, while quote and WebSocket interfaces provide current information. Combining them requires consistent instrument identifiers, timestamps, and signal-generation rules.

Build a Reproducible Python Trading Workflow

A practical starting point is to retrieve historical K-lines, validate the data, and run a reproducible backtest. Add latest quotes or WebSocket updates when the strategy requires live monitoring or more granular market information.

AllTick's interfaces support these different market-data tasks, subject to the relevant instrument coverage and interface limitations. Before integrating additional endpoints, consult the AllTick REST API documentation and WebSocket API documentation for the current request examples and parameters.

Reliable quantitative trading starts with data that can be retrieved, validated, and interpreted consistently. Choosing the right interface for each stage helps keep historical research and live strategy monitoring aligned.

Start streaming market data today

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