Repository navigation
[1.2.0] - 2026-08-02
Summary of Changes — PositionState / Average Price Tracking
Problem found: For a single strategy with multiple buys at different prices followed by partial sells, the reported AveragePrice diverged from the actual account average price.
Root cause: the code tracked a single blended weighted-average cost that never changed on partial closes, while the account itself computes average price on a FIFO (first-in-first-out) cost basis — so which lot gets closed first matters, and the old code didn't model that at all.
Changed - FIFO lot tracking: PositionState now keeps an internal list of cost-basis "lots" (qty + raw fill price) instead of one blended average. On each fill:
Same-direction fills append a new lot at its own price.
Opposite-direction fills consume the oldest lot(s) first (FIFO), splitting/removing lots as needed.
AveragePrice is recomputed from whatever lots remain.
This makes the internal average price match the account's actual FIFO-based calculation.
Second bug found during implementation: tick-rounding (SnapAveragePriceToTick), which runs after every single fill for display purposes, was calling the same setter used for rare broker corrections — and that setter resets the lot list to one synthetic lot. Left as-is, this would silently erase the raw per-fill prices right after they were created, defeating the FIFO fix before it could ever be used on a later partial close.
Fix - separated two concerns that were sharing one method:
SetAveragePrice() — cosmetic, tick-rounds the displayed average only; never touches the lots.
CorrectAveragePriceFromBroker() — used only in the rare restore-time reconciliation path where the broker's reported average is treated as ground truth and the lot history is intentionally reset.
Other bug fixed along the way: CorrectQuantity() (called when reconciling with the broker after a restart) updated Quantity but not the internal signed quantity used for direction/math on the next fill, causing the two to silently drift apart after any broker-driven quantity correction. Now both are kept in sync, and a new consistency check (IsHealthyAfterRestore) validates this after every restore.
Persistence: the FIFO lots are now included in the in-memory position cache (no disk format involved, so no migration needed) so cost-basis accuracy survives an application restart, not just a live session.