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

Aperta
#9,938 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

  • #9939 di @Jackmeson1 — chiusa senza merge

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
25/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Ferma
Stack tecnologico
csharp
Ambito
backend

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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
Lingua principale
C#
Stelle
22.5k
Fork
5.4k
Merge medio
22h 6m
PR unite (30g)
81

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di QuantConnect/Lean

Tutte le issue di QuantConnect/Lean

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.