Every trading simulation tracks three numbers: your position (shares held; negative is short), your cash, and your PnL (profit and loss). Strategies and backtests are built on this bookkeeping.
Implement mark_to_market(fills, last_price) -> (position, cash, pnl). You start flat. fills are (side, qty, price) tuples in order:
- A buy adds
qtyto the position and paysqty * pricefrom cash; a sell does the opposite. Going short and negative cash are allowed. pnl = cash + position * last_price.
fills = [("buy", 10, 100), ("buy", 5, 102), ("sell", 8, 105)]
mark_to_market(fills, 104)
# position = 10 + 5 - 8 = 7
# cash = -1000 - 510 + 840 = -670
# pnl = -670 + 7 * 104 = 58
# -> (7, -670, 58)
mark_to_market([("sell", 3, 50)], 45) # (-3, 150, 15): a short gains when the price falls
Up to 10^5 fills; quantities and prices are integers in 1..10^6. Stay in integers: money in floats picks up rounding errors.
Show hint
two running totals with the sign set by the side, then value what's left at the last price.