AllTick
A Hong Kong skyline and harbor combined with real-time financial charts, order-book data, and flowing digital data connections
Market-DataTick-DataHong Kong Stocks real-time market data

What is the real-time Hong Kong stock market data API?

Learn how to integrate a real-time Hong Kong stock market data API using AllTick REST and WebSocket interfaces, with Python examples, order-book subscriptions, heartbeat handling, and production integration tips.

AllTick5 min read

For fintech developers building stock dashboards, market monitoring tools, or trading applications, a real-time Hong Kong stock market data API provides a structured way to bring market information into a product without parsing financial websites.

A market data API typically exposes current quotes, trade updates, and other market information through programmatic interfaces. REST is useful for on-demand queries, while WebSocket supports continuous updates over an established connection.

The right setup depends on the application’s requirements: which Hong Kong stocks it monitors, whether it needs the latest trade price or multiple order-book levels, and how it handles interruptions in the data stream.

What Data Does a Hong Kong Stock Market API Need to Provide?

Before integrating an API, developers should distinguish between several data types. They support different application features and are not interchangeable.

Data typeTypical application
Latest trade priceLive price displays and price alerts
Tick updatesIntraday monitoring and real-time processing
Level 1 quotesWatchlists and basic market dashboards
Order-book depthInspecting multiple bid and ask levels
Historical K-line dataCharts, indicators, and backtesting
Stock reference dataSymbol lookup and instrument identification

The distinction between live and historical data is particularly important. A stream of current trade updates does not automatically provide historical tick records. Applications that need historical backtesting should verify that the provider supports the required historical data separately.

Developers should also check symbol formats, timestamp conventions, market-data entitlements, and whether the data is real-time or delayed under their chosen plan.

How AllTick API Supports Hong Kong Stock Integration

AllTick provides REST and WebSocket interfaces for stock market data, including Hong Kong stocks. Developers can use these interfaces for different parts of the same application instead of repeatedly polling a webpage.

For example, an application might use REST to retrieve historical K-line data or an initial snapshot, then use WebSocket to keep a stock page updated as new data arrives.

For live Hong Kong stock data, AllTick supports subscriptions for latest trade-price updates and order-book data. Its order-book interface documents up to 10 levels for Hong Kong stocks, although the available data and subscription limits should be checked against the applicable plan.

The official WebSocket order-book documentation provides the request format and response structure. The following example uses Chow Tai Fook (1929.HK) to demonstrate a five-level subscription.

Quick-Start Integration with Python

Install the websocket-client package before connecting:

text
pip install websocket-client

Store your AllTick token in an environment variable named ALLTICK_TOKEN. The following example connects to the stock WebSocket service, subscribes to five levels of order-book data for 1929.HK, and sends the required heartbeat every 10 seconds.

text
import json
import os
import threading
import time
import uuid

import websocket

TOKEN = os.environ["ALLTICK_TOKEN"]
WS_URL = (
    f"wss://quote.alltick.co/"
    f"quote-stock-b-ws-api?token={TOKEN}"
)


def send_heartbeats(ws):
    while ws.keep_running:
        time.sleep(10)

        if not ws.keep_running:
            break

        try:
            if ws.sock and ws.sock.connected:
                heartbeat = {
                    "cmd_id": 22000,
                    "seq_id": int(time.time()),
                    "trace": f"heartbeat-{uuid.uuid4()}",
                    "data": {}
                }
                ws.send(json.dumps(heartbeat))
        except (websocket.WebSocketException, OSError):
            break


def on_open(ws):
    threading.Thread(
        target=send_heartbeats,
        args=(ws,),
        daemon=True
    ).start()

    request = {
        "cmd_id": 22002,
        "seq_id": 123,
        "trace": f"hk-depth-{uuid.uuid4()}",
        "data": {
            "symbol_list": [
                {
                    "code": "1929.HK",
                    "depth_level": 5
                }
            ]
        }
    }

    ws.send(json.dumps(request))


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


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


def on_close(ws, close_status_code, close_msg):
    print("WebSocket closed:", close_status_code, close_msg)


ws = websocket.WebSocketApp(
    WS_URL,
    on_open=on_open,
    on_message=on_message,
    on_error=on_error,
    on_close=on_close
)

ws.run_forever()

This example demonstrates the subscription flow, not a complete production client. Check the response for subscription errors before treating the stream as active.

The key parameters are:

  • cmd_id: 22002 requests order-book data.
  • code identifies the Hong Kong stock.
  • depth_level specifies the requested number of levels.
  • cmd_id: 22000 sends the application-level heartbeat.

For latest trade-price updates rather than order-book data, use the separate 22004 subscription command. The request format is described in the official latest trade-price subscription documentation.

REST vs WebSocket for Hong Kong Stock Data

The two interfaces serve different purposes.

RequirementSuitable interface
Retrieve historical K-line dataREST
Request a current snapshotREST
Receive continuous trade updatesWebSocket
Monitor changing bid and ask levelsWebSocket
Refresh data after reconnectingREST snapshot followed by WebSocket

A useful architecture combines both. REST supplies the initial data needed to render a stock page, while WebSocket updates the page as new messages arrive.

After a connection interruption, the application can fetch a fresh snapshot and resume its subscription. This helps prevent a dashboard from continuing to display outdated values while appearing connected.

Production Considerations and API Limits

Connecting successfully is only the beginning. A production market-data pipeline needs to handle subscription state, message validation, connection recovery, and storage.

Plan for reconnections. AllTick's WebSocket documentation specifies a heartbeat interval of 10 seconds and warns that a connection can be disconnected if no heartbeat arrives within 30 seconds. After reconnecting, the client should resubscribe and verify that updates are arriving.

Respect subscription behavior and rate limits. AllTick documents that a new subscription request can replace the previous subscription on the same connection. When adding symbols, send the complete intended symbol list rather than assuming the new request will append to the old one. The WebSocket limits documentation also explains connection and request-frequency restrictions.

Validate incoming data. Check symbols, timestamps, prices, volumes, and bid/ask levels before passing messages to downstream services. Handle empty order-book sides and missing fields without crashing the application.

Separate ingestion from storage. For a larger application, a maintainable design separates the WebSocket client, validation and normalization, persistent storage, and downstream consumers. PostgreSQL, TimescaleDB, or ClickHouse may be suitable storage choices depending on query patterns and data volume.

Protect credentials. Keep tokens in environment variables or a secret-management service, and avoid logging authentication URLs containing tokens.

Finally, test with the actual symbols and expected subscription volume. An application tracking a handful of stocks has different connection and scaling requirements from a service monitoring hundreds or thousands.

Choosing an API for Your Application

For fintech developers, choosing a Hong Kong stock market data API is not simply a matter of finding a provider that returns a price. The decision depends on the data required, supported protocols, subscription limits, and how the application will recover from interruptions.

AllTick offers REST and WebSocket interfaces that can support this integration pattern, including Hong Kong stock trade updates and order-book subscriptions. Developers can begin with a single symbol such as 1929.HK, validate the response structure, and expand the subscription once the application handles heartbeats, failures, and data normalization correctly.

Before deployment, verify the required market-data coverage and current plan restrictions in the official AllTick API documentation.

Start streaming market data today

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