Skip to main content
All questions
MediumArrays · Simulation

Order Book Imbalance

Written by a community member · · 3 attempts · 0% pass

0

Given a sequence of market events for a single stock, compute the maximum bid-ask imbalance observed after each event. Each event is one of the following:

  • B price quantity: add quantity shares to the bid side at price
  • A price quantity: add quantity shares to the ask side at price
  • C side price quantity: cancel up to quantity shares from the given side ('B' or 'A') at price

The imbalance after an event is defined as abs(total_bid_quantity - total_ask_quantity). Return the maximum imbalance seen over the entire event stream.

Assume all prices and quantities are positive integers. Cancels may remove fewer shares than requested if the book at that price has less available. If a cancel targets a price level with no shares on that side, it has no effect.

Example 1:
Input: events = ['B 100 10', 'A 101 7', 'B 100 5']
Output: 15
Explanation: After the three events, total bids are 15 and total asks are 7, so the imbalances are 10, 3, and 8. The maximum is 10.

Example 2:
Input: events = ['B 100 10', 'A 101 8', 'C B 100 4', 'C A 101 10']
Output: 10
Explanation: The imbalances are 10, 2, 6, and 2. The maximum is 10.

Implement a function max_order_book_imbalance(events: list[str]) -> int.