Skip to content
AllTick
Integration TutorialsPython 3.11 · requests 2.32

Python Stock Quotes: REST & Tick Parsing

Call the equity trade-tick REST endpoint in Python using requests, encode JSON query parameters, handle errors, and convert UTC timestamps.

Updated:
Maintained by:AllTick Technical Team
Audience:Developers making their first Python REST request to a market data API

Core Takeaway · 30-Second Brief

Fetching latest stock quotes in Python takes three steps: serialize your symbol query into a JSON string parameter, send an HTTP GET request with your API Token, and validate the return code before parsing tick_list. The example below queries Tencent (700.HK) and Apple (AAPL.US) in a single call.

01

Environment Setup

1Install Python 3.9 or newer.
2Install the HTTP client library: pip install requests
3Export your API Token via the ALLTICK_API_TOKEN environment variable rather than hardcoding credentials.
Terminal Commandbash
pip install requests
export ALLTICK_API_TOKEN="your_api_token"

02

Request Structure

AllTick REST endpoints accept filter parameters inside a URL query parameter named query formatted as a JSON string. For equities, the base URL is https://quote.alltick.co/quote-stock-b-api and the latest trade endpoint is /trade-tick.

ParameterLocationDescription
tokenURL QueryYour AllTick API Token
queryURL QueryJSON string containing trace and data
traceInside queryUnique request trace ID for debugging (UUID recommended)
data.symbol_listInside queryArray of ticker objects, e.g. [{"code": "700.HK"}]

03

Complete Runnable Code

stock_quote.pypython
import json, os, uuid
from datetime import datetime, timezone
import requests
BASE_URL = "https://quote.alltick.co/quote-stock-b-api"
def latest_trades(codes: list[str]) -> list[dict]:
token = os.getenv("ALLTICK_API_TOKEN", "YOUR_API_TOKEN")
query = {
"trace": str(uuid.uuid4()),
"data": {"symbol_list": [{"code": c} for c in codes]},
}
resp = requests.get(
f"{BASE_URL}/trade-tick",
params={"token": token, "query": json.dumps(query)},
timeout=10,
)
body = resp.json() if resp.content else {}
if body.get("ret") != 200:
raise RuntimeError(f"API error ret={body.get('ret')} msg={body.get('msg')}")
resp.raise_for_status()
return body.get("data", {}).get("tick_list", [])
def to_local_time(ms: str) -> str:
return datetime.fromtimestamp(int(ms) / 1000, tz=timezone.utc).astimezone().isoformat()
if __name__ == "__main__":
for tick in latest_trades(["700.HK", "AAPL.US"]):
print(tick.get("code"), tick.get("price"), to_local_time(tick.get("tick_time", "0")))

04

Understanding the Response Payload

A successful call returns ret: 200 with data.tick_list containing the latest trade for each requested symbol. Key fields include code (symbol), price (trade price as string), volume, and tick_time (UTC millisecond timestamp as string).

  • price is returned as a string; convert to Decimal before arithmetic to avoid floating-point precision loss.
  • tick_time is a UTC timestamp in milliseconds; convert to the exchange timezone before display.
  • During market closures, the endpoint returns the last recorded trade and tick_time remains static.

05

Common Errors & Fixes

SymptomLikely CauseResolution
Missing ALLTICK_API_TOKENEnvironment variable not exportedRun export ALLTICK_API_TOKEN in the active shell
ret != 200Invalid token, rate limit, or malformed queryInspect msg and see the 401/429 diagnostic guide
Empty tick_listWrong symbol format or unsupported marketVerify exact ticker notation such as 700.HK
ReadTimeoutNetwork latency or proxy issueCheck outbound connectivity and keep an explicit timeout

Sources & Verification · 2026-10-13

Relevant endpoint, field, and exchange rules were checked against the primary specifications linked below.

Python examples passed ast.parse on Python 3.14.0. This checks syntax only; dependencies, runtime compatibility, and network responses were not tested.

Authenticated AllTick requests and production end-to-end tests were not run for this review. Record your token plan, library versions, market session, ret/trace, and observed results when reproducing these checks.

Reproduce before deployment

  • Test a supported stock, unknown symbol, expired token, and forced timeout. Inspect HTTP status and API ret independently, redact tokens, and compare requested and returned codes.
  • The latest /trade-tick snapshot is not historical ticks. Convert tick_time from milliseconds to UTC and label closed-session values as the last known trade.