Welcome to the settlement team. The engine applies a batch of trade fills into per-symbol positions and realized profit and loss. Each fill has trade_id, symbol, side ("buy"/"sell"), quantity, and price_cents. Money is i…
Welcome to the settlement team. The engine applies a batch of trade fills into per-symbol positions and realized profit and loss. Each fill has trade_id, symbol, side ("buy"/"sell"), quantity, and price_cents. Money is integer cents.
There are two tickets below. Fix as many as you can in 35 minutes. Each ticket is checked separately, and you are not expected to finish every one.
trade_id is unique: a resent fill is applied exactly once.Two correctness problems in settlement. Resent fills (same trade_id) are applied twice, inflating positions. And realized PnL on a sell uses the most recent purchase price instead of the weighted average cost, so PnL does not match a hand calculation after staggered buys.
trade_id leaves the position as if applied once.(sell_price - avg_cost) * qty, where avg_cost is the weighted average over the held quantity.Do not change the validation rules as part of this ticket.
Selling more than is held drives the position negative (and divides by zero at a zero quantity), and a fill missing a field or carrying a non-positive quantity or price fails deep in the code with an unclear error.
SettlementError; the position is unchanged.SettlementError.Do not change the PnL calculation as part of this ticket.
models.py (Position and the SettlementError type) and settlement.py (Blotter with apply, and settle for a batch). The shipped regression tests are in tests/visible/; every one of them fails until the bugs are fixed.pytest tests/visible.Adapted from treasure567/bloomberg-practice (round-1/marlin @ 8de07d5), used with the author's permission.
Visible test command
pytest tests/visibleThe repository’s own tests. Run all tests includes them, and so does every submission.
Repository
trade-settlement-duplicate-fills-and-oversells
Changes under src/ are evaluated.