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:

  1. Initialization: ArbitrageEngine(quote_ttl_ms) sets the maximum age (in milliseconds) for a quote to remain tradable, raising ValueError if quote_ttl_ms < 0.
  2. Quote Validation: Reject quote immediately (returning None without modifying any stored book or advancing the clock) if:
    • bid_size < 0 or ask_size < 0;
    • an active side (size > 0) has a non-finite or non-positive price (price <= 0, inf, or NaN); or
    • both sides are active (bid_size > 0 and ask_size > 0) and bid_price > ask_price on that single venue (a crossed book). A locked single-venue book (bid_price == ask_price) is valid, and any side with size == 0 is inactive so its price field is ignored.
  3. 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 return None. Otherwise, store quote as that venue's current top-of-book for quote.instrument and update the engine's global clock now_ms to the largest timestamp_ms seen across all accepted quotes (across all instruments).
  4. Freshness Window: A stored quote is fresh while now_ms - quote.timestamp_ms <= quote_ttl_ms.
  5. Best Cross-Venue Opportunity: After accepting quote, evaluate all pairs of distinct fresh venues (buy_venue, sell_venue) for quote.instrument where buy_venue has ask_size > 0, sell_venue has bid_size > 0, and sell_price > buy_price. For each valid pair:
    • buy_price is buy_venue's ask_price and sell_price is sell_venue's bid_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 largest profit, breaking ties by largest quantity, and then by lexicographically smallest (buy_venue, sell_venue). Return None if 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_ms is an integer; raise ValueError when quote_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 0 marks that side inactive.
  • Timestamps (timestamp_ms) are integers representing milliseconds; timestamps from distinct venues or instruments may arrive slightly interleaved, and now_ms never decreases.
  • Quotes for different instrument strings never trade against each other, though all accepted quotes share the single now_ms clock.
  • 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

  1. Understand bid, ask, and cross-venue arbitrage

    Each incoming Quote is 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_price and bid_size: the highest price someone on that exchange is willing to buy at. That means we can sell up to bid_size shares to them at bid_price.
    • ask_price and ask_size: the lowest price someone on that exchange is willing to sell at. That means we can buy up to ask_size shares from them at ask_price.

    On any healthy single exchange, bid_price <= ask_price. Across two different exchanges, however, exchange Y's buyers may bid higher than exchange X'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.00
    

    Before writing code, pin down the exact rules from the specification: 1. Validation: reject a quote (returning None and 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 and bid_price > ask_price (crossed single-venue book). A side with size == 0 is 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). Update now_ms to the maximum timestamp_ms across all accepted quotes; a quote is fresh while now_ms - timestamp_ms <= quote_ttl_ms. 3. Ranking: among fresh quotes for that instrument on distinct venues (buy_venue != sell_venue), pick the pair with sell_price > buy_price that maximizes total profit, breaking ties by largest quantity, then alphabetically smallest (buy_venue, sell_venue).

  2. Why comparing only the global best bid and best ask fails

    A tempting shortcut is to grab the single lowest ask_price across all exchanges and pair it with the single highest bid_price across 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. With V venues (say V = 50), V * (V - 1) = 2,450 integer comparisons takes well under a millisecond in Python.

  3. Convert prices to integer cents and validate incoming quotes

    Binary floating-point numbers cannot represent 0.10 or 0.05 exactly: in Python, (84.10 - 84.05) * 60 evaluates to 2.9999999999998295 instead of 3.0. Because every valid price has at most 2 decimal places, round(price * 100) converts dollars into exact integer cents (8410 - 8405 = 5 cents; 5 * 60 = 300 cents = 3.0 dollars).

    In is_positive_finite_price, checking math.isfinite(price) and price > 0 rejects 0.0, negative numbers, inf, and NaN (NaN makes every < or > comparison False, so a naive bid > ask check without isfinite would let NaN slip 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 True
    
  4. Partition 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.books as a nested dictionary instrument -> {venue -> Quote} so NVDA and MSFT never mix, while self.now_ms tracks the single global engine clock across all accepted quotes.

    process_quote executes 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_ms uses max rather than self.now_ms = quote.timestamp_ms: feeds from two exchanges can arrive slightly interleaved (say t = 2080 from ARCA, followed by t = 2065 from IEX), and reference time must never run backward.

  5. 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 while self.now_ms - venue_quote.timestamp_ms <= self.quote_ttl_ms (a quote 250 ms old with quote_ttl_ms = 250 is still fresh; at 251 ms it is skipped).

    Iterating venues in sorted(venue_quotes) order and updating best_rank = (total_profit_cents, quantity) only on strict > handles all three ranking levels cleanly: 1. Larger total_profit_cents wins first; 2. On equal profit, larger quantity wins 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_opp
    
  6. Trace 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)
    
  7. 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), where V is the number of venues tracked for that single instrument. Validating the incoming quote and updating the nested dictionary take O(1) average time; sorting the V venue names for deterministic tie-breaking takes O(V log V); and checking every ordered (buy_venue, sell_venue) pair among at most V fresh quotes examines V * (V - 1) pairs in O(V^2). Because stocks trade on a modest number of venues (for 50 venues, 50 * 49 = 2,450 integer operations), each update finishes in microseconds.
  • Space complexity: O(I * V) (more precisely, O(number of distinct (instrument, venue) pairs seen)), because self.books stores only the single latest accepted Quote per (instrument, venue) and _get_fresh_quotes builds a temporary list of at most V references.

Edge cases

  • Single fresh venue (or all other venues expired): no distinct (buy_venue, sell_venue) pair exists, so _find_best_opportunity returns None (a venue can never trade against itself).
  • Zero-profit touch across venues (sell_bid == buy_ask): spread_cents == 0 earns $0.00 and is skipped; arbitrage requires spread_cents > 0.
  • Locked single-venue book (bid_price == ask_price on the same venue): accepted as valid—only bid_price > ask_price on a single venue is rejected as crossed.
  • Inactive side (bid_size == 0 or ask_size == 0): a size-0 side cannot be traded and its placeholder price is skipped during validation (a venue quoting only an ask can carry 0.0 or stale numbers in bid_price without being rejected).
  • Exact TTL boundary (now_ms - timestamp_ms == quote_ttl_ms): still fresh (<=); quote_ttl_ms == 0 accepts only quotes stamped at the exact current now_ms.
  • Interleaved timestamps across instruments/venues: self.now_ms advances via max(...) across all instruments, so an MSFT tick at t = 2350 advances now_ms to 2350 and properly ages NVDA quotes from t = 2000.
  • Rejected or out-of-order quotes: return None immediately before modifying self.books or self.now_ms, preventing one corrupt timestamp like t = 999999 from expiring every good quote.

Common mistakes

  • Computing profit directly in IEEE-754 floats: (84.10 - 84.05) * 60 evaluates to 2.9999999999998295; converting 2-decimal prices to integer cents via round(price * 100) keeps every subtraction and multiplication exact.
  • Swapping bid and ask directions: remember that an exchange's ask is their selling offer (you buy at buy_quote.ask_price), and their bid is their buying offer (you sell at sell_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.00 beating $1.00 * 1 = $1.00).
  • Using max instead of min for trade quantity: you cannot execute more shares than the smaller of buy_quote.ask_size and sell_quote.bid_size.
  • Forgetting NaN in price validation: float("nan") > ask_price evaluates to False, so checking bid > ask without math.isfinite(price) and price > 0 lets NaN prices enter the book.
  • Setting self.now_ms = quote.timestamp_ms unconditionally: 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 on ARCA and only sell 35 on NYSE, 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 in O(log n)—pushing (price_cents, venue, seq_no) on every accepted update alongside a per-venue latest_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 while seq_no != latest_seq[venue], that side's current size is 0, or now_ms - timestamp_ms > quote_ttl_ms. Because now_ms and seq_no only 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 whenever len(heap) > 2 * V bounds memory to O(V). Note that heaps find the widest price spread in O(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) for O(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/100 of 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, a 1.00-cent gross spread with +0.30-cent taker fees on both legs leaves 0.40 cents/share ($0.40 on 100 shares), whereas +0.30 cents on the buy leg and a -0.10-cent rebate on an inverted sell leg leaves 0.80 cents/share ($0.80)—and any pair with net_edge_units <= 0 is 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

Similar questions

More Jane Street interview questions

All 47 Jane Street questions →