Trade-by-Trade Realized P&L Engine With FIFO Matching

Coding · Hard · Free problem
You are building a real-time P&L engine for a trading desk. A stream of $m$ timestamped trades arrives, each represented as a pair $(p_j, q_j)$ where $p_j$ is the execution price and $q_j$ is the signed quantity ($q_j > 0$ for buys, $q_j < 0$ for sells). Your engine must process the stream in a single pass using $O(m)$ time and $O(1)$ extra space (beyond the inventory queue), and return three things: 1. **Realized P&L** -- computed using FIFO (first-in, first-out) inventory matching. When a trade offsets an existing position, match it against the oldest inventory lot first. 2. **Ending inventory and average cost** -- the remaining open position after all trades, along with its weighted-average cost basis. 3. **Maximum drawdown of cumulative realized P&L** -- the largest peak-to-trough decline in the running realized P&L over the trade sequence. Your implementation must handle the following edge cases: - **Partial fills**: a single trade may only partially offset the oldest lot, leaving a residual. - **Zero-quantity records**: trades with $q_j = 0$ (no-ops that should be skipped). - **Fees**: each trade may carry an optional fee that reduces realized P&L. - **NaN prices or quantities**: invalid records that should be skipped with a warning. **Constraints:** -
\le m \le 10^6$ - Prices and quantities are floating-point numbers. - Fees are non-negative floats (default 0). **Example:** Input trades: `[(100, +10), (102, +5), (105, -8), (103, -4), (101, +3)]` Using FIFO matching: - Sell 8 at 105: matched against the first lot (bought 10 at 100). Realized P&L on 8 units = $8 \times (105 - 100) = +40$. Remaining from lot 1: 2 units at 100. - Sell 4 at 103: matched against remaining 2 from lot 1 at 100, then 2 from lot 2 at 102. Realized P&L =
\times (103 - 100) + 2 \times (103 - 102) = 6 + 2 = +8$. - Final realized P&L: $+48$. - Ending inventory: 3 units from lot 2 at 102, plus 3 units from the new buy at 101. Total 6 long, average cost $(3 \times 102 + 3 \times 101)/6 = 101.5$. - Cumulative realized P&L series: $[0, 0, +40, +48, +48]$. Peak = 48, no drawdown occurs, so max drawdown = 0.

Open the full interactive solver, hints, and worked solution →