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 the received incremental depth updates, and record the fromVersion of the first received update.

3.Request the order book snapshot from https://api.mexc.com/api/v3/depth?symbol={symbol}&limit=5000 and record the lastUpdateId.

4.If lastUpdateId is less than the fromVersion of the first cached update, return to Step 3 and fetch the snapshot again.

5.From the cached incremental updates, discard all updates where toVersion is less than or equal to lastUpdateId.

6.Take the first remaining update. If fromVersion is greater than lastUpdateId + 1, the data is considered discontinuous. Return to Step 3 and reinitialize.

7.Initialize the local Order Book using the snapshot data, and set the local version to lastUpdateId.Then, sequentially apply all remaining cached updates and all subsequent incoming updates. After each update is applied, update the local version to the update’s toVersion. If any update does not satisfy: fromVersion = previous toVersion + 1, the Order Book must be reinitialized starting from Step 3.

Note: Since the depth snapshot has a limitation on the number of price levels, price levels outside the initial snapshot that have not changed in quantity will not appear in incremental push messages. Therefore, the local order book may differ slightly from the real order book. However, for most use cases, the 5000-depth limit is sufficient to effectively understand the market and trading activity.