progress

~/problems / Order books / Market and strategy simulations

Position, cash and PnL from fills

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

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 qty to the position and pays qty * price from 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.

Topic: Market and strategy simulations. Execution, backtests, allocation rules: careful state and event ordering.

0:00
Ctrl ' run · Ctrl ↵ submit
esc