Skip to content

Fix the sign of coin-margined crypto future profit - #10133

Merged
quantconnect-kronos[bot] merged 1 commit into
masterfrom
kronos/bug-9940-coin-future-profit-sign
Nov 13, 2026
Merged

quantconnect-kronos[bot] merged 1 commit into
masterfrom
kronos/bug-9940-coin-future-profit-sign

Conversation

@quantconnect-kronos

Copy link
Copy Markdown
Contributor

Description

For coin-margined (inverse) crypto futures, SecurityHolding.TotalCloseProfit (behind UnrealizedProfit) and SecurityPortfolioModel.ProcessCloseTradeProfit took the value at exit minus the value at entry. CryptoFutureHolding.GetQuantityValue values an inverse position as quantity × multiplier / price, which falls for a long position as the price rises, so the profit came out with the wrong sign: long 100 Binance BTCUSD contracts 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 to exitValue - entryValue so every other security type is unchanged. CryptoFutureHolding overrides it to return entryValue - exitValue for coin-margined futures, with the same dYdX exception GetQuantityValue makes, 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 is internal, 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 BTCUSD now 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 (the BTCUSD trades 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 TradeBuilder have 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 TotalPortfolioValue and margin remaining, had their signs reversed.

Requires Documentation Change

No.

How Has This Been Tested?

  • New CryptoFutureMarginModelTests cases: UnrealizedProfitFollowsPriceMove (long/short, rising/falling, Binance BTCUSD, with linear ADAUSDT and dYdX BTCUSD as controls) and CloseProfitSettlesInMarginCurrency (full closes without fees and partial closes with fees, BTCUSD and ADAUSDT), checking profit, margin-currency cash, fees, net profit and TotalPortfolioValue.
  • dotnet build QuantConnect.Lean.sln (Release): 0 errors.
  • Full test suite as CI runs it (TestCategory!=TravisExclude&TestCategory!=ResearchRegressionTests): 39623 passed, 100 skipped, 0 failed (includes the crypto-future regression algorithms).
  • Tested end to end with a backtest on Binance BTCUSD minute 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 matched quantity × 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

  • Bug fix (non-breaking change which fixes an issue)

Checklist

  • My code follows the code style of this project.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

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>

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added risk:low Low risk and removed kronos:review:working review: in progress labels Nov 13, 2026
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 13, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued and removed kronos:review Request review labels Nov 13, 2026
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot added kronos:review:working review: in progress and removed kronos:review:queued review: queued labels Nov 13, 2026

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 CryptoFutureMarginModelTests passed; the broader holding/portfolio/futures selection passed 327 tests.
  • With the new tests retained but QuantConnect.Common built 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 BTCUSD minute-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 against signed 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.

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot removed the kronos:review:working review: in progress label Nov 13, 2026
@quantconnect-kronos
quantconnect-kronos Bot merged commit 6646c1f into master Nov 13, 2026
8 checks passed
@quantconnect-kronos
quantconnect-kronos Bot deleted the kronos/bug-9940-coin-future-profit-sign branch November 13, 2026 18:08
@quantconnect-kronos quantconnect-kronos Bot removed the kronos:develop:working develop: in progress label Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Low risk

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Coin-margined crypto future holdings profit has its sign reversed

1 participant