
How to Access Live Hong Kong Stock Data with AllTick API
Learn how to access Hong Kong stock data through AllTick REST API and WebSocket, with a practical Python example, response validation, connection management, and plan selection guidance.
For fintech developers building stock dashboards, portfolio trackers, or market-monitoring applications, accessing live Hong Kong stock data involves more than retrieving a price. The application also needs to handle updates efficiently, validate timestamps, and retrieve historical data when users want to review price movements.
AllTick provides REST API and WebSocket interfaces for market-data integration. REST is suitable for retrieving the latest available quote and historical K-line data, while WebSocket supports continuous updates for subscribed market data. Choosing the right interface for each task helps developers build a more responsive and maintainable application.
Choose the Right API for Your Application
The best approach depends on how frequently your application needs new data and how it will use the results.
| Requirement | Recommended interface | Typical use |
|---|---|---|
| Retrieve the latest stock quote | REST API | Stock detail pages and portfolio valuations |
| Load historical price data | REST API | Charts and technical analysis |
| Receive continuous price updates | WebSocket | Live watchlists and market-monitoring dashboards |
| Retrieve order-book information | REST API or supported WebSocket subscription | Bid-and-ask displays |
| Retrieve data for multiple stocks | Supported batch requests or WebSocket subscriptions | Multi-stock watchlists |
For example, a portfolio dashboard can use REST to load initial prices when a user opens the page. If the application needs continuous updates, WebSocket can deliver subsequent messages without repeatedly polling the same endpoint.
Historical K-lines serve a different purpose. They provide price series for charts and analysis, whereas a latest-quote response provides a market snapshot. AllTick's WebSocket documentation specifies that K-line push is not supported, so K-line retrieval should use the appropriate HTTP interface.
The key is to match the retrieval method to the task rather than treating every market-data request as a streaming requirement.
Retrieve Hong Kong Stock Quotes with Python
A practical integration starts with one stock. Retrieve its latest available quote, validate the response, and then pass the returned data to your application.
AllTick's REST API uses the X-API-Key header for authentication. The following Python example requests the latest quote for Tencent Holdings (700.HK).
First, install the required dependency:
pip install requestsSet your API key as an environment variable before running the script:
export ALLTICK_API_KEY="your_api_key"Then send the request:
import os
import requests
API_KEY = os.getenv("ALLTICK_API_KEY")
if not API_KEY:
raise SystemExit(
"Missing ALLTICK_API_KEY. Set it in your environment first."
)
URL = "https://quote.alltick.co/quote-stock-b-api/v1/quote"
PAYLOAD = {
"trace": "hk-stock-quote-001",
"data": {
"symbol_list": [
{"code": "700.HK"}
]
},
}
try:
response = requests.post(
URL,
headers={
"X-API-Key": API_KEY,
"Content-Type": "application/json",
},
json=PAYLOAD,
timeout=10,
)
response.raise_for_status()
except requests.exceptions.RequestException as exc:
raise SystemExit(f"HTTP request failed: {exc}") from exc
try:
result = response.json()
except ValueError as exc:
raise SystemExit(
"The API response was not valid JSON."
) from exc
if str(result.get("ret")) != "200":
raise SystemExit(
f"AllTick API returned an error: "
f"ret={result.get('ret')}, "
f"msg={result.get('msg', 'No message provided')}"
)
quotes = (result.get("data") or {}).get("tick_list") or []
if not quotes:
print(
"No quote records returned. Check symbol availability, "
"plan access, and the response."
)
else:
for quote in quotes:
print(
f"symbol={quote.get('code')} "
f"price={quote.get('price')} "
f"volume={quote.get('volume')} "
f"turnover={quote.get('turnover')} "
f"tick_time={quote.get('tick_time')}"
)The request body contains a tracking identifier and a list of stock symbols. You can add more entries to symbol_list to request multiple symbols in one call, subject to the applicable interface and plan limits.
The response's tick_list contains returned quote records. Fields such as code, price, volume, turnover, and tick_time can be used to associate a price with its stock and identify when the quote was generated. Check the actual response and the current documentation before relying on any particular field in production.
The example includes HTTP error handling, JSON parsing, API result checks, and empty-response handling. These checks matter because a successful HTTP response does not necessarily mean that usable quote records were returned.
Keep the API key on the backend instead of exposing it in browser-side JavaScript or public repositories. The example has been syntax-checked, but a successful live request still depends on a valid API key, symbol availability, plan permissions, and the actual API response.
Keep Stock Prices Updated with WebSocket
REST works well when an application needs a quote on demand or refreshes data periodically. When a watchlist or trading interface needs continuous updates, maintaining a WebSocket connection can be more appropriate.
The general workflow is to establish a connection using the authentication method specified in the documentation, subscribe to the required Hong Kong stock symbols, and process incoming messages as they arrive.
A production implementation should account for several details:
- Subscription management: Subscribe only to the symbols and data types the application needs. Keep an authoritative list of desired subscriptions and follow the documented rules for adding, replacing, and cancelling subscriptions.
- Heartbeat handling: The documented stock WebSocket interface requires a heartbeat every 10 seconds. If no heartbeat request is received within 30 seconds, the connection is disconnected.
- Reconnection: Detect unexpected disconnections, reconnect with a controlled retry policy, and restore the required subscriptions.
- Message validation: Check the symbol, price, sequence information when available, and timestamp before updating the displayed quote.
- Plan limits: Account for the maximum number of connections, supported data types, and request restrictions associated with your plan.
These controls prevent a common integration problem: the application appears to be connected, but its displayed prices are no longer being updated correctly.
Stale data is another consideration. If messages are processed asynchronously, an older update can arrive after a newer one. Where the data provides suitable sequence numbers or timestamps, use them to decide whether an incoming update should replace the stored value. Normalize timestamp units and timezones before comparing timestamps from different sources.
For connection settings, subscription commands, message formats, and heartbeat requirements, refer to the AllTick WebSocket API documentation.
Check Historical Data and Market Coverage
A stock dashboard often needs more than the latest price. Historical K-lines provide data for charts and technical analysis, while order-book information can support displays of bid-and-ask prices and quantities.
Use the appropriate interface for each requirement instead of trying to derive every feature from a latest-quote response. Also distinguish between historical price data and current market updates: they serve different purposes and should not automatically share the same refresh schedule.
Plan selection is another part of the integration. The following table summarizes the published limits for the main AllTick plans.
| Plan | Product coverage | API calls per minute | WebSocket connections | Historical K-line coverage |
|---|---|---|---|---|
| Free | 10 demo products | 10 | 1 | Up to 1 year; latest 500 stock K-lines |
| Basic | Up to 100 selected products | 60 | 1 | Up to 1 year; latest 500 stock K-lines |
| Premium | Up to 200 selected products | 600 | 3 | Up to 3 years; latest 500 stock K-lines |
| Professional | Up to 3,000 selected products | 1,200 | 10 | Up to 5 years; latest 500 stock K-lines |
| All HK Stocks | Approximately 3,000 Hong Kong stock symbols | 1,200 | 10 | Latest 500 historical K-lines |
The Free plan is useful for initial integration checks with supported demo products. If your application needs a wider selection of Hong Kong stocks, real-time tick updates, order-book data, or broader market coverage, verify that the required symbols and features are included in the selected plan.
The number of symbols is only one consideration. You should also estimate how frequently the application queries the API, how many concurrent connections it needs, and how much historical data it must load. A small personal watchlist and a market-wide scanner can have very different requirements.
Because plan limits and product availability can change, check the AllTick pricing page before choosing a plan for production.
Build a Reliable Hong Kong Stock Data Workflow
Once the appropriate interface and plan have been selected, the integration can be organized into three stages.
Load the initial data. Use REST to retrieve the required quotes and, where necessary, historical K-lines. Validate the response status, stock symbol, price, and timestamp before displaying the data.
Maintain updates. Use WebSocket when the application needs continuous updates. Implement heartbeat handling, reconnection, and subscription recovery while keeping the active symbol list consistent with the application's requirements.
Validate before displaying. Prevent older messages from overwriting newer values when sequence or timestamp information permits comparison. Account for market sessions, empty responses, and the possibility that the latest available quote may remain unchanged when no new market update has arrived.
This workflow separates data retrieval from data validation and display. That makes it easier to identify whether a problem comes from the API response, the connection, the update-processing logic, or the application's own state management.
For example, if a stock price stops changing, increasing the polling frequency should not automatically be the first response. Check the latest timestamp, connection status, subscription state, and relevant market session first. These checks help distinguish a data-access problem from expected market behavior or an application-side issue.
To get started, consult the AllTick REST API documentation for endpoint details and authentication, the REST API request examples for request formats, and the WebSocket API documentation for streaming requirements. Use the pricing page to choose a plan that matches your Hong Kong stock data needs.