TradeBuilder FlatToFlat can miscalculate a trade's P&L when a fill reverses the position after partial exits
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
- #9939 de @Jackmeson1 — cerrado sin fusionar
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 25/100
Línea de trabajo
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.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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
- Lenguaje dominante
- C#
- Estrellas
- 22.5k
- Forks
- 5.4k
- Merge medio
- 22 h 6 min
- PR fusionados (30 d)
- 81
Preparar el entorno
Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.
- Incluye un Dockerfile o un archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de QuantConnect/Lean
-
PDF report generation can overwrite HTML when the destination extension is not lowercase .htmlAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
QuantConnect/Lean#10082 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
QuantConnect/Lean#10059 ·
Los mantenedores suelen responder en 1 día
-
Library Request: highspyAbiertolibrary-request
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
QuantConnect/Lean#10034 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
QuantConnect/Lean#9965 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
QuantConnect/Lean#9955 ·
Los mantenedores suelen responder en 1 día
Todos los issues de QuantConnect/Lean
Issues similares
-
bug emitter:client:csharp
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
microsoft/typespec#12572 · 1 comentario · 1 reacción ·
Los mantenedores suelen responder en 1 día
-
needs-area-label
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 2 días
-
AWS Lambda: KeyNotFoundException drops HTTP-triggered transactions when allowAllHeaders is disabledAbiertobug
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
newrelic/newrelic-dotnet-agent#3949 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
area-networking
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
dotnet/aspnetcore#70545 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 87/100
Los mantenedores suelen responder en 1 día