TradeBuilder FlatToFlat can miscalculate a trade's P&L when a fill reverses the position after partial exits
Maintainers usually reply within 1 day
Nobody has claimed this yet.
- #9939 by @Jackmeson1 — closed without merging
Assessment
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Newbie friendliness
- 25/100
Research direction
The issue points to Common/Statistics/TradeBuilder.cs, in TradeBuilder.ProcessFillUsingFlatToFlat around the trade-closed branch, and names the TradeBuilderTests.FlatToFlatReversalAfterPartialExit regression. Read that branch and run the regression for both FIFO and LIFO. Done means the closing portion of a reversing fill determines the completed trade’s exit price, and all four long and short cases report the expected gross P&L.
Written by the indexing model from the issue text.
Description
Expected Behavior
With FillGroupingMethod.FlatToFlat, when a fill both closes a trade and reverses the position, only the part of
the fill that closes the trade goes into that trade's exit price; the rest opens the next trade.
Example: buy 10 @ 100, sell 5 @ 110, sell 10 @ 120 (5 close the long, 5 open a short), buy 5 @ 120. With zero fees
and conversion rate and multiplier both equal to one, the long trade exits at (5 × 110 + 5 × 120) / 10 = 115 with
a gross P&L of 150, and the short trade has a P&L of 0. The total, 150, equals the cash flows
(−1000 + 550 + 1200 − 600) and what FillToFill and FlatToReduced report for the same fills.
Actual Behavior
On master f3d841e, FlatToFlat reports the long trade with an exit price displayed as 116.67 and a gross P&L
of 166.67:
FillToFill sum(trade.ProfitLoss) = 150.0 trades: Long q=5 entry=100 exit=110 pnl=50.0 | Long q=5 entry=100 exit=120 pnl=100.0 | Short q=5 entry=120 exit=120 pnl=0.0
FlatToFlat sum(trade.ProfitLoss) = 166.67 trades: Long q=10 entry=100 exit=116.67 pnl=166.67 | Short q=5 entry=120 exit=120 pnl=0.0
FlatToReduced sum(trade.ProfitLoss) = 150.0 trades: Long q=5 entry=100 exit=110 pnl=50.0 | Long q=5 entry=100 exit=120 pnl=100.0 | Short q=5 entry=120 exit=120 pnl=0.0
In TradeBuilder.ProcessFillUsingFlatToFlat (Common/Statistics/TradeBuilder.cs, the "trade closed" branch around
lines 424-472 at f3d841e) the reversing fill is added to the position's pending fills with its whole quantity before
the exit average is computed, so all 10 units at 120 are averaged in although only 5 of them close the trade.
For this long example, gross P&L is (exit average - entry average) × entry quantity, rounded to two decimals.
The remaining 5 units correctly open the next position (lines 486-495), so their quantity contributes to both
trades' prices. The affected output is reconstructed closed-trade reporting.
Potential Solution
Subtract the opening remainder from the closing fill before it is added to the pending fills, so the exit average
uses only the closing quantity. The remainder already opens the next position.
Reproducing the Problem
In a Linux shell at the root of a LEAN checkout at f3d841e, with a .NET 10 SDK, create a temporary console project:
repro_dir="$(mktemp -d /tmp/lean-flattoflat.XXXXXX)"
dotnet new console --framework net10.0 --name FlatToFlatRepro --output "$repro_dir"
dotnet add "$repro_dir/FlatToFlatRepro.csproj" reference "$PWD/Common/QuantConnect.csproj"
Replace the generated Program.cs in that directory with:
using System;
using System.Linq;
using QuantConnect;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Statistics;
var spy = new Symbol(SecurityIdentifier.GenerateEquity("SPY", Market.USA, mapSymbol: false), "SPY");
var t0 = new DateTime(2024, 1, 2, 9, 30, 0);
// buy 10 @100, sell 5 @110, sell 10 @120 (closes the 5 left and opens a short of 5), buy 5 @120 (flat)
var fills = new[] { (10, 100m), (-5, 110m), (-10, 120m), (5, 120m) };
foreach (var g in Enum.GetValues<FillGroupingMethod>())
{
var tb = new TradeBuilder(g, FillMatchingMethod.FIFO);
for (var i = 0; i < fills.Length; i++)
tb.ProcessFill(new OrderEvent(i + 1, spy, t0.AddMinutes(i), OrderStatus.Filled, fills[i].Item1 > 0 ? OrderDirection.Buy : OrderDirection.Sell,
fills[i].Item2, fills[i].Item1, OrderFee.Zero), 1m, 0m);
Console.WriteLine($"{g,-13} sum(trade.ProfitLoss) = {tb.ClosedTrades.Sum(t => t.ProfitLoss),7} trades: " +
string.Join(" | ", tb.ClosedTrades.Select(t => $"{t.Direction} q={t.Quantity} entry={t.EntryPrice:0.##} exit={t.ExitPrice:0.##} pnl={t.ProfitLoss}")));
}
Run it from the same shell:
dotnet run --project "$repro_dir/FlatToFlatRepro.csproj" --configuration Release
This is a standalone console reproduction, not included in the patch. I ran the sequence against f3d841e on
Linux; the output above uses FIFO and formats exit prices to two decimal places.
The added TradeBuilderTests.FlatToFlatReversalAfterPartialExit regression also fails on f3d841e for both FIFO
and LIFO: the long cases expect gross P&L 150 but receive 166.67. Mirroring all quantity signs gives short cases
that expect -150 but receive -166.67. With the fix, all four cases pass.
System Information
LEAN master f3d841e, Linux, .NET 10 (net10.0).
Regression validation used the quantconnect/lean:foundation CI image in a Linux VM, .NET SDK 10.0.101 and
VSTest 18.0.1.
Checklist
- I have completely filled out this template
- I have confirmed that this issue exists on the current
masterbranch - I have confirmed that this is not a duplicate issue by searching issues
- I have provided detailed steps to reproduce the issue
- Dominant language
- C#
- Stars
- 22.6k
- Forks
- 5.4k
- Avg merge
- 11h 39m
- Merged PRs (30d)
- 104
Getting set up
Starts the project's dev container in your browser, under your own GitHub account.
- Ships a Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from QuantConnect/Lean
-
priority:p2
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
QuantConnect/Lean#10216 ·
Maintainers usually reply within 1 day
-
priority:p2
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
QuantConnect/Lean#10206 ·
Maintainers usually reply within 1 day
-
priority:p2
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
QuantConnect/Lean#10199 ·
Maintainers usually reply within 1 day
-
priority:p2
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
QuantConnect/Lean#10198 ·
Maintainers usually reply within 1 day
-
priority:p2
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
QuantConnect/Lean#10197 ·
Maintainers usually reply within 1 day
All issues in QuantConnect/Lean
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
dotnet-outdated/dotnet-outdated#871 ·
Maintainers usually reply within 1 day
-
triage/untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
unoplatform/uno#26676 ·
Maintainers usually reply within 1 day
-
.NET bug
Difficulty 2/5 1-3 hours Newbie friendliness 84/100
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
jhaizhou-ops/S2Arm#2177 · 3 comments ·
Maintainers usually reply within 1 day
-
area-CodeGen-coreclr untriaged
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
dotnet/runtime#138181 · 1 comment ·
Maintainers usually reply within 1 day