Incremental Order Book Maintenance Mechanism
-
Obtain Full Depth Snapshot (Initialization) Endpoint:
GET https://api.mexc.com/api/v1/contract/depth/{symbol}?limit=1000Save the version from the response as localLastVersion. -
Subscribe to WebSocket Depth Stream
-
Subscribe to push.depth When a push.depth update is received:
- If the message
version>localLastVersion, updates for the same price level should override earlier ones (updates can be cached temporarily). - Under normal conditions, if
version==localLastVersion + 1, apply the update directly.
-
Packet Loss Recovery: Fetch Latest Depth Commits Endpoint:
GET https://api.mexc.com/api/v1/contract/depth_commits/{symbol}/1000Retrieves the latest 1000 depth incremental commits (sorted in ascending order by version). -
Apply Commits and Clear Cache Iterate through the commits
- skip any with
version<=localLastVersion. - Starting from the first commit where
version==localLastVersion + 1, sequentially apply each commit's updates (quantity > 0: update or - insert the price level; quantity == 0: delete the price level). - Update
localLastVersionto theversionof the last applied commit. - If there are cached WebSocket updates, apply them as well (higher version takes priority).
- Resume Real-Time Updates
- Continue applying incoming WebSocket events to the local order book.
- Each new event's version should be exactly equal to the previous
version + 1. - If the sequence is discontinuous (gaps or out-of-order versions), packet loss may have occurred → restart recovery from step 4 (or fall back to step 1 for full reinitialization).
- Update Rules
- The quantity in each event is an absolute value (the current total quantity at that price level, not a relative change).
- If quantity == 0, the price level has been canceled or fully filled and should be removed.