Repository navigation
Fix the sign of coin-margined crypto future profit - #10133
Conversation
The signed value of a long inverse position falls as the price rises, but TotalCloseProfit and ProcessCloseTradeProfit took exit value minus entry value. This reversed gross holdings profit and the trading-profit component of margin-coin settlement. Let the holding compute profit from the two values; CryptoFutureHolding inverts the difference for coin-margined futures, preserving the existing dYdX linear exception. Update the expected End Equity of BasicTemplateCryptoFutureAlgorithm and BybitCryptoFuturesRegressionAlgorithm, which trade inverse BTCUSD. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019TTGAv6fe859ebbCLLfLHP Signed-off-by: Jackmeson1 <130693642+Jackmeson1@users.noreply.github.com>
There was a problem hiding this comment.
Review
Approved. It fixes what #9940 asks for, the way agreed on the issue, and leaves every other security type as it is.
Correctness. GetProfitFromValueChange defaults to exitValue - entryValue, so TotalCloseProfit and ProcessCloseTradeProfit give exactly what they gave before for everything except coin-margined crypto futures. The override takes the same branch as CryptoFutureHolding.GetQuantityValue (not dYdX, IsCryptoCoinFuture()), so profit and valuation agree on which contracts are inverse. In TotalCloseProfit both values are converted at the same rate before the subtraction, so flipping the order is the same as flipping the base-coin profit. In ProcessCloseTradeProfit the result keeps its currency (the base coin), so ApplyFunds now credits or debits the margin coin in the right direction. The callers downstream pick up the fix without changes: UnrealizedProfit, UnrealizedProfitPercent, TotalPortfolioValue, Holdings.Profit/LastTradeProfit, and the win/loss flag passed to AddTransactionRecord. GetQuantityValue stays the same, and so does everything that uses it for notional: margin, fees, funding.
Cost. UnrealizedProfit is evaluated every time TotalPortfolioValue is recomputed. The override adds a cast and up to three string comparisons on that path, which is negligible.
Tests and evidence. I ran them locally. All 46 CryptoFutureMarginModelTests pass with the change. With only the three production files reverted to master, the 12 inverse BTCUSD cases fail and the linear ADAUSDT and dYdX controls pass, so the tests catch the defect. They cover long and short, rising and falling prices, full and partial closes, and fees. I also checked the description's end-to-end figures against quantity × 100 × (1/entry − 1/exit) for both legs, and they match. CI is green.
Regression statistics. Only End Equity changes, in the two algorithms that trade inverse BTCUSD, and each change is twice the inverse contract's profit, as the description explains. No Python algorithm has its own copy of those numbers.
Related, not blocking: this fix doesn't cover adding to an inverse position at a different price. The average entry price is averaged arithmetically for every security type, but inverse contracts need the harmonic mean. Buy 100 at 40,000, buy 100 at 50,000, close at 45,000: 0 BTC is credited instead of about +0.0056 BTC. That happens with or without this change, so I opened #10134 for it. #10031 (closed-trade statistics) and #9574 (classification) stay out of scope, as the description says.
Other repositories: none need an update. The method is internal, so the API and the Python stubs are unchanged, and the brokerage plugins don't compute holdings profit through these paths.
Risk: risk:low. It's a small bug fix and easy to revert. It replaces a plainly wrong profit sign and leaves every path that was correct as it was. There's no API change, and the evidence is tests that fail without the fix, green CI and an end-to-end run.
There was a problem hiding this comment.
Approved at 46379d7e6. No blocking findings.
The change fixes #9940 without changing notional valuation or the algorithm API. Both profit paths use the same inverse-contract condition as GetQuantityValue, including the dYdX exception. Unrealized profit still subtracts liquidation fees after calculating gross profit; realized profit retains the margin currency for settlement. Other holdings retain exactly exitValue - entryValue. Partial closes and reversals realize only the quantity being closed.
Independent validation:
- Release test-project build succeeded. All 45
CryptoFutureMarginModelTestspassed; the broader holding/portfolio/futures selection passed 327 tests. - With the new tests retained but
QuantConnect.Commonbuilt from the base commit, all 12 inverse cases failed and all 12 linear/dYdX controls passed. Restoring the reviewed assembly made all 24 new cases pass. - Tested end to end: Binance
BTCUSDminute-data backtest with seven orders, covering partial closure, both reversal directions and final flattening. All 99 unrealized-profit/portfolio-value checks and five realized-profit/BTC-settlement checks passed againstsigned contracts × multiplier × (1/entry − 1/exit). - CI is green: seven passing checks and one skipped check.
The two End Equity updates are consistent with correcting inverse profit; Python regressions share the C# expected-statistics definitions. The existing average-entry-price, closed-trade-statistics and classification defects remain separately tracked in #10134, #10031 and #9574, respectively, and do not block this sign fix.
Affected repositories: no additional source or stub updates are required. Binance, ByBit and dYdX brokerage consumers use the corrected Lean calculation; the new internal method is excluded from API stub generation.
Risk label: risk:low (retained). This is a small, easily reverted correction of a demonstrably wrong result, with no public API change or changes to the previously correct linear paths, backed by green CI, regression-sensitive tests and an independent end-to-end run.
Description
For coin-margined (inverse) crypto futures,
SecurityHolding.TotalCloseProfit(behindUnrealizedProfit) andSecurityPortfolioModel.ProcessCloseTradeProfittook the value at exit minus the value at entry.CryptoFutureHolding.GetQuantityValuevalues an inverse position asquantity × multiplier / price, which falls for a long position as the price rises, so the profit came out with the wrong sign: long 100 BinanceBTCUSDcontracts from 40,000 to 44,000 showed −1,000 USD unrealized profit and debited 0.0227 BTC on close instead of +1,000 USD and a 0.0227 BTC credit (contracts × contract size × (1/entry − 1/exit)).This adds an
internal virtual SecurityHolding.GetProfitFromValueChange(entryValue, exitValue), defaulting toexitValue - entryValueso every other security type is unchanged.CryptoFutureHoldingoverrides it to returnentryValue - exitValuefor coin-margined futures, with the same dYdX exceptionGetQuantityValuemakes, and both profit paths call it.GetQuantityValue(used for notional, margin, fees and funding), fee handling and the currency of the result are unchanged. The method isinternal, so the algorithm API is unchanged.The change is the commit from #9941 by @Jackmeson1, cherry-picked with its authorship kept, following the approach agreed on the issue.
Regression statistics: the two algorithms that trade inverse
BTCUSDnow book that contract's profit with the right sign, so their End Equity moves by twice that profit, and nothing else in their statistics changes:BasicTemplateCryptoFutureAlgorithm: 1000278.02 → 1000272.75 (theBTCUSDtrades lost 2.64 USD and were booked as a 2.64 USD gain).BybitCryptoFuturesRegressionAlgorithm: 100285.26 → 100277.70 (lost 3.78 USD, booked as a gain).Out of scope: closed-trade statistics in
TradeBuilderhave their own formula for these contracts (#10031), and contracts misclassified as coin-margined (#9574) flip along with real inverse ones, consistent with how they are valued today.Related Issue
Closes #9940
Motivation and Context
Gross unrealized and realized holdings profit of inverse crypto futures, the margin-coin settlement on close, and with them
TotalPortfolioValueand margin remaining, had their signs reversed.Requires Documentation Change
No.
How Has This Been Tested?
CryptoFutureMarginModelTestscases:UnrealizedProfitFollowsPriceMove(long/short, rising/falling, BinanceBTCUSD, with linearADAUSDTand dYdXBTCUSDas controls) andCloseProfitSettlesInMarginCurrency(full closes without fees and partial closes with fees,BTCUSDandADAUSDT), checking profit, margin-currency cash, fees, net profit andTotalPortfolioValue.dotnet build QuantConnect.Lean.sln(Release): 0 errors.TestCategory!=TravisExclude&TestCategory!=ResearchRegressionTests): 39623 passed, 100 skipped, 0 failed (includes the crypto-future regression algorithms).BTCUSDminute data (2022-12-13) that opens a long and then a short of 10 contracts and closes each: unrealized profit and the BTC credited or debited on close matchedquantity × 100 × (1/entry − 1/exit)for both legs (long: −0.0000420 BTC as the price fell 17,179.7 → 17,167.35; short: −0.0007402 BTC as it rose 17,176.2 → 17,397.35). Without the change, the same backtest failed with the BTC change on close having the opposite sign (+0.0000420 BTC on the long leg).Types of changes
Checklist