Repository navigation
Value coin-margined crypto futures correctly in closed-trade statistics - #10136
Conversation
Inverse contracts are valued at the reciprocal of the price, so a zero market price would throw while updating drawdown on the data loop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Approving. Closed trades on coin-margined crypto futures now report profit, MAE, MFE and end-trade drawdown in the account currency, valued the same way the holding values them: quantity × multiplier / price in the base currency, converted at the base currency's rate. This is what #10031 asks for.
What I checked:
- Math, all three grouping methods. I traced each formula by hand against the tests.
−1/pricerises with the price, so the min/max price still gives the adverse and favorable excursion. FlatToFlat and FlatToReduced weight the averaged values by fill quantity, so scaling in and partial exits add up to the same total, 633.33 inInverseCryptoFutureScaleInAndPartialExit.EntryPriceandExitPricedon't change. - dYdX exclusion.
IsCryptoCoinFuture()returns true for dYdXBTCUSDbecause its quote currency is USD. The addedMarket.DYDXcheck matchesCryptoFutureHolding.GetQuantityValueandGetProfitFromValueChange, so dYdX stays linear. - Zero-price guard. It's needed.
AlgorithmManagercallsSetMarketPriceon every data update and doesn't catch exceptions, so without the guard−1/0there would stop the algorithm. Linear securities don't go through the guard and work as before. - Tests. Built locally.
TradeBuilderTestsand everyCryptoFuturetest pass (578). I putmaster'sTradeBuilder.csback and 23 of the new cases failed, so the tests catch the bug. The 11 crypto future regression algorithms pass. - CI is green, and the end-to-end comparison in the description matches the expected
100 × (1/17167.4 − 1/17419.5) × 17419.5 ≈ 1.47. Equity is unchanged, because only statistics change.
Non-blocking:
- The change uses the shared
CryptoFuture.IsCryptoCoinFuture(), so closed-trade statistics now follow its classification. That classification is wrong for a few linear Binance contracts in the symbol properties database:BTCU,ETHU,BTCUSD1,ETHUSD1andETHBTC, tracked in #9574. Their closed trades will now be valued as inverse. Their holdings, margin and fees already are, so the statistics match what the portfolio books. Fixing #9574 fixes this path too, with no change needed here.
Other repositories: none need an update. ITradeBuilder is unchanged, and only TradeBuilder's internals moved.
Risk: risk:low. The change is small and easy to revert. It only affects trade statistics for coin-margined crypto futures, and portfolio values, orders and every other security type compute as before. Tests fail without the fix, CI is green, and there's an end-to-end run.
There was a problem hiding this comment.
Changes requested: preserve the previously correct closed-trade calculation for linear Binance contracts before applying reciprocal pricing.
The new branch relies on IsCryptoCoinFuture(), whose existing whitelist misclassifies ETHBTC, BTCUSD1, ETHUSD1, BTCU and ETHU. Binance's published contract metadata identifies their settlement currency as the quote currency. Although the classification defect is already tracked in #9574, extending it to TradeBuilder introduces a new regression: those contracts' closed-trade statistics were linear and correct before this change. Matching their already-incorrect holdings valuation does not make the new statistics correct. Please constrain inverse valuation to actual inverse contracts, retaining the linear path for these contracts, and add regression coverage.
Independent validation:
- Release build succeeded; all 420 selected trade-builder and crypto-future margin tests passed. Substituting the base
TradeBuildermade 23 inverse cases fail; the restored head passed the 420-test selection again. CI is green. - A standalone
ETHBTCtrade, one contract from0.03to0.04, with BTC/USD conversion40,000and ETH/USD conversion1,600, reports 400.00 on master versus 13,333.33 here, in all three grouping methods. The correct result is(0.04 - 0.03) × 40,000 = 400. - Tested end to end: a daily-data backtest correctly reported the inverse
BTCUSDtrade at −1.97, but reported the linearETHBTCtrade at 768.04 instead of 22.28. The linear regression is reachable through normal algorithm orders, not just a directTradeBuildercall.
Separately, the existing two-decimal rounding problem for BTC-denominated accounts is now tracked in #10137; it also reproduces on master and is not a blocker for this fix.
Affected repositories: no additional source or stub updates are required outside Lean; ITradeBuilder and the public API are unchanged.
Risk label: risk:high (raised). The change currently corrupts previously correct results for existing linear contracts. Preserve those paths and cover them with tests before this can be considered a narrowly scoped inverse-contract correction.
…mula IsCryptoCoinFuture() also matches linear Binance contracts quoted in currencies other than USDT, BUSD and USDC, such as ETHBTC, BTCUSD1 and BTCU. Coin-margined contracts have a USD face value, so only value USD-quoted contracts at the reciprocal of the price in TradeBuilder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Addressed the request to keep linear contracts on the linear formula (77bb568).
|
There was a problem hiding this comment.
Approving 77bb568. It resolves the change request on d60cb04: linear Binance contracts quoted outside USD keep the linear closed-trade formula and their quote currency's rate, as on master.
What I checked since my last review:
- Classification.
TryGetInverseCryptoFuturenow requires a USD quote currency (dYdX still excluded) instead ofIsCryptoCoinFuture(). In the symbol properties database, crypto futures quoted in USD are the 48 Binance and 25 Bybit coin-margined contracts and the dYdX ones. The others are quoted inUSDT/BUSD/USDC,BTC(ETHBTC),U(BTCU,ETHU) orUSD1(BTCUSD1,ETHUSD1), so all of them now stay linear. The zero-price guard and the base-currency rate go through the same check, so they follow it. - Tests. Built locally: all 399
TradeBuilderTestspass. When I put back theIsCryptoCoinFuture()check, the 18 new linear cases (ETHBTC,BTCUSD1,BTCU, three groupings, both directions) fail. The inverse value would be about 0.1 against the expected 4,000, so the tests do tell the two formulas apart. The Bybit inverseBTCUSDcase passes. - End to end. The description has a backtest with both an inverse
BTCUSDand a linearETHBTCtrade. Their −25.70 and −971.83 match each formula at the exit fill. This is the case the earlier request reproduced. - CI is green on this commit.
Non-blocking:
TradeBuildernow has its own inverse check alongsideCryptoFuture.IsCryptoCoinFuture(). Until #9574 is fixed, closed-trade statistics forETHBTC,BTCU/ETHUandBTCUSD1/ETHUSD1are right, but they differ from the holdings, margin and fees, which still value those contracts as inverse. Once #9574 corrects the shared classification, this check could go back toIsCryptoCoinFuture()(plus the dYdX exclusion), so there is one definition again.
Other repositories: none need an update. ITradeBuilder and the public API are unchanged.
Risk: risk:low. The change is small and easy to revert, and it only changes closed-trade statistics for USD-quoted coin-margined crypto futures. Portfolio values, orders, linear contracts and other security types work as before. Tests fail without the fix, CI is green, and an end-to-end run covers both inverse and linear contracts. The earlier risk:high was set because linear contracts regressed on d60cb04. This commit fixes that and covers it with tests.
There was a problem hiding this comment.
Approving 77bb568. This resolves my earlier change request: the five linear Binance contracts (ETHBTC, BTCU/ETHU, BTCUSD1/ETHUSD1) retain linear pricing and quote-currency conversion, while actual inverse contracts retain the correction.
Follow-up validation
- Compared the predicates against the symbol-properties database: the classification changes for exactly those five linear contracts. All 48 Binance and 25 Bybit USD-quoted inverse entries remain selected; dYdX remains excluded. Binance's coin-futures subscription predicate also requires USD.
- Release build succeeded. All 602 selected trade-builder and crypto-future tests passed. Restoring only the previous classifier caused exactly 18 linear regression cases to fail; rebuilding the restored head passed all 602 again.
- Tested end to end: a daily backtest placed and closed normal orders in both contract types, with assertions against their respective formulas at the exit fill's conversion rates. The 100-contract inverse
BTCUSDtrade reported −66.48 USD (unrounded expectation −66.4845255); the 10-contract linearETHBTCtrade reported −152.85 USD (expectation −152.846064). Both assertions passed. - CI is green on the reviewed commit.
Affected repositories: no additional source or stub updates are required; ITradeBuilder and public signatures are unchanged. The existing shared-classifier issue remains tracked separately in #9574.
Risk label: risk:low. The previously introduced linear-contract regression is removed and covered by tests that fail without this correction. The remaining change is a narrowly scoped inverse-contract statistics fix, backed by green CI and end-to-end evidence; portfolio and order behavior are unchanged.
Description
Closed-trade statistics (
TradeBuilder) for coin-margined (inverse) crypto futures used the linear formula(exit − entry) × quantity × quote rate × multiplier. That treated the contract's USD face value as a base-asset quantity. For example, BinanceBTCUSDlong 100 contracts from 40,000 to 44,000 reported aProfitLossof 40,000,000 instead of about 1,000 USD.This builds on #10039 by @mkzung, whose two commits are cherry-picked here with authorship kept:
CryptoFutureHolding), prices are valued as−1/price, and the base currency's conversion rate is used. This matches the holding's valuationquantity × multiplier / pricein the base currency. The result applies toProfitLoss,MAE,MFEandEndTradeDrawdownin all three grouping methods.EntryPriceandExitPricestay as they were.One commit is added on top.
SetMarketPricenow skips a zero price for inverse contracts. It runs on every data update, and without this a zero price would throw a division by zero there.The inverse valuation applies only to USD-quoted contracts, which in the symbol properties database are the coin-margined Binance and Bybit contracts.
CryptoFuture.IsCryptoCoinFuture()also returns true for linear Binance contracts quoted in other currencies (ETHBTC,BTCU/ETHU,BTCUSD1/ETHUSD1, see #9574). Their closed trades therefore keep the linear formula and the quote currency's rate, as on master.Linear contracts (
BTCUSDT,ETHBTC,BTCU,BTCUSD1, dYdXBTCUSD) and every other security type keep their calculation.Related Issue
Closes #10031
Motivation and Context
Inverse contracts settle in the base asset, so closed-trade profit and its risk statistics have to be computed from the base-asset notional.
Requires Documentation Change
No.
How Has This Been Tested?
TradeBuilderTestsgained cases from Value inverse crypto futures correctly in closed-trade statistics #10039 that cover:BTCUSDand the linear BinanceETHBTC,BTCUSD1andBTCU. With the earlierIsCryptoCoinFuture()classification, the 18 linear cases fail.TestCategory!=TravisExclude&TestCategory!=ResearchRegressionTests): 39,683 passed, 100 skipped, 0 failed.BasicTemplateCryptoFutureAlgorithm, comparing master with this branch:1.47 matches 100 × (1/17167.4 − 1/17419.5) BTC × 17,419.5 USD/BTC ≈ 1.468 USD.
BTCUSD(100 contracts, 27,985.7 → 27,913.8) and linearETHBTC(10 contracts, 0.06198 → 0.0585). Closed-trade profit is −25.70 and −971.83 USD, matching100 × 100 × (1/27985.7 − 1/27913.8) × BTC rateand(0.0585 − 0.06198) × 10 × BTC rateat the exit fill.Types of changes
Checklist:
bug-<issue#>-<description>.