Cross-Venue Quote Book and Arbitrage Scanner
Data Structure DesignModel answerLast updated
Build an in-memory engine that keeps the latest valid top-of-book quote per venue, expires old ones, and reports the most profitable buy-low/sell-high pair across venues.
Context
The same stock can be quoted on several trading venues at once. Each venue publishes its top of book: the best bid (what buyers will pay) and the best ask (what sellers want), each with a size. If one venue's bid is strictly higher than a different venue's ask for the same instrument, you can buy on the cheap venue and sell on the expensive one for a risk-free gain.
Task
Implement an ArbitrageEngine that consumes a stream of quotes one at a time and, after each one, reports the best immediately available cross-venue opportunity, if there is one.
from dataclasses import dataclass
from typing import Optional
@dataclass
class Quote:
venue: str
instrument: str
bid_price: float
bid_size: int
ask_price: float
ask_size: int
timestamp_ms: int
@dataclass
class ArbitrageOpportunity:
instrument: str
buy_venue: str
sell_venue: str
buy_price: float
sell_price: float
quantity: int
profit: float
class ArbitrageEngine:
def __init__(self, quote_ttl_ms: int): ...
def process_quote(self, quote: Quote) -> Optional[ArbitrageOpportunity]: ...
process_quote must:
- Validate the quote. A quote whose own bid is higher than its own ask is a corrupted feed and is rejected.
- Store it as that venue's latest quote for that instrument.
- Expire quotes that are too old, according to
quote_ttl_ms. - Return the opportunity with the highest total profit among the remaining fresh quotes, or
None.
Rules
- Prices are positive and have two decimal places.
- Sizes are non-negative integers. A size of 0 means that side is inactive and cannot trade.
- Timestamps never decrease for a given venue, but different venues may interleave slightly. The engine's current time is the largest timestamp it has accepted.
- A quote is stale when
current_time - quote.timestamp_ms > quote_ttl_ms. - Buying and selling on the same venue is not allowed.
- Quantity is
min(buy venue ask size, sell venue bid size), and profit is(sell price - buy price) * quantity. - Among candidate pairs, choose the largest total profit. If profits tie, choose the larger quantity.
Examples
engine = ArbitrageEngine(quote_ttl_ms=500)
engine.process_quote(Quote("EXCH_A", "AAPL", 150.10, 100, 150.20, 50, 1000))
# -> None (only one venue)
engine.process_quote(Quote("EXCH_B", "AAPL", 149.90, 80, 150.05, 40, 1050))
# -> ArbitrageOpportunity("AAPL", buy_venue="EXCH_B", sell_venue="EXCH_A",
# buy_price=150.05, sell_price=150.10,
# quantity=40, profit=2.00)
engine.process_quote(Quote("EXCH_C", "AAPL", 151.00, 50, 149.00, 50, 1100))
# -> None (this venue's own bid is above its own ask, so it is rejected)
engine.process_quote(Quote("EXCH_B", "AAPL", 149.00, 10, 150.00, 10, 1600))
# -> None (EXCH_A's quote is 600 ms old, beyond the 500 ms TTL)
What to cover
Explain your data model, the time and staleness conventions, how you validate input, how you compare prices safely, and the complexity. Then give the code.
Hints
Hint 1
Group state by instrument, then by venue, so each (instrument, venue) holds only the newest valid quote. Everything else can be derived from that.
Hint 2
Decide the rules up front: what counts as the current time, whether an age exactly equal to the TTL is stale, and whether a rejected quote may change any state.
Hint 3
Do not just pair the best bid with the best ask. The most profitable pair depends on sizes too, so try every ordered pair of distinct venues. Compare prices as integer cents to avoid float noise like 150.10 - 150.05.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What this question is really about
There is no clever algorithm here. It tests state modeling, explicit conventions, and edge-case discipline. I would state my decisions before writing code.
Decisions to state first
- Current time is the maximum timestamp among accepted quotes. It never goes backwards.
- Stale means
now - ts > ttl. An age of exactly the TTL is still fresh. - Invalid quotes are dropped completely. They do not replace the venue's previous quote and do not advance the clock, since a corrupted message's timestamp is not trustworthy either. The alternative, treating a bad quote as "this venue pulled its liquidity", is defensible, but I would name it as a choice.
- Inactive sides (size 0) cannot trade. The crossed-book check only applies when both sides are active. A locked book (
bid == ask) is legal. - An arbitrage needs a strictly positive edge: the sell venue's bid is greater than the buy venue's ask, on two different venues.
- Detection does not consume liquidity. Reporting an opportunity does not reduce the displayed sizes.
Data model
books[instrument][venue] -> latest valid Quote
Each update overwrites one slot. This is O(1) to update and keeps memory at one quote per (instrument, venue).
Algorithm per quote
- Validate. Reject negative sizes, non-finite prices, non-positive prices on an active side, and a crossed book when both sides are active.
- Ignore the quote if it is older than the one already stored for that venue. The spec says this should not happen, but it is a cheap guard.
- Store it and set
now = max(now, ts). - Remove quotes for this instrument whose age exceeds the TTL. Since
nownever decreases, a stale quote stays stale, so deleting it loses nothing. Other instruments are pruned lazily when they next receive a quote. - For every ordered pair
(buy, sell)of different venues with both relevant sides active, compute the edge in cents. If the edge is positive, setqty = min(buy.ask_size, sell.bid_size)andprofit = edge * qty. - Keep the best pair by
(profit, qty). As an extra deterministic tie-break, prefer the smaller(buy_venue, sell_venue)names.
Why check all pairs
Maximizing total profit is not the same as maximizing per-share edge. The best bid may show 1 share while the next bid, one cent lower, shows 1,000. Size matters, so the "best bid versus best ask" shortcut can give the wrong answer. With V venues the scan is V² pairs, and V is small in practice (tens at most), so this is cheap.
Floating-point handling
150.10 - 150.05 is not exactly 0.05 in binary floating point. Convert prices to integer cents with round(p * 100) and compare in integers. Ties and strict inequalities then become exact. Convert back only for the final profit, using edge_cents * qty / 100, rounded to 2 decimals.
Complexity
- Time per quote: O(V) for pruning plus O(V²) for pair evaluation, where V is the number of venues quoting that instrument.
- Space: O(I · V).
If V grew large, you could keep the top-k bids and asks per instrument in heaps with lazy deletion. That is overkill for dozens of venues but is a natural follow-up.
Code
import math
from dataclasses import dataclass
from typing import Dict, Optional
@dataclass
class Quote:
venue: str
instrument: str
bid_price: float
bid_size: int
ask_price: float
ask_size: int
timestamp_ms: int
@dataclass
class ArbitrageOpportunity:
instrument: str
buy_venue: str
sell_venue: str
buy_price: float
sell_price: float
quantity: int
profit: float
def _cents(price: float) -> int:
return int(round(price * 100))
class ArbitrageEngine:
def __init__(self, quote_ttl_ms: int):
self.ttl = quote_ttl_ms
self.now: Optional[int] = None
self.books: Dict[str, Dict[str, Quote]] = {}
@staticmethod
def _valid(q: Quote) -> bool:
if q.bid_size < 0 or q.ask_size < 0:
return False
bid_on, ask_on = q.bid_size > 0, q.ask_size > 0
if bid_on and not (math.isfinite(q.bid_price) and q.bid_price > 0):
return False
if ask_on and not (math.isfinite(q.ask_price) and q.ask_price > 0):
return False
if bid_on and ask_on and _cents(q.bid_price) > _cents(q.ask_price):
return False
return True
def process_quote(self, quote: Quote) -> Optional[ArbitrageOpportunity]:
if not self._valid(quote):
return None
book = self.books.setdefault(quote.instrument, {})
prev = book.get(quote.venue)
if prev is not None and quote.timestamp_ms < prev.timestamp_ms:
return None
book[quote.venue] = quote
ts = quote.timestamp_ms
self.now = ts if self.now is None else max(self.now, ts)
for v in [v for v, q in book.items() if self.now - q.timestamp_ms > self.ttl]:
del book[v]
best_key, best = None, None
quotes = list(book.values())
for buy in quotes:
if buy.ask_size <= 0:
continue
ask_c = _cents(buy.ask_price)
for sell in quotes:
if sell.venue == buy.venue or sell.bid_size <= 0:
continue
edge = _cents(sell.bid_price) - ask_c
if edge <= 0:
continue
qty = min(buy.ask_size, sell.bid_size)
profit_c = edge * qty
key = (profit_c, qty, tuple(-ord(c) for c in buy.venue + "|" + sell.venue))
if best_key is None or key > best_key:
best_key, best = key, (buy, sell, qty, profit_c)
if best is None:
return None
buy, sell, qty, profit_c = best
return ArbitrageOpportunity(
instrument=quote.instrument,
buy_venue=buy.venue,
sell_venue=sell.venue,
buy_price=buy.ask_price,
sell_price=sell.bid_price,
quantity=qty,
profit=round(profit_c / 100, 2),
)
Walkthrough
- Example 1: After the second quote, the clock is 1050 and both venues are fresh. Buying on EXCH_B at 150.05 and selling on EXCH_A at 150.10 gives a 5-cent edge. The quantity is
min(40, 100) = 40, so profit is 200 cents, or 2.00. The reverse direction has a negative edge. - Example 2: The crossed EXCH_C quote is rejected and nothing changes. The next EXCH_B quote moves the clock to 1600, so EXCH_A (age 600 > 500) is pruned. Only one venue remains, so the result is
None.
Edge cases and common mistakes
- Using
>=instead of>for staleness, which wrongly drops a quote at exactly the TTL. - Letting a rejected quote advance the clock or overwrite good state.
- Rejecting a quote that has one inactive side because its zero price looks "crossed".
- Comparing raw floats, which makes ties and strict inequalities unreliable.
- Pairing a venue with itself.
- Checking only the single best bid and best ask, which misses larger-size pairs.
- Forgetting that a quote arriving already stale is stored and then immediately pruned.