TradeBuilder FlatToFlat can miscalculate a trade's P&L when a fill reverses the position after partial exits

Abierto
#9,938 1 comentario 0 reacciones 0 asignados Ver en GitHub

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
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Estancado
Stack tecnológico
csharp
Área
backend

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 master branch
  • 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

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de QuantConnect/Lean

Todos los issues de QuantConnect/Lean

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.