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

オープン
#9,938 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

  • #9939 @Jackmeson1 による — マージされずにクローズ

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
25/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
停滞
技術スタック
csharp
領域
backend

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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
主要言語
C#
スター
22.5k
フォーク
5.4k
平均マージ
22時間 6分
マージ済み PR(30日)
81

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

QuantConnect/Lean のほかの issue

QuantConnect/Lean の issue をすべて見る

似ている issue

C# の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。