{"record":{"id":"39f43cee8e592013","repo":"QuantConnect/Lean","slug":"expected-positive-totalmarginused-got-portfolio","errorCode":null,"errorMessage":"Expected positive TotalMarginUsed, got {Portfolio.TotalMarginUsed}","messagePattern":"Expected positive TotalMarginUsed, got (.+?)","errorType":"exception","errorClass":"RegressionTestException","httpStatus":null,"severity":"error","filePath":"Algorithm.CSharp/BinanceCryptoFutureBnfcrCollateralRegressionAlgorithm.cs","lineNumber":79,"sourceCode":"            // 1. BNFCR collateral must produce positive buying power (USDT is zero)\n            var buyingPower = _adaUsdt.BuyingPowerModel.GetBuyingPower(new BuyingPowerParameters(Portfolio, _adaUsdt, OrderDirection.Buy));\n            if (buyingPower.Value <= 0)\n            {\n                throw new RegressionTestException($\"Expected positive buying power from BNFCR, got {buyingPower.Value}\");\n            }\n\n            // 2. Order must not be rejected\n            var ticket = Buy(_adaUsdt.Symbol, 1000);\n            _orderPlaced = true;\n            if (ticket.Status == OrderStatus.Invalid)\n            {\n                throw new RegressionTestException(\"Order rejected — BNFCR collateral should cover margin\");\n            }\n\n            // 3. Margin must be tracked\n            if (Portfolio.TotalMarginUsed <= 0)\n            {\n                throw new RegressionTestException($\"Expected positive TotalMarginUsed, got {Portfolio.TotalMarginUsed}\");\n            }\n\n            // 4. Shared collateral: ETHUSDC (different quote currency) must deduct ADAUSDT margin\n            _ethUsdc.SetMarketPrice(new TradeBar { Time = Time, Symbol = _ethUsdc.Symbol, Close = 1600 });\n\n            var ethBuyingPower = _ethUsdc.BuyingPowerModel.GetBuyingPower(new BuyingPowerParameters(Portfolio, _ethUsdc, OrderDirection.Buy));\n            var adaBuyingPower = _adaUsdt.BuyingPowerModel.GetBuyingPower(new BuyingPowerParameters(Portfolio, _adaUsdt, OrderDirection.Buy));\n\n            // ETHUSDC must see less buying power than ADAUSDT - ADAUSDT maintenance margin\n            // is deducted from ETHUSDC's shared pool, but ADAUSDT skips itself.\n            if (ethBuyingPower.Value >= adaBuyingPower.Value)\n            {\n                throw new RegressionTestException(\n                    $\"ETHUSDC buying power ({ethBuyingPower.Value}) must be less than ADAUSDT ({adaBuyingPower.Value}) \" +\n                    $\"— shared BNFCR pool must deduct ADAUSDT maintenance margin\");\n            }\n        }\n","sourceCodeStart":61,"sourceCodeEnd":97,"githubUrl":"https://github.com/QuantConnect/Lean/blob/d2c3659f877bfc2b5d9dc0fc89a9c7566f45e892/Algorithm.CSharp/BinanceCryptoFutureBnfcrCollateralRegressionAlgorithm.cs#L61-L97","documentation":"Thrown when Portfolio.TotalMarginUsed is zero or negative after the ADAUSDT buy order fills. TotalMarginUsed should reflect the maintenance margin consumed by the open ADAUSDT futures position. A zero value means the margin tracking system failed to register the position's margin requirement.","triggerScenarios":"The CryptoFutureSecurityMarginModel did not update TotalMarginUsed after the fill, the position was not actually opened despite the order being accepted, or the margin model returns zero for this position configuration.","commonSituations":"Margin model bugs where crypto future positions are not counted, Holding objects not updated after fills, or Portfolio.ProcessFill not invoking the margin model correctly for CryptoFuture security type.","solutions":["Verify the ADAUSDT position is actually open: check Portfolio[_adaUsdt.Symbol].Quantity and .HoldingsValue.","Inspect SecurityMarginModel.GetReservedMargin to confirm it returns a positive value for the open position.","Check that Portfolio.ProcessFill or the fill event handler triggers margin recalculation for CryptoFuture.","Log Securities[_adaUsdt.Symbol].BuyMarginModel and .MaintenanceMarginModel outputs.","Ensure the crypto future price feed is active so the margin model has a current price to compute against."],"exampleFix":"// before\nif (Portfolio.TotalMarginUsed <= 0)\n{\n    throw new RegressionTestException($\"Expected positive TotalMarginUsed, got {Portfolio.TotalMarginUsed}\");\n}\n\n// after — diagnose margin components\nif (Portfolio.TotalMarginUsed <= 0)\n{\n    var sec = Securities[_adaUsdt.Symbol];\n    Log($\"Position: qty={Portfolio[_adaUsdt.Symbol].Quantity}, \" +\n        $\"margin model={sec.BuyingPowerModel.GetType().Name}\");\n    throw new RegressionTestException(\n        $\"Expected positive TotalMarginUsed, got {Portfolio.TotalMarginUsed}\");\n}","handlingStrategy":"validation","validationCode":"// Validate margin tracking before asserting\nvar qty = Portfolio[_adaUsdt.Symbol].Quantity;\nLog($\"ADAUSDT position: {qty}, TotalMarginUsed: {Portfolio.TotalMarginUsed}\");\nif (Portfolio.TotalMarginUsed <= 0 && qty != 0)\n{\n    Log($\"Position open but margin not tracked — check margin model\");\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Verify the position is actually open (non-zero quantity) before checking margin.","Inspect SecurityMarginModel.GetReservedMargin for the crypto future position.","Ensure Portfolio.ProcessFill triggers margin recalculation for CryptoFuture.","Log Holdings.Quantity and TotalMarginUsed together to correlate."],"tags":["quantconnect","binance","crypto-futures","margin","portfolio","regression-test"],"backgroundTag":null,"analyzedSha":"d2c3659f877bfc2b5d9dc0fc89a9c7566f45e892","analyzedAt":"2026-08-13T13:52:21.013Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}