Order Book Simulator with Fair Volume Participation
Data Structure DesignModel answerLast updated
Build a limit order matching engine, then add participation-rate execution logic for one client, and finally extend to multiple clients with fair allocation.
Build a trading simulator in three progressive stages.
Stage 1: Limit Order Book
Create a matching engine for a single instrument that processes two event types:
NEW orderId side price qty— submits a new limit order wheresideis eitherB(buy) orS(sell)CANCEL orderId— removes any unfilled portion of the specified order
Matching behavior:
When a new order arrives, match it immediately against opposing resting orders using:
- Price priority — best available price executes first (highest for buys, lowest for sells)
- Time priority — among orders at identical prices, earlier submissions execute first
Each match creates a trade where:
- Trade price equals the resting order's limit price
- Trade quantity equals the minimum of what the incoming order needs and what the resting order offers
Required output: For each input event, return all trades generated (empty list if none).
Stage 2: Volume Participation for One Client
A client submits an order specifying:
- Target quantity
Qto execute - Participation rate
p(where 0 < p ≤ 1)
The market generates a sequence of volume events:
PRINT t marketQty— indicates thatmarketQtyshares traded at timet
Your execution algorithm must satisfy this constraint at all times:
clientExecutedSoFar ≤ floor(p × cumulativeMarketVolume)
Required output: For each print event, determine how many shares to execute for the client (may be zero), continuing until either Q is reached or the print stream ends.
Stage 3: Multiple Clients with Fair Allocation
Extend to handle multiple simultaneous client orders, each with its own (Q_i, p_i).
At each print event, allocate executions across all clients satisfying:
- Each client's execution respects
executed_i ≤ floor(p_i × cumulativeMarketVolume) - No client executes beyond their remaining quantity
- Total allocation at each print cannot exceed that print's
marketQty - When available volume is insufficient for all allowable executions, prioritize clients by smallest fill ratio:
executed_i / Q_i
Break ties by choosing the smaller clientId.
Implementation requirements:
- Clearly state your assumptions about edge cases
- Handle scenarios like canceling non-existent orders or participation rates allowing more than the remaining target
- Use exact arithmetic where precision matters
Hints
Hint 1
For the order book, consider using heaps with sequence numbers to enforce time priority within each price level
Hint 2
The participation constraint is cumulative across all prints—executing more now never reduces future allowance
Hint 3
When multiple clients compete for limited volume, a min-heap tracking fill ratios naturally implements the fairness requirement
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests event-driven simulation, priority-based matching, and quota-constrained allocation. Each stage builds on the previous one.
Stage 1: Order Book Implementation
Use two heaps to maintain buy and sell orders:
- Bids: max-heap by price (store negative prices), then FIFO by sequence number
- Asks: min-heap by price, then FIFO by sequence number
For each new order:
- Match against the opposite side while prices cross
- Generate trades using the resting order's price
- If quantity remains, add the order to the appropriate heap
For cancellations, use lazy deletion: mark the order as canceled (set quantity to zero) without searching through the heap. Skip zero-quantity orders when they surface at the heap top.
Key insight: Assigning a monotonically increasing sequence number to each order naturally implements time priority within price levels.
Stage 2: Single Client Participation
The constraint executed ≤ floor(p × V) is cumulative, where V is total market volume so far.
Greedy strategy: at each print, execute the maximum allowed amount:
execute = min(Q - alreadyExecuted, floor(p × cumulativeVolume) - alreadyExecuted)
This is optimal because executing sooner never constrains future executions—the allowance only grows.
Since p ≤ 1, the newly allowed amount never exceeds the print's market quantity, so no explicit volume check is needed.
Stage 3: Multi-Client Allocation
For each print:
- Compute each client's allowance using the Stage 2 formula
- If total allowances fit within
marketQty, grant all requests - Otherwise, use a min-heap keyed by
(executed_i / Q_i, clientId)and allocate one share at a time to the minimum element
Water-filling approach: Repeatedly grant shares to whoever is most under-filled relative to their target. This naturally satisfies the fairness requirement and handles dynamic reordering as fill ratios change during a single print.
Complexity
- Order book: O(log n) amortized per operation, where n is the number of orders. Each order is pushed and popped at most once. Space: O(n)
- Participation: O(C) per print for C clients to compute allowances, plus O(A log C) for allocation when contended, where A is allocated shares
Edge Cases & Common Mistakes
- Floating-point precision:
0.29 × 100in floating-point gives 28.999..., which floors to 28 instead of 29. UseFractionfrom Python'sfractionsmodule for exact arithmetic - Canceling non-existent orders: Treat as no-op, generate no trades
- Orders crossing multiple price levels: A single incoming order may match several resting orders at different prices
- Allowance exceeding remaining quantity: Cap execution at
Q - executedeven if the participation rate allows more - Finished clients: Once a client reaches Q, they receive zero allocation at all subsequent prints
- Zero-quantity prints: All clients receive zero allocation
Solution
import heapq
import itertools
import math
from fractions import Fraction
# ============ Stage 1: Order Book ============
class Order:
def __init__(self, order_id, side, price, quantity):
self.order_id = order_id
self.side = side
self.price = price
self.quantity = quantity
class LimitOrderBook:
def __init__(self):
self.buy_orders = [] # max-heap: (-price, seq, order)
self.sell_orders = [] # min-heap: (price, seq, order)
self.active_orders = {}
self.sequence = itertools.count()
def handle_event(self, event_line):
tokens = event_line.split()
if tokens[0] == "CANCEL":
order_id = tokens[1]
if order_id in self.active_orders:
self.active_orders[order_id].quantity = 0
del self.active_orders[order_id]
return []
# NEW order
_, order_id, side, price, qty = tokens
price = Fraction(price)
qty = int(qty)
if order_id in self.active_orders:
return [] # reject duplicate
opposing_book = self.sell_orders if side == "B" else self.buy_orders
trades = []
# Match against opposing orders
while qty > 0 and opposing_book:
resting_order = opposing_book[0][2]
if resting_order.quantity == 0:
heapq.heappop(opposing_book)
continue
crosses = (side == "B" and resting_order.price <= price) or \
(side == "S" and resting_order.price >= price)
if not crosses:
break
trade_qty = min(qty, resting_order.quantity)
trades.append((resting_order.price, trade_qty, order_id, resting_order.order_id))
qty -= trade_qty
resting_order.quantity -= trade_qty
if resting_order.quantity == 0:
heapq.heappop(opposing_book)
del self.active_orders[resting_order.order_id]
# Add remaining quantity to book
if qty > 0:
new_order = Order(order_id, side, price, qty)
self.active_orders[order_id] = new_order
heap_key = -price if side == "B" else price
target_book = self.buy_orders if side == "B" else self.sell_orders
heapq.heappush(target_book, (heap_key, next(self.sequence), new_order))
return trades
# ============ Stages 2 & 3: Participation Execution ============
def execute_with_participation(clients, market_prints):
"""
clients: [(client_id, target_qty, participation_rate), ...]
market_prints: [(timestamp, market_qty), ...]
Returns: [(timestamp, {client_id: executed_qty}), ...]
"""
client_state = {
cid: {"target": Q, "rate": Fraction(str(p)), "executed": 0}
for cid, Q, p in clients
}
cumulative_volume = 0
results = []
for timestamp, market_qty in market_prints:
cumulative_volume += market_qty
# Compute allowances for each client
allowances = {}
for cid, state in client_state.items():
remaining = state["target"] - state["executed"]
if remaining > 0:
allowed_total = math.floor(state["rate"] * cumulative_volume)
new_allowance = allowed_total - state["executed"]
allowances[cid] = min(remaining, new_allowance)
allocations = {cid: 0 for cid in client_state}
total_requested = sum(allowances.values())
if total_requested <= market_qty:
# Grant all requests
for cid, amount in allowances.items():
allocations[cid] = amount
client_state[cid]["executed"] += amount
else:
# Fair allocation using min-heap
heap = []
for cid, allowance in allowances.items():
if allowance > 0:
ratio = Fraction(client_state[cid]["executed"], client_state[cid]["target"])
heapq.heappush(heap, (ratio, cid))
remaining_volume = market_qty
while remaining_volume > 0 and heap:
ratio, cid = heapq.heappop(heap)
allocations[cid] += 1
client_state[cid]["executed"] += 1
remaining_volume -= 1
# Re-add if client can still execute
if allocations[cid] < allowances[cid]:
new_ratio = Fraction(client_state[cid]["executed"], client_state[cid]["target"])
heapq.heappush(heap, (new_ratio, cid))
results.append((timestamp, allocations))
return results
This solution maintains clean separation between the three stages while reusing core concepts. The order book handles arbitrary matching scenarios efficiently, and the participation logic scales gracefully from one to many clients through careful priority management.