Price-Time Priority in Code

Matching is the part candidates think is hard and is not. It is one loop. What separates implementations is a handful of rules that are easy to state and easy to get subtly wrong, and hidden tests are built from exactly those.

The loop

An aggressive order arrives. While it has quantity left and the opposite side has a level that its limit price permits, take from the front of that level's queue.

def match(book, incoming):
    fills = []
    while incoming.quantity > 0:
        level = book.best_opposite(incoming.side)
        if level is None or not crosses(incoming.price, level.price, incoming.side):
            break
        resting = level.front()
        traded = min(resting.quantity, incoming.quantity)
        fills.append(Fill(resting.id, incoming.id, traded, level.price))
        resting.quantity -= traded
        incoming.quantity -= traded
        if resting.quantity == 0:
            level.pop_front()
        if level.empty():
            book.remove_level(level.price)
    if incoming.quantity > 0:
        book.rest(incoming)          # or cancel, depending on order type
    return fills

The rest of this lesson is for subscribers

Unlock every lesson in Programming for Quantitative Developers, and every other premium course.

Subscribe to continue

Test your knowledge

Questions are only available to subscribers.

Keep reading Programming for Quantitative Developers

25 lessons in this course, and every other premium course, on one subscription.

  • Every lesson in every course, with the worked examples and interactive simulators
  • Graded questions on every lesson, with explanations for the wrong answers as well as the right one
  • The trainers, timed assessments and brainteaser library that go with them