Aggregated Multi-Venue Liquidity Tracker with BBO and NBBO
Data Structure DesignAuto-graded · 22 test casesLast updated
Build a system that maintains liquidity across trading venues and efficiently queries best prices per venue and across all venues.
Build an in-memory liquidity tracking system that consolidates order information from multiple trading venues. Each liquidity record specifies an exchange identifier, a price level, a quantity, and whether it represents buy interest (bid) or sell interest (ask).
Your system must provide three capabilities:
-
add(exchange, price, quantity, side) — Update the total quantity available at a specific price level on one side of one exchange. The quantity parameter represents a signed delta: positive values increase liquidity, negative values reduce it.
-
get_exchange_bbo(exchange) — Retrieve the best bid and offer for a single exchange, meaning the highest bid price and the lowest ask price currently available on that venue.
-
get_nbbo() — Determine the national best bid and offer across all exchanges: the single highest bid price and single lowest ask price from any venue.
Implement these operations using only Python's standard library (no external packages like sortedcontainers), and analyze their time complexity.
Rules and Edge Cases
- Liquidity is tracked per
(exchange, side, price)tuple. Multiple updates to the same tuple accumulate. - When a price level's total quantity reaches zero, that level is removed from the book and cannot be returned as a best price.
- If one side of an exchange has no active levels, return
Nonefor that side's best price. - Quantity updates are cumulative. If applying a delta would cause a level's total to drop below zero, raise a
ValueErrorwith the message"quantity cannot become negative". - An exchange that has never received any updates should return
[None, None]for its BBO. - You must use only the
heapqmodule from Python's standard library for heap operations. Do not import or usesortedcontainers,blist, or any third-party sorted data structures.
Constraints
- Exchange names are non-empty strings.
- Prices are positive floating-point numbers.
- Quantities are non-zero integers (positive or negative deltas).
- Side is either the string
"bid"or"ask". - Up to 10,000 total operations.
- Up to 100 distinct exchanges.
- Up to 1,000 distinct price levels per exchange per side.
Examples
Example 1
Input: execute_order_book(['add', 'add', 'add', 'get_exchange_bbo', 'get_nbbo'], [['NYSE', 100, 10, 'bid'], ['NYSE', 102, 5, 'ask'], ['NASDAQ', 101, 7, 'bid'], ['NYSE'], []])
Output: [None, None, None, [100, 102], [101, 102]]
Example 2
Input: execute_order_book(['add', 'add', 'add', 'add', 'get_nbbo', 'add', 'get_nbbo'], [['A', 10, 4, 'bid'], ['A', 12, 3, 'ask'], ['B', 11, 8, 'bid'], ['B', 13, 2, 'ask'], [], ['A', 10, -4, 'bid'], []])
Output: [None, None, None, None, [11, 12], None, [11, 12]]
Hints
Hint 1
Use a heap per side per exchange to track the best price, but remember that cancelled levels leave stale entries behind
Hint 2
Maintain a global heap for each side that stores entries from all exchanges, but verify each entry is still current before trusting it
Hint 3
When an exchange's best price changes, push a new versioned entry into the global heap instead of updating in place
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution maintains separate structures for per-exchange tracking and global aggregation using only Python's standard library heapq module:
Per-Exchange State: For each exchange and side (bid/ask), we keep:
- A dictionary mapping price levels to their current quantities
- A min-heap (for asks) or max-heap (for bids, storing negated prices) containing all price levels that have ever been active
When quantity updates arrive, we modify the dictionary immediately. However, we do not remove prices from the heap when levels empty—this would require linear search. Instead, we use lazy deletion: stale heap entries remain until they bubble to the top, at which point we discard them.
Global State: Two heaps (one per side) store candidate best prices from all exchanges. Each entry is a tuple (priority, exchange, version) where the version number increments whenever that exchange's best price changes. Before trusting a heap entry, we verify its version matches the exchange's current version and the price still equals the exchange's actual best.
Operations:
add: Update the quantity dictionary, push the price into the heap if newly active, then check whether the exchange's best price changed. If so, increment that exchange-side version and push a new entry into the global heap.get_exchange_bbo: Prune stale entries from each side's heap until the top reflects a positive-quantity level, then return those prices.get_nbbo: Pop stale or outdated entries from each global heap until finding one whose version and price match the source exchange's current state.
Why This Works
Lazy deletion ensures we never scan the entire heap to remove interior elements. Each price level eventually reaches the heap top and gets removed in O(log n) time. The global heaps allow constant-time access to candidate best prices while version checks prevent reporting stale data after an exchange's true best has changed.
Complexity
- add: O(log P) amortized per operation, where P is the number of distinct price levels on one side of one exchange. The dictionary update is O(1), the heap push is O(log P), and each stale entry is removed once amortized.
- get_exchange_bbo: O(log P) amortized. Pruning removes each stale entry once.
- get_nbbo: O(E log E) amortized, where E is the number of exchanges. Each outdated global entry is popped once, and in the worst case we verify the current best for multiple exchanges.
Space: O(E · P) for the dictionaries and per-exchange heaps, plus O(E · U) for the global heaps where U is the number of best-price changes. In practice, stale global entries can accumulate; periodic full reconstruction or reference counting can bound this growth.
An alternative is a balanced tree (e.g., a sorted container) per side, which supports O(log P) insertion, deletion, and min/max queries with no lazy cleanup, at the cost of higher constant factors and requiring external libraries.
import heapq
from typing import List, Optional
def execute_order_book(operations, arguments):
exchange_books = {}
global_best_heaps = [[], []]
exchange_versions = {}
output = []
def prune_stale_levels(exch, side_idx):
level_quantities, price_heap = exchange_books[exch][side_idx]
while price_heap:
top_price = -price_heap[0] if side_idx == 0 else price_heap[0]
if level_quantities.get(top_price, 0) > 0:
break
heapq.heappop(price_heap)
def fetch_best_price(exch, side_idx):
if exch not in exchange_books:
return None
prune_stale_levels(exch, side_idx)
level_quantities, price_heap = exchange_books[exch][side_idx]
if not level_quantities:
return None
return -price_heap[0] if side_idx == 0 else price_heap[0]
def push_to_global(exch, side_idx):
prune_stale_levels(exch, side_idx)
version_key = (exch, side_idx)
exchange_versions[version_key] = exchange_versions.get(version_key, 0) + 1
best_price = fetch_best_price(exch, side_idx)
if best_price is not None:
heap_priority = -best_price if side_idx == 0 else best_price
heapq.heappush(global_best_heaps[side_idx], (heap_priority, exch, exchange_versions[version_key]))
def query_global_best(side_idx):
candidate_heap = global_best_heaps[side_idx]
while candidate_heap:
heap_priority, exch, stored_version = candidate_heap[0]
current_version = exchange_versions.get((exch, side_idx))
if current_version != stored_version:
heapq.heappop(candidate_heap)
continue
actual_best = fetch_best_price(exch, side_idx)
expected_priority = None if actual_best is None else (-actual_best if side_idx == 0 else actual_best)
if expected_priority != heap_priority:
heapq.heappop(candidate_heap)
continue
return actual_best
return None
for op, args in zip(operations, arguments):
if op == "add":
exch, price, qty, side = args
side_idx = 0 if side == "bid" else 1
if exch not in exchange_books:
exchange_books[exch] = [({}, []), ({}, [])]
level_quantities, price_heap = exchange_books[exch][side_idx]
prev_best = fetch_best_price(exch, side_idx)
updated_qty = level_quantities.get(price, 0) + qty
if updated_qty < 0:
raise ValueError("quantity cannot become negative")
if updated_qty == 0:
level_quantities.pop(price, None)
else:
if price not in level_quantities:
heapq.heappush(price_heap, -price if side_idx == 0 else price)
level_quantities[price] = updated_qty
prune_stale_levels(exch, side_idx)
current_best = fetch_best_price(exch, side_idx)
if current_best != prev_best:
push_to_global(exch, side_idx)
output.append(None)
elif op == "get_exchange_bbo":
exch = args[0]
output.append([fetch_best_price(exch, 0), fetch_best_price(exch, 1)])
elif op == "get_nbbo":
output.append([query_global_best(0), query_global_best(1)])
else:
raise ValueError("unknown operation")
return output