How to Properly Maintain a Local Copy of the Order Book
-
Open a WebSocket connection and subscribe to
spot@public.aggre.depth.v3.api.pb@(100ms|10ms)@{symbol} -
Start caching received incremental depth updates, and record the
fromVersionof the first push message -
Request
https://api.mexc.com/api/v3/depth?symbol={symbol}&limit=5000to obtain a depth snapshot, and recordlastUpdateId -
If
lastUpdateId< thefromVersionof the first push, return to Step 3 and fetch the snapshot again -
From the cached incremental updates, discard all pushes where
toVersion<=lastUpdateId -
Take the first remaining push. If
fromVersion>lastUpdateId + 1, the data is considered discontinuous; return to Step 3 and reinitialize -
Set the local order book to the snapshot data, set the local version to
lastUpdateId, and apply all remaining and subsequent incremental pushes in order. After each update, set the local version to that push'stoVersion. If any push does not satisfy:fromVersion= previoustoVersion+ 1, you must reinitialize.
Note: Because the depth snapshot limits the number of price levels, levels outside the snapshot that have not changed in quantity will not appear in incremental pushes. The local order book may therefore differ slightly from the real order book. For most use cases, the 5000-depth limit is sufficient to understand the market and trade effectively.