Intro
While building a simple A‑share market monitor for my quant lab work, I initially only cared about extracting obvious metrics: last price, total trading volume, and so on. My naive assumption was that pulling raw JSON from an A‑share real‑time market API and rendering it would finish the job.
Once I started running short‑term trading simulation workflows, I realized most actionable insight lives inside structured order‑book data. Level‑2 data is far more than a basic price snapshot. It carries granular bid‑ask tiers plus real‑time order change events. Bad parsing logic will desync your local order book from the real exchange state and mislead your trading simulation decisions.
Pain points: Regular market data vs Level‑2 data
Standard market APIs return lightweight records built for simple UI display. You mostly get last traded price, total volume, and price change.
Level‑2 is designed to reconstruct the full order book. It exposes five‑tier bid/ask prices & volumes, trade direction flags, and order‑update events. You can clearly observe shifts between buying pressure and selling pressure.
One common gotcha: A‑share real‑time market APIs don’t follow uniform field naming. Some wrap order tiers inside arrays, others split bids and asks into separate top‑level fields. Without standardized parsing logic, order‑book ratio calculations and strength comparisons will produce wrong results.
A typical five‑tier order‑book object includes ticker symbol, bid array, ask array, and timestamp. In my workflow I keep bid‑side and ask‑side processing separate:
- Bid side: extract best‑bid price and volume, aggregate total buy‑side depth
- Ask side: extract best‑ask price and volume, assess selling pressure
Keeping them isolated makes multi‑side calculations cleaner and speeds up debugging.
Efficiency note: Don’t compute directly on raw API payloads
I never feed unprocessed Level‑2 raw responses straight into indicator calculations. A normalization step is mandatory.
Raw unnormalized data can have mis‑sorted price tiers and inconsistent formatting. After normalization you can sum total bid/ask volumes and compute order‑book imbalance to spot market bias. Remember: no single metric makes a complete trading signal. Always combine execution speed, price movement, and broader market context.
Order‑book updates happen extremely frequently. HTTP one‑off queries work for ad‑hoc checks, but heavy polling burns API rate limits and you can easily miss fast‑evolving order‑book states. WebSocket streaming is the better fit for real‑time monitoring.
For my lab tests I subscribed to A‑share Level‑2 feeds via AllTick API and parsed order‑book structures from incoming push events.
import websocket
import json
def on_message(ws, message):
data = json.loads(message)
symbol = data.get("symbol")
bids = data.get("bid")
asks = data.get("ask")
print("Ticker:", symbol)
print("Bid tiers:", bids)
print("Ask tiers:", asks)
def on_open(ws):
sub_payload = {
"action": "subscribe",
"symbol": "600000",
"type": "level2"
}
ws.send(json.dumps(sub_payload))
if __name__ == "__main__":
ws_app = websocket.WebSocketApp("wss://api.alltick.co/stock/websocket",
on_open=on_open,
on_message=on_message)
ws_app.run_forever()
⚠️ Note: Minimal demo snippet for learning purposes. Production code needs auto‑reconnection, duplicate‑message filtering and timestamp validation. Lost messages will corrupt all downstream order‑book analysis.
Common parsing pitfalls to watch out for
These are three bugs I ran into while implementing my monitor:
- Price precision: Different A‑share instruments use different minimum price steps. Direct float arithmetic creates hidden precision errors and breaks price‑tier comparison.
- Message sequence skew: Network delivery order does not equal market event order. Always trust timestamps, never process messages purely in arrival order.
- Storage bloat: Level‑2 streams generate huge data volumes. Poor storage design will eat up server compute and disk resources very quickly.
My approach: normalize fields and unify the order‑book data structure first, then pass data to calculation and storage modules. If you later switch to another market‑data provider, high‑level business logic stays mostly unchanged.
Wrap‑up thoughts
Working through this project taught me that parsing Level‑2 is not just reading JSON fields. The real challenge is understanding what the order‑book structure tells us about capital flows.
Individual price and volume values are just numbers. Combined, they show how money is moving in the market. For quant developers, converting messy raw market data into consistent, well‑structured objects is more important than simply fetching API responses.
Solid foundations — timestamp handling, data cleaning, order‑book parsing — make later work like chart rendering and factor simulation much less painful.
Top comments (0)