DEV Community

kelos
kelos

Posted on

Looking for a multi‑market stock API? Pull A‑Share, Hong Kong and US quotes in Python

Intro

If you track equities across multiple markets — A‑Share, Hong Kong, and US stocks — you’ve probably bounced between multiple apps or browser tabs just to keep up with live prices.

I do a lot of personal market research and small quantitative prototyping. At first, my workflow was straightforward: open one tool for each market and switch back and forth to compare ticker data.

This setup worked fine until trading hours overlapped. Hong Kong market opening happened at the same time as US pre‑market session. I was manually cross‑checking prices across different interfaces, and human reaction delay made me miss a notable price movement.

That pushed me to look for a better approach. Instead of manually juggling dashboards, why not consume real‑time quotes for all three markets from one Python program via a stock API and let code handle monitoring?

How to evaluate multi‑market stock APIs

Many services claim to provide global stock data, but integration often reveals hidden drawbacks. Based on my practical testing, I prioritize these four criteria:

1. Built‑in multi‑market coverage

Your chosen API should natively support A‑Share, Hong Kong, and US stocks. Several providers only focus on US equities. If Asian markets require extra third‑party services, you will face extra integration work, data alignment issues and higher maintenance costs.

2. WebSocket stability & low latency

Market opening and pre‑auction periods generate heavy quote traffic, which acts as a real‑world stress test for APIs. If your WebSocket connection lags or drops during these peak windows, your live feed stops working. Any market observation or prototype strategy you build will become unusable.

3. Unified data schema across markets

This is often overlooked. When different markets return inconsistent field names, price precision and timestamp formats, you end up writing messy conditional parsing logic. Too many if‑else branches make your code harder to read, debug and extend. The best solution uses one shared schema for every supported market.

4. Pricing and free tiers (consider last)

Cost only matters when core functional requirements are satisfied. A low‑cost or free API brings little practical value if stability and data consistency are poor.

After benchmarking multiple services, I settled on AllTick API. It puts A‑Share, Hong Kong stocks, US equities, forex and other instruments behind one unified WebSocket protocol. Subscription logic remains identical across markets. There is no need to implement separate parsing modules for each region, which removes plenty of repetitive adaptation work.

Python code example: one WebSocket for three‑market real‑time quotes

This working demo uses the websocket‑client library. We establish one persistent connection to subscribe to live quotes for A‑Share, Hong Kong and US markets. The sample references official documentation and can be run locally directly.

import json
import websocket

# Replace with your own token
TOKEN = "YOUR_TOKEN"

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

# Sample tickers for A‑Share, US and Hong Kong markets
symbols = [
    {"code": "688036.SH"},
    {"code": "AAPL.US"},
    {"code": "700.HK"},
]


def on_open(ws):
    """Triggered when WebSocket handshake completes, send subscription request"""
    print("WebSocket connected")
    subscribe_req = {
        "cmd_id": 22002,
        "seq_id": 1,
        "trace": "devto_demo",
        "data": {
            "symbol_list": [
                {"code": item["code"], "depth_level": 1}
                for item in symbols
            ]
        }
    }
    ws.send(json.dumps(subscribe_req))


def on_message(ws, message):
    """Handle incoming real‑time quote push messages"""
    try:
        payload = json.loads(message)
        print(payload)
    except json.JSONDecodeError:
        print("Invalid JSON message")


def on_error(ws, error):
    print(f"WebSocket error: {error}")


def on_close(ws, code, msg):
    print(f"WebSocket closed, code:{code}, msg:{msg}")


if __name__ == "__main__":
    ws_app = websocket.WebSocketApp(
        WS_URL,
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    ws_app.run_forever()
Enter fullscreen mode Exit fullscreen mode

Once you start the script, real‑time market data streams continuously inside your terminal. All markets return millisecond timestamps and unified quote fields, so you avoid heavy conditional logic for market differentiation.

💡 Note: This is minimal demonstration code. For long‑running services, implement auto‑reconnection logic to handle temporary network flakiness. In my long‑term tests with reconnection added, unexpected disconnects rarely occurred.

Real‑world results

After launching the script, quotes from A‑Share, Hong Kong and US markets converge into a single console output. You no longer need to switch constantly between different market applications.

Even during high‑volatility Hong Kong pre‑auction time windows, data delivery stays responsive. Prices returned match those you see on web‑based market dashboards.

For developers and hobbyists doing cross‑market research or building small‑scale prototypes, the benefit is more than saving manual clicks. It eliminates information latency introduced by switching UI tools, reducing the chance of missing sudden price movements.

Wrap‑up

Fetching multi‑market real‑time stock data with Python is more than calling a random stock API. Market coverage, long‑connection stability and cross‑market schema consistency are critical evaluation points. With WebSocket persistent connections, you can aggregate A‑Share, Hong Kong and US quotes within one program for unified monitoring.

AllTick API used in this project lowers cross‑market integration complexity via its unified protocol, making it a good pick for hands‑on financial‑data development.

⚠️ Disclaimer: This article shares purely technical implementation practice, and does not constitute investment advice.

Top comments (0)