Skip to main content

How to Properly Maintain a Local Copy of the Order Book

  1. Open a WebSocket connection and subscribe to spot@public.aggre.depth.v3.api.pb@(100ms|10ms)@{symbol}

  2. Start caching received incremental depth updates, and record the fromVersion of the first push message

  3. Request https://api.mexc.com/api/v3/depth?symbol={symbol}&limit=5000 to obtain a depth snapshot, and record lastUpdateId

  4. If lastUpdateId < the fromVersion of the first push, return to Step 3 and fetch the snapshot again

  5. From the cached incremental updates, discard all pushes where toVersion <= lastUpdateId

  6. Take the first remaining push. If fromVersion > lastUpdateId + 1, the data is considered discontinuous; return to Step 3 and reinitialize

  7. 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's toVersion. If any push does not satisfy: fromVersion = previous toVersion + 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.