DEV Community

Academic Quant
Academic Quant

Posted on Originally published at academicquant.co.uk

A limit order book bug that only shows up after a level empties

I'd guess that most people preparing for a quant developer interview write a limit order book at some point, and I wrote a small one in Python recently to go with some practice material. I thought it was finished, but it wasn't, and I think the way I found out is worth more than the book itself.

My book keeps a dict on each side that maps a price to a queue of orders, oldest first, and it keeps a heap so that it can find the best price quickly. When a price level runs out of orders I don't bother taking it out of the heap at once. I just skip it the next time it comes to the top, which people call lazy deletion. Every test I wrote by hand passed. Then I wrote one more test that sends 3,000 random orders and cancels to my book and also to a very slow version that keeps everything in a list and searches it each time, and it checks that the two agree after every single step. It failed, because my book said there was no best bid and the slow version said there was one at 101.

What had happened was this. An order came in and filled against the last order resting at 101, and my code took that order off its queue but forgot to remove the empty queue from the dict. A bit later the heap got to 101, found nothing there and dropped it, which is fine. But when a new bid came in at 101, my code checked the dict, saw that a level for 101 already existed and so didn't put 101 back on the heap. The new order was sitting in the book and the heap had no idea it was there.

The fix is to delete the level as soon as it empties:

if rest.qty == 0:
    queue.popleft()
    del self.orders[rest.oid]
    if not queue:
        del self.levels[other][p]
Enter fullscreen mode Exit fullscreen mode

My cancel code already did that, which I suspect is why none of my own tests caught it. If you get this question in an interview, I'd make sure that whatever decides a level is still alive and whatever decides a price needs to go back on the heap agree with each other. I'd also say that a random test against a slow but obviously correct version takes ten minutes to write and finds the cases you would never think of.

There's more on how a real trading system lays out its order book here: https://academicquant.co.uk/qd-order-book?utm_source=devto&utm_medium=post&utm_campaign=devto-order-book-empty-level

Top comments (0)