Cross-Venue Top-of-Book Quote Aggregator and Arbitrage Detector
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Identical equities often trade across several independent exchanges at the same time. Each exchange publishes a top-of-book quote for an instrument: its highest buying price (bid_price for bid_size shares) and lowest selling price (ask_price for ask_size shares). Whenever one exchange bids strictly more than a different exchange asks (sell_bid > buy_ask), a trader can buy shares at the cheaper ask and sell them into the higher bid for an immediate gross profit.
Implement an in-memory quote book and cross-venue arbitrage detector using the interface below:
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]:
...
Your implementation must enforce these rules:
- Initialization:
ArbitrageEngine(quote_ttl_ms)sets the maximum age (in milliseconds) for a quote to remain tradable, raisingValueErrorifquote_ttl_ms < 0. - Quote Validation: Reject
quoteimmediately (returningNonewithout modifying any stored book or advancing the clock) if:bid_size < 0orask_size < 0;- an active side (
size > 0) has a non-finite or non-positive price (price <= 0,inf, orNaN); or - both sides are active (
bid_size > 0andask_size > 0) andbid_price > ask_priceon that single venue (a crossed book). A locked single-venue book (bid_price == ask_price) is valid, and any side withsize == 0is inactive so its price field is ignored.
- Per-Venue Ordering & Reference Clock: If the engine already holds an accepted quote for
(quote.instrument, quote.venue)with a newer timestamp (quote.timestamp_ms < stored.timestamp_ms), ignore the late arrival and returnNone. Otherwise, storequoteas that venue's current top-of-book forquote.instrumentand update the engine's global clocknow_msto the largesttimestamp_msseen across all accepted quotes (across all instruments). - Freshness Window: A stored quote is fresh while
now_ms - quote.timestamp_ms <= quote_ttl_ms. - Best Cross-Venue Opportunity: After accepting
quote, evaluate all pairs of distinct fresh venues(buy_venue, sell_venue)forquote.instrumentwherebuy_venuehasask_size > 0,sell_venuehasbid_size > 0, andsell_price > buy_price. For each valid pair:buy_priceisbuy_venue'sask_priceandsell_priceissell_venue'sbid_price;quantity = min(buy_quote.ask_size, sell_quote.bid_size);profit = (sell_price - buy_price) * quantity, computed with exact cent arithmetic. Return the candidate with the largestprofit, breaking ties by largestquantity, and then by lexicographically smallest(buy_venue, sell_venue). ReturnNoneif no profitable pair exists.
Examples
Example 1
engine = ArbitrageEngine(quote_ttl_ms=250)
q1 = Quote(
venue="NYSE", instrument="NVDA",
bid_price=84.10, bid_size=120, ask_price=84.25, ask_size=75, timestamp_ms=2000,
)
assert engine.process_quote(q1) is None
q2 = Quote(
venue="ARCA", instrument="NVDA",
bid_price=83.95, bid_size=90, ask_price=84.05, ask_size=60, timestamp_ms=2080,
)
opp = engine.process_quote(q2)
# ArbitrageOpportunity(
# instrument="NVDA",
# buy_venue="ARCA",
# sell_venue="NYSE",
# buy_price=84.05,
# sell_price=84.10,
# quantity=60,
# profit=3.0,
# )
Walk-through: After q1, only "NYSE" is known for "NVDA", so no cross-venue trade is possible (None). When q2 arrives at t = 2080, "NYSE" has age 2080 - 2000 = 80 ms <= 250 ms and remains fresh. Buying "ARCA"'s ask at 84.05 (up to 60 shares) and selling into "NYSE"'s bid at 84.10 (up to 120 shares) trades min(60, 120) = 60 shares at a $0.05 spread per share, yielding $0.05 * 60 = $3.00 total profit.
Example 2
engine = ArbitrageEngine(quote_ttl_ms=250)
engine.process_quote(Quote("NYSE", "NVDA", 84.10, 120, 84.25, 75, 2000))
engine.process_quote(Quote("ARCA", "NVDA", 83.95, 90, 84.05, 60, 2080))
# Crossed single-venue quote (bid 85.00 > ask 83.50)
q3 = Quote("BATS", "NVDA", 85.00, 40, 83.50, 40, 2150)
assert engine.process_quote(q3) is None
# Clock advances to 2350; NYSE's quote from t=2000 is now 350 ms old (> 250 ms TTL)
q4 = Quote("ARCA", "NVDA", 83.90, 30, 84.00, 30, 2350)
assert engine.process_quote(q4) is None
Walk-through: q3 has bid_price = 85.00 > ask_price = 83.50 on "BATS" alone, so it is discarded without entering the book or advancing now_ms. Next, q4 updates "ARCA" and moves now_ms to 2350; "NYSE"'s quote from t = 2000 now has age 350 ms > 250 ms and expires, leaving "ARCA" as the only fresh venue (None).
Constraints
quote_ttl_msis an integer; raiseValueErrorwhenquote_ttl_ms < 0.- Valid active prices are finite positive floats expressed to at most 2 decimal places (whole cents).
- Share sizes are integers; a negative size is invalid, while a size of
0marks that side inactive. - Timestamps (
timestamp_ms) are integers representing milliseconds; timestamps from distinct venues or instruments may arrive slightly interleaved, andnow_msnever decreases. - Quotes for different
instrumentstrings never trade against each other, though all accepted quotes share the singlenow_msclock. - Buying and selling on the same venue is disallowed, and zero-spread crosses (
sell_price == buy_price) do not count as arbitrage.
Step-by-step walkthrough
Understand bid, ask, and cross-venue arbitrage
Each incoming
Quoteis a top-of-book snapshot—the single best buy price and single best sell price currently posted on one exchange (venue) for one stock (instrument):bid_priceandbid_size: the highest price someone on that exchange is willing to buy at. That means we can sell up tobid_sizeshares to them atbid_price.ask_priceandask_size: the lowest price someone on that exchange is willing to sell at. That means we can buy up toask_sizeshares from them atask_price.
On any healthy single exchange,
bid_price <= ask_price. Across two different exchanges, however, exchangeY's buyers may bid higher than exchangeX's sellers ask (Y.bid_price > X.ask_price). That price overlap is a cross-venue arbitrage:ARCA (we BUY at ask): ask_price = $84.05, ask_size = 60 shares NYSE (we SELL at bid): bid_price = $84.10, bid_size = 120 shares --------------------------------------------------------------------- Spread per share: $84.10 - $84.05 = $0.05 Executable shares: min(60, 120) = 60 shares Immediate profit: $0.05 * 60 = $3.00Before writing code, pin down the exact rules from the specification: 1. Validation: reject a quote (returning
Noneand changing zero engine state) if either size is< 0, if an active side (size > 0) has a non-positive or non-finite price, or if both sides are active andbid_price > ask_price(crossed single-venue book). A side withsize == 0is inactive, so its price is ignored. 2. Ordering & engine clock: reject a quote if it is older (<) than the quote already stored for the same(instrument, venue). Updatenow_msto the maximumtimestamp_msacross all accepted quotes; a quote is fresh whilenow_ms - timestamp_ms <= quote_ttl_ms. 3. Ranking: among fresh quotes for that instrument on distinct venues (buy_venue != sell_venue), pick the pair withsell_price > buy_pricethat maximizes total profit, breaking ties by largest quantity, then alphabetically smallest(buy_venue, sell_venue).Why comparing only the global best bid and best ask fails
A tempting shortcut is to grab the single lowest
ask_priceacross all exchanges and pair it with the single highestbid_priceacross all exchanges. That maximizes spread per share, NOT total profit (spread * min(ask_size, bid_size)).Look at four fresh venues for
NVDA:Venue Bid (price x size) Ask (price x size) ----------------------------------------------- A 101.00 x 1 102.00 x 10 B 99.00 x 10 100.00 x 1 C 100.50 x 100 101.50 x 10 D 99.50 x 10 100.20 x 100 Global lowest ask (B @ 100.00) -> highest bid (A @ 101.00): spread = $1.00, qty = min(1, 1) = 1 -> total profit = $1.00 Buy D @ 100.20 -> Sell C @ 100.50: spread = $0.30, qty = min(100, 100) = 100 -> total profit = $30.00 (30x higher!)Because share sizes vary across venues, we check every ordered
(buy_venue, sell_venue)pair among fresh quotes for that instrument. WithVvenues (sayV = 50),V * (V - 1) = 2,450integer comparisons takes well under a millisecond in Python.Convert prices to integer cents and validate incoming quotes
Binary floating-point numbers cannot represent
0.10or0.05exactly: in Python,(84.10 - 84.05) * 60evaluates to2.9999999999998295instead of3.0. Because every valid price has at most 2 decimal places,round(price * 100)converts dollars into exact integer cents (8410 - 8405 = 5cents;5 * 60 = 300cents =3.0dollars).In
is_positive_finite_price, checkingmath.isfinite(price) and price > 0rejects0.0, negative numbers,inf, andNaN(NaNmakes every<or>comparisonFalse, so a naivebid > askcheck withoutisfinitewould letNaNslip through!).import math def price_to_cents(price: float) -> int: """Convert a 2-decimal dollar float to exact integer cents to avoid float drift.""" # Example: (84.10 - 84.05) * 60 is 2.9999999999998295 in floats, vs 300 cents exact. return round(price * 100) def is_positive_finite_price(price: float) -> bool: """Return True only for finite positive numbers (rejects <= 0, inf, and NaN).""" # NaN > 0 evaluates to False, and math.isfinite(inf) evaluates to False. return math.isfinite(price) and price > 0 def is_valid_quote(quote: Quote) -> bool: """Reject negative sizes, invalid active prices, and crossed single-venue books.""" if quote.bid_size < 0 or quote.ask_size < 0: return False # A side with size == 0 is inactive, so its placeholder price is ignored. bid_active = quote.bid_size > 0 ask_active = quote.ask_size > 0 if bid_active and not is_positive_finite_price(quote.bid_price): return False if ask_active and not is_positive_finite_price(quote.ask_price): return False # Reject crossed single-venue books (bid > ask); locked books (bid == ask) are valid. if bid_active and ask_active: if price_to_cents(quote.bid_price) > price_to_cents(quote.ask_price): return False return TruePartition state by instrument and advance the monotonic clock
Each venue's newest top-of-book quote completely replaces its previous quote for that stock. We store
self.booksas a nested dictionaryinstrument -> {venue -> Quote}soNVDAandMSFTnever mix, whileself.now_mstracks the single global engine clock across all accepted quotes.process_quoteexecutes four phases in strict order so bad or late packets never corrupt state:class ArbitrageEngine: def __init__(self, quote_ttl_ms: int): if quote_ttl_ms < 0: raise ValueError("quote_ttl_ms must be >= 0") self.quote_ttl_ms = quote_ttl_ms # now_ms: largest timestamp_ms seen across all accepted quotes (never moves backward) self.now_ms: Optional[int] = None # books: {"NVDA": {"NYSE": Quote(...), "ARCA": Quote(...)}} self.books: Dict[str, Dict[str, Quote]] = {} def process_quote(self, quote: Quote) -> Optional[ArbitrageOpportunity]: # Phase 1: Reject corrupt quotes before touching stored state or the engine clock. if not is_valid_quote(quote): return None if quote.instrument not in self.books: self.books[quote.instrument] = {} venue_quotes = self.books[quote.instrument] # Phase 2: Ignore out-of-order messages older than this venue's latest stored quote. previous_quote = venue_quotes.get(quote.venue) if previous_quote is not None and quote.timestamp_ms < previous_quote.timestamp_ms: return None # Phase 3: Save the new top-of-book quote and advance the global reference clock. venue_quotes[quote.venue] = quote if self.now_ms is None or quote.timestamp_ms > self.now_ms: self.now_ms = quote.timestamp_ms # Phase 4: Search fresh venues of this instrument for the most profitable arb. return self._find_best_opportunity(quote.instrument)Notice why
self.now_msusesmaxrather thanself.now_ms = quote.timestamp_ms: feeds from two exchanges can arrive slightly interleaved (sayt = 2080fromARCA, followed byt = 2065fromIEX), and reference time must never run backward.Filter expired quotes and rank every valid venue pair
A TTL (Time-To-Live) defines how long a quote stays actionable before becoming stale. In
_get_fresh_quotes, a quote is fresh whileself.now_ms - venue_quote.timestamp_ms <= self.quote_ttl_ms(a quote250 msold withquote_ttl_ms = 250is still fresh; at251 msit is skipped).Iterating venues in
sorted(venue_quotes)order and updatingbest_rank = (total_profit_cents, quantity)only on strict>handles all three ranking levels cleanly: 1. Largertotal_profit_centswins first; 2. On equal profit, largerquantitywins second; 3. On exact ties, keeping the first pair visited picks the alphabetically smallest(buy_venue, sell_venue).def _get_fresh_quotes(self, instrument: str) -> List[Quote]: """Return non-expired quotes for one instrument, ordered by venue name.""" venue_quotes = self.books[instrument] fresh: List[Quote] = [] # Sorting venue names makes tie-breaking deterministic without extra tuple strings. for venue_name in sorted(venue_quotes): venue_quote = venue_quotes[venue_name] age_ms = self.now_ms - venue_quote.timestamp_ms # Inclusive '<=': a quote whose age equals quote_ttl_ms has not expired yet. if age_ms <= self.quote_ttl_ms: fresh.append(venue_quote) return fresh def _find_best_opportunity(self, instrument: str) -> Optional[ArbitrageOpportunity]: """Check every ordered (buy_venue, sell_venue) pair to maximize total profit.""" fresh = self._get_fresh_quotes(instrument) best_opp: Optional[ArbitrageOpportunity] = None # best_rank stores (total_profit_cents, quantity) for exact integer comparison. best_rank = None # We BUY from buy_quote at its ask_price (the price that venue offers to sell at). for buy_quote in fresh: if buy_quote.ask_size == 0: continue buy_cents = price_to_cents(buy_quote.ask_price) # We SELL to sell_quote at its bid_price (the price that venue offers to buy at). for sell_quote in fresh: if sell_quote.venue == buy_quote.venue or sell_quote.bid_size == 0: continue sell_cents = price_to_cents(sell_quote.bid_price) spread_cents = sell_cents - buy_cents # Arbitrage requires strictly positive profit (sell_price > buy_price). if spread_cents <= 0: continue # Executable volume is bottlenecked by whichever side offers fewer shares. quantity = min(buy_quote.ask_size, sell_quote.bid_size) total_profit_cents = spread_cents * quantity candidate_rank = (total_profit_cents, quantity) # Strict '>' keeps the alphabetically earliest venue pair on exact ties. if best_rank is None or candidate_rank > best_rank: best_rank = candidate_rank best_opp = ArbitrageOpportunity( instrument=instrument, buy_venue=buy_quote.venue, sell_venue=sell_quote.venue, buy_price=buy_quote.ask_price, sell_price=sell_quote.bid_price, quantity=quantity, profit=total_profit_cents / 100, ) return best_oppTrace Examples 1 and 2 step by step
With
quote_ttl_ms = 250, follow all four quotes from Examples 1 and 2:Step Incoming quote now_ms Fresh NVDA venues Result --------------------------------------------------------------------------------------------------------- q1 NYSE bid 84.10x120, ask 84.25x75, t=2000 2000 [NYSE (age 0)] None (need >= 2 venues) q2 ARCA bid 83.95x90, ask 84.05x60, t=2080 2080 [ARCA (0), NYSE (80)] - buy ARCA (8405c), sell NYSE (8410c): spread = +5c, qty = min(60, 120) = 60 - buy NYSE (8425c), sell ARCA (8395c): spread = -30c <= 0 -> skip Buy ARCA @ 84.05, Sell NYSE @ 84.10, qty=60, profit=3.00 q3 BATS bid 85.00x40 > ask 83.50x40, t=2150 2080 (unchanged: rejected!) None q4 ARCA bid 83.90x30, ask 84.00x30, t=2350 2350 NYSE age 350 > 250 -> expired [ARCA (age 0)] None (only 1 fresh venue)Complete solution
from typing import Dict, List, Optional from dataclasses import dataclass import math @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 price_to_cents(price: float) -> int: """Convert a 2-decimal dollar float to exact integer cents to avoid float drift.""" # Example: (84.10 - 84.05) * 60 is 2.9999999999998295 in floats, vs 300 cents exact. return round(price * 100) def is_positive_finite_price(price: float) -> bool: """Return True only for finite positive numbers (rejects <= 0, inf, and NaN).""" # NaN > 0 evaluates to False, and math.isfinite(inf) evaluates to False. return math.isfinite(price) and price > 0 def is_valid_quote(quote: Quote) -> bool: """Reject negative sizes, invalid active prices, and crossed single-venue books.""" if quote.bid_size < 0 or quote.ask_size < 0: return False # A side with size == 0 is inactive, so its placeholder price is ignored. bid_active = quote.bid_size > 0 ask_active = quote.ask_size > 0 if bid_active and not is_positive_finite_price(quote.bid_price): return False if ask_active and not is_positive_finite_price(quote.ask_price): return False # Reject crossed single-venue books (bid > ask); locked books (bid == ask) are valid. if bid_active and ask_active: if price_to_cents(quote.bid_price) > price_to_cents(quote.ask_price): return False return True class ArbitrageEngine: def __init__(self, quote_ttl_ms: int): if quote_ttl_ms < 0: raise ValueError("quote_ttl_ms must be >= 0") self.quote_ttl_ms = quote_ttl_ms # now_ms: largest timestamp_ms seen across all accepted quotes (never moves backward) self.now_ms: Optional[int] = None # books: {"NVDA": {"NYSE": Quote(...), "ARCA": Quote(...)}} self.books: Dict[str, Dict[str, Quote]] = {} def process_quote(self, quote: Quote) -> Optional[ArbitrageOpportunity]: # Phase 1: Reject corrupt quotes before touching stored state or the engine clock. if not is_valid_quote(quote): return None if quote.instrument not in self.books: self.books[quote.instrument] = {} venue_quotes = self.books[quote.instrument] # Phase 2: Ignore out-of-order messages older than this venue's latest stored quote. previous_quote = venue_quotes.get(quote.venue) if previous_quote is not None and quote.timestamp_ms < previous_quote.timestamp_ms: return None # Phase 3: Save the new top-of-book quote and advance the global reference clock. venue_quotes[quote.venue] = quote if self.now_ms is None or quote.timestamp_ms > self.now_ms: self.now_ms = quote.timestamp_ms # Phase 4: Search fresh venues of this instrument for the most profitable arb. return self._find_best_opportunity(quote.instrument) def _get_fresh_quotes(self, instrument: str) -> List[Quote]: """Return non-expired quotes for one instrument, ordered by venue name.""" venue_quotes = self.books[instrument] fresh: List[Quote] = [] # Sorting venue names makes tie-breaking deterministic without extra tuple strings. for venue_name in sorted(venue_quotes): venue_quote = venue_quotes[venue_name] age_ms = self.now_ms - venue_quote.timestamp_ms # Inclusive '<=': a quote whose age equals quote_ttl_ms has not expired yet. if age_ms <= self.quote_ttl_ms: fresh.append(venue_quote) return fresh def _find_best_opportunity(self, instrument: str) -> Optional[ArbitrageOpportunity]: """Check every ordered (buy_venue, sell_venue) pair to maximize total profit.""" fresh = self._get_fresh_quotes(instrument) best_opp: Optional[ArbitrageOpportunity] = None # best_rank stores (total_profit_cents, quantity) for exact integer comparison. best_rank = None # We BUY from buy_quote at its ask_price (the price that venue offers to sell at). for buy_quote in fresh: if buy_quote.ask_size == 0: continue buy_cents = price_to_cents(buy_quote.ask_price) # We SELL to sell_quote at its bid_price (the price that venue offers to buy at). for sell_quote in fresh: if sell_quote.venue == buy_quote.venue or sell_quote.bid_size == 0: continue sell_cents = price_to_cents(sell_quote.bid_price) spread_cents = sell_cents - buy_cents # Arbitrage requires strictly positive profit (sell_price > buy_price). if spread_cents <= 0: continue # Executable volume is bottlenecked by whichever side offers fewer shares. quantity = min(buy_quote.ask_size, sell_quote.bid_size) total_profit_cents = spread_cents * quantity candidate_rank = (total_profit_cents, quantity) # Strict '>' keeps the alphabetically earliest venue pair on exact ties. if best_rank is None or candidate_rank > best_rank: best_rank = candidate_rank best_opp = ArbitrageOpportunity( instrument=instrument, buy_venue=buy_quote.venue, sell_venue=sell_quote.venue, buy_price=buy_quote.ask_price, sell_price=sell_quote.bid_price, quantity=quantity, profit=total_profit_cents / 100, ) return best_opp✅ Submit now — all tests should pass.
Intuition & how it works
Picture walking past several independent currency or collector stalls trading the exact same item. Each stall posts a top-of-book quote (its single best buy offer and single best sell offer right now): a bid (the highest price that stall will pay to buy from you, up to bid_size units) and an ask (the lowest price that stall will charge to sell to you, up to ask_size units). Whenever Stall B offers to sell cheaper than Stall A offers to buy (A.bid_price > B.ask_price), you can buy from Stall B and immediately sell to Stall A—that risk-free cross-stall gap is arbitrage.
Two naive shortcuts fail right away. First, simply pairing the lowest ask_price across all venues with the highest bid_price across all venues maximizes profit per share, not total dollar profit: a $1.00 gap for 1 share earns $1.00, whereas a $0.30 gap for 100 shares on another pair of venues earns $30.00. Second, subtracting prices in binary floating point ((84.10 - 84.05) * 60 == 2.9999999999998295) introduces rounding noise, and trusting every incoming packet lets corrupted crossed books (bid > ask on the same venue) or wild timestamps poison your state.
Walk through a 3-event trace with quote_ttl_ms = 250 (a TTL / Time-To-Live window specifying the maximum age in milliseconds before a quote expires):
1. NYSE posts NVDA bid = 84.10 x 120, ask = 84.25 x 75 at t = 2000 -> valid (8410 <= 8425 cents), stored under books["NVDA"]["NYSE"], now_ms = 2000; only 1 venue exists, so return None.
2. ARCA posts NVDA bid = 83.95 x 90, ask = 84.05 x 60 at t = 2080 -> valid, now_ms = 2080; both venues are fresh (2080 - 2000 = 80 <= 250). Buying ARCA's ask (8405 cents) and selling into NYSE's bid (8410 cents) yields +5 cents/share across min(60, 120) = 60 shares = 300 cents = $3.00 profit.
3. BATS posts a corrupted crossed book bid = 85.00 > ask = 83.50 at t = 2150 -> rejected up front without updating books or now_ms, returning None.
Complexity
- Time complexity per
process_quote:O(V log V + V^2), whereVis the number of venues tracked for that singleinstrument. Validating the incoming quote and updating the nested dictionary takeO(1)average time; sorting theVvenue names for deterministic tie-breaking takesO(V log V); and checking every ordered(buy_venue, sell_venue)pair among at mostVfresh quotes examinesV * (V - 1)pairs inO(V^2). Because stocks trade on a modest number of venues (for 50 venues,50 * 49 = 2,450integer operations), each update finishes in microseconds. - Space complexity:
O(I * V)(more precisely,O(number of distinct (instrument, venue) pairs seen)), becauseself.booksstores only the single latest acceptedQuoteper(instrument, venue)and_get_fresh_quotesbuilds a temporary list of at mostVreferences.
Edge cases
- Single fresh venue (or all other venues expired): no distinct
(buy_venue, sell_venue)pair exists, so_find_best_opportunityreturnsNone(a venue can never trade against itself). - Zero-profit touch across venues (
sell_bid == buy_ask):spread_cents == 0earns$0.00and is skipped; arbitrage requiresspread_cents > 0. - Locked single-venue book (
bid_price == ask_priceon the same venue): accepted as valid—onlybid_price > ask_priceon a single venue is rejected as crossed. - Inactive side (
bid_size == 0orask_size == 0): a size-0side cannot be traded and its placeholder price is skipped during validation (a venue quoting only an ask can carry0.0or stale numbers inbid_pricewithout being rejected). - Exact TTL boundary (
now_ms - timestamp_ms == quote_ttl_ms): still fresh (<=);quote_ttl_ms == 0accepts only quotes stamped at the exact currentnow_ms. - Interleaved timestamps across instruments/venues:
self.now_msadvances viamax(...)across all instruments, so anMSFTtick att = 2350advancesnow_msto2350and properly agesNVDAquotes fromt = 2000. - Rejected or out-of-order quotes: return
Noneimmediately before modifyingself.booksorself.now_ms, preventing one corrupt timestamp liket = 999999from expiring every good quote.
Common mistakes
- Computing profit directly in IEEE-754 floats:
(84.10 - 84.05) * 60evaluates to2.9999999999998295; converting 2-decimal prices to integer cents viaround(price * 100)keeps every subtraction and multiplication exact. - Swapping
bidandaskdirections: remember that an exchange'saskis their selling offer (you buy atbuy_quote.ask_price), and theirbidis their buying offer (you sell atsell_quote.bid_price). - Only checking the global min-ask and max-bid: misses higher-volume pairs that earn far more total profit (
$0.30 * 100 = $30.00beating$1.00 * 1 = $1.00). - Using
maxinstead ofminfor trade quantity: you cannot execute more shares than the smaller ofbuy_quote.ask_sizeandsell_quote.bid_size. - Forgetting
NaNin price validation:float("nan") > ask_priceevaluates toFalse, so checkingbid > askwithoutmath.isfinite(price) and price > 0letsNaNprices enter the book. - Setting
self.now_ms = quote.timestamp_msunconditionally: lets interleaved feeds rewind the clock or lets rejected corrupt quotes jump the clock forward.
Follow-up questions
- What execution safeguards would you add when one leg fills while the opposite leg misses or fills only partway, leaving unhedged inventory? Legging risk is the danger that one side of your paired trade fills while the other side misses or partially fills because another trader got there first, leaving you holding unintended directional inventory. Send both orders simultaneously as IOC (Immediate-Or-Cancel) limit orders (orders that fill whatever shares are immediately available at your limit price and cancel the rest without resting on the book), and apply a size haircut (e.g., send 70% of displayed size on venues with high cancellation rates) or fire the harder-to-fill leg first when latency differs sharply. Track each arbitrage in an execution state machine (
PENDING -> PARTIAL_LEG -> HEDGED / FLATTENED): if you buy 60 shares onARCAand only sell 35 onNYSE, immediately sweep the remaining 25 shares to the next best bid across venues (accepting a tiny slippage cost) and enforce a hard unhedged-inventory cap per instrument that pauses new arbs until exposure returns below limit. - How could you speed up cross-venue bid and ask queries from O(V) to O(log V) while keeping expired or superseded quotes from polluting priority queues? Maintain per instrument a max-heap of bids and a min-heap of asks—a heap is a binary-tree priority queue that reads the extreme element in
O(1)and inserts or pops inO(log n)—pushing(price_cents, venue, seq_no)on every accepted update alongside a per-venuelatest_seq[venue]map. Use lazy deletion (leaving outdated entries inside the heap until they bubble to the top): before reading the top of a heap, pop entries whileseq_no != latest_seq[venue], that side's current size is0, ornow_ms - timestamp_ms > quote_ttl_ms. Becausenow_msandseq_noonly increase, an invalidated heap entry can never become valid again, so each pushed quote is popped at most once (O(log V)amortized), and rebuilding a heap wheneverlen(heap) > 2 * Vbounds memory toO(V). Note that heaps find the widest price spread inO(log V); when maximizing price spread times quantity, pop only the crossing bids above the global min-ask and asks below the global max-bid (typically just 1–3 venues), evaluate pairs among those crossing quotes, and push the live ones back—or store active quotes in a balanced BST (sortedcontainers.SortedList) keyed by(price_cents, venue)forO(log V)in-place updates and ordered prefix scans. - How would per-venue maker rebates and taker fees change your net spread math and venue selection? Under maker-taker pricing, exchanges charge a taker fee to orders that remove resting liquidity immediately and pay a maker rebate to passive orders (while "inverted" venues pay a taker rebate and charge makers). Because simultaneous cross-venue arbitrage takes liquidity on both exchanges, subtract both venues' taker fees from the per-share edge using exact integer sub-cent units (such as basis-cents =
1/100of a cent, since US equity fees like$0.0030/share have 4 decimal places):net_edge_units = (sell_bid_cents - buy_ask_cents) * 100 - taker_fee_units[buy_venue] - taker_fee_units[sell_venue](where a taker rebate is negative). For example, a1.00-cent gross spread with+0.30-cent taker fees on both legs leaves0.40cents/share ($0.40on 100 shares), whereas+0.30cents on the buy leg and a-0.10-cent rebate on an inverted sell leg leaves0.80cents/share ($0.80)—and any pair withnet_edge_units <= 0is skipped even when raw prices cross!
python
def net_profit_dollars(
buy_ask_cents: int,
sell_bid_cents: int,
quantity: int,
buy_taker_fee_subcents: int,
sell_taker_fee_subcents: int,
) -> float:
"""Compute exact net profit using 1/100-cent integer units (negative fee = rebate)."""
gross_subcents = (sell_bid_cents - buy_ask_cents) * 100
net_per_share_subcents = gross_subcents - buy_taker_fee_subcents - sell_taker_fee_subcents
if net_per_share_subcents <= 0:
return 0.0
return (net_per_share_subcents * quantity) / 10_000
Follow-up questions
- What execution safeguards would you add when one leg fills while the opposite leg misses or fills only partway, leaving unhedged inventory?
- How could you speed up cross-venue bid and ask queries from O(V) to O(log V) while keeping expired or superseded quotes from polluting priority queues?
- How would per-venue maker rebates and taker fees change your net spread math and venue selection?
Similar questions
- Optimal Stopping Strategy in a Two-Player Signed-Die Game
- Four-Function Pocket Calculator State Engine
- Total Pumpkin Weight from Unlabeled Pairwise Weighings
- Productionizing a Prototype Game Engine as a Package or Service
- Comparing Single-Die vs. Paired-Dice Win Probabilities
- Stack-Based Load/Store Language Interpreter
More Jane Street interview questions
- Three-Player Fair Die Playoff Probability Medium
- Trading Gateway and Exchange Messaging Protocol Easy
- Positive-Only Integer Expression Evaluator Medium Pro
- Low-Latency Multi-Venue BBO Arbitrage Engine Medium Pro
- Probability and Strategic Game Puzzles Easy Pro
- Canonical Trade Execution Ordering Easy Pro
- Multi-Store Order Book Validation and Reconciliation Easy Pro
- Stack-Based Load/Store Language Interpreter Medium Pro
- Optimal Stopping Strategy in a Two-Player Signed-Die Game Hard Pro
- Modeling RFQ Quote Competitiveness and Information Edge Medium Pro