📌LT;DR
AllTick’s China stock API provides a powerful, reliable solution for accessing real-time market data. With 99.95% SLA uptime, our system ensures consistent, uninterrupted data delivery. We offer wide coverage of 100,000+ symbols across global markets, including China’s A-shares. Our low-latency WebSocket interface delivers ultra-fast, 170ms latency for real-time updates, while our tick-by-tick data ensures precise, synchronized trading quotes. Whether you’re building a trading platform or developing quantitative strategies, AllTick’s API offers the speed, accuracy, and reliability you need to stay ahead in the fast-moving China stock market.
Create a free account now!

China’s A-shares market is one of the most fascinating and debated financial landscapes in the world. Some view it as fraught with risks, even calling it a scam, while others have uncovered immense opportunities, earning substantial profits. Now, as the U.S. Federal Reserve transitions into a rate-cutting cycle, global capital is beginning to flow into this undervalued market, which has languished for over two years.

For traders and developers, this shifting dynamic underscores the critical need for reliable, real-time market data to navigate the opportunities and challenges of A-shares trading. At AllTick, we understand that access to accurate data can be a game-changer, providing the edge needed to make informed decisions in this volatile environment.

In this article, we will explore how to access real-time China A-shares market data through our API. Whether you’re looking to enhance your trading strategies or optimize your platform’s performance, this guide will equip you with the tools to capitalize on the emerging opportunities in China’s A-shares market.

What is a Stock API?

A Stock API is a tool that allows developers and businesses to access stock market data programmatically, delivering critical information like real-time prices, historical data, trading volumes, and financial indicators directly to applications and platforms. This is especially valuable in fast-moving markets like China’s A-shares, where access to accurate and timely data can significantly impact decision-making and performance.

Stock APIs typically leverage two key technologies: REST and WebSockets.

  • REST APIs are ideal for on-demand data retrieval, such as fetching historical trends, conducting financial analysis, or accessing specific market insights. They provide a flexible solution for applications that don’t require constant updates but need structured, reliable information for strategic planning.
  • WebSockets, on the other hand, offer real-time, continuous data delivery by maintaining an open connection between the client and server. This makes them perfect for live-streaming market updates, such as price changes or order book movements, enabling responsive and high-performance trading systems.

At AllTick, we provide a powerful Stock API that supports both REST and WebSocket technologies, giving you the flexibility to handle both real-time and on-demand data needs. Whether you’re building a trading platform, automating a strategy, or conducting market analysis, our solutions ensure you stay ahead in the dynamic A-shares market.

Why AllTick API?

When it comes to accessing reliable and high-quality market data, AllTick API stands out for several reasons that can elevate your trading and development efforts.

Reliable Market Data Source
We understand that consistency is key in trading, which is why our system boasts an impressive 99.95% SLA. This means you can count on our API to deliver uninterrupted, real-time market data with minimal downtime. At AllTick, we’re committed to raising the standards for data quality and system uptime to ensure that your platform or trading strategy remains powered by the most reliable information available.

Wide Coverage
AllTick API supports around 100,000 symbols across a vast range of assets, from global stocks to futures, commodities, forex, and more. Whether you’re focusing on China A-shares, U.S. stocks, or international markets, our extensive coverage ensures that you have access to the data you need, no matter where or what you trade.

Low-Latency Interface for Real-Time Push
For high-frequency traders and real-time applications, latency is critical. That’s why AllTick API delivers a low-latency interface for real-time data streams via WebSocket, with an average latency of just 170 milliseconds. This ultra-fast connection ensures that you receive updates as quickly as the market moves, giving you the edge in fast-paced environments.

High-Frequency Data with Tick-by-Tick Updates
AllTick doesn’t just provide real-time market data—we offer tick-by-tick updates that are 100% synchronized with the exchange’s trading quotes. This means every data point is traceable, ensuring accuracy and precision in every trade. For quantitative traders and algorithmic systems, this level of data granularity is essential for crafting sophisticated strategies that react to market conditions in real-time.

With AllTick, you’re not just getting an API; you’re gaining access to a high-performance, scalable, and reliable solution that powers your trading and development goals.

Test Our Stock API

Click the image below to test our Stock Market Data API.

Just input the stock code and click to fetch the data.

How to Get Started with Our HK Stock Data API

Getting started with AllTick’s HK Stock Data API is quick and easy. Here’s how:

Create an Account

First, head over to our registration page and create your account at https://alltick.co/en-US/register. Registration is completely free, and no credit card is required. You can even simplify the process by signing up with your Google account.

Access Your Dashboard and API Key

After you complete registration, you’ll be automatically redirected to your account dashboard. Here, you’ll see your very own unique API key. This key is essential for accessing our data and should accompany every data request you make.

With just a few steps, you’ll have everything you need to start leveraging AllTick’s real-time HK stock data. To help you make the most of our API, we recommend checking out our API documentation and exploring our GitHub repository for additional resources and examples.

And remember, if you need help or have questions, our support team is ready to assist. Let’s get you connected and trading with real-time insights!

Code Example

HTTP request:

import time
import requests
import json

# Extra headers for the API request
test_headers = {
    'Content-Type': 'application/json'
}

# Note: Replace "testtoken" in the URLs below with your actual API token.

# Define the API endpoints for different types of data, updating the stock code to "5.HK" for HSBC
test_url1 = 'https://quote.tradeswitcher.com/quote-stock-b-api/kline?token=testtoken&query=%7B%22trace%22%20%3A%20%22python_http_test1%22%2C%22data%22%20%3A%20%7B%22code%22%20%3A%20%225.HK%22%2C%22kline_type%22%20%3A%201%2C%22kline_timestamp_end%22%20%3A%200%2C%22query_kline_num%22%20%3A%202%2C%22adjust_type%3A%200%7D%7D'
test_url2 = 'https://quote.tradeswitcher.com/quote-stock-b-api/depth-tick?token=testtoken&query=%7B%22trace%22%20%3A%20%22python_http_test2%22%2C%22data%22%20%3A%20%7B%22symbol_list%22%3A%20%5B%7B%22code%22%3A%20%225.HK%22%7D%2C%7B%22code%22%3A%20%22UNH.US%22%7D%5D%7D%7D'
test_url3 = 'https://quote.tradeswitcher.com/quote-stock-b-api/trade-tick?token=testtoken&query=%7B%22trace%22%20%3A%20%22python_http_test3%22%2C%22data%22%20%3A%20%7B%22symbol_list%22%3A%20%5B%7B%22code%22%3A%20%225.HK%22%7D%2C%7B%22code%22%3A%20%22UNH.US%22%7D%5D%7D%7D'

# Send the first API request to retrieve kline data
resp1 = requests.get(url=test_url1, headers=test_headers)
time.sleep(1)  # Pause for a moment to avoid hitting the rate limit

# Send the second API request to get depth tick data
resp2 = requests.get(url=test_url2, headers=test_headers)
time.sleep(1)

# Send the third API request for trade tick data
resp3 = requests.get(url=test_url3, headers=test_headers)

# Print the decoded text returned by each request
text1 = resp1.text
print("Kline Data:", text1)

text2 = resp2.text
print("Depth Tick Data:", text2)

text3 = resp3.text
print("Trade Tick Data:", text3)

WebSockets:

import json
import websocket    # Ensure you have the websocket-client library installed: pip install websocket-client

'''
# Special Note:
# GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
# Token Application: https://alltick.co
# Replace "testtoken" in the URL below with your actual token.
# Stock API address:
# wss://quote.tradeswitcher.com/quote-stock-b-ws-api
'''

class Feed(object):

    def __init__(self):
        self.url = 'wss://quote.tradeswitcher.com/quote-stock-b-ws-api?token=testtoken'  # Replace with your actual WebSocket URL and token
        self.ws = None

    def on_open(self, ws):
        """
        Callback executed when the WebSocket connection is opened.
        """
        print('A new WebSocketApp is opened!')

        # Example subscription parameters
        sub_param = {
            "cmd_id": 22002,
            "seq_id": 123,
            "trace": "3baaa938-f92c-4a74-a228-fd49d5e2f8bc-1678419657806",  # Unique trace identifier
            "data": {
                "symbol_list": [
                    {
                        "code": "1929.HK",  # Chow Tai Fook stock code
                        "depth_level": 5,  # Market depth level
                    }
                ]
            }
        }

        # Send the subscription request to WebSocket
        sub_str = json.dumps(sub_param)
        ws.send(sub_str)
        print("Depth quotes subscribed for 1929.HK!")

    def on_message(self, ws, message):
        """
        Callback executed when a message is received.
        """
        # Parse the received message and print it
        result = json.loads(message)  # Safely parse the JSON message
        print(result)

    def on_error(self, ws, error):
        """
        Callback executed when an error occurs.
        """
        print(error)

    def on_close(self, ws, close_status_code, close_msg):
        """
        Callback executed when the WebSocket connection is closed.
        """
        print('The connection is closed!')

    def start(self):
        """
        Initiates the WebSocket connection and starts the listener.
        """
        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,
        )
        self.ws.run_forever()  # Keeps the connection open and continuously listens for messages

if __name__ == "__main__":
    feed = Feed()
    feed.start()  # Start the WebSocket feed