{"record":{"id":"9a4d58ca0e3d076c","repo":"nautechsystems/nautilus_trader","slug":"maintenance-margin-calculation-overflow","errorCode":null,"errorMessage":"maintenance margin calculation overflow","messagePattern":"maintenance margin calculation overflow","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/model/src/accounts/margin_model.rs","lineNumber":290,"sourceCode":"        let currency = margin_currency(instrument, use_quote)?;\n        Money::from_decimal(margin, currency).map_err(Into::into)\n    }\n\n    fn calculate_maintenance_margin(\n        &self,\n        instrument: &dyn Instrument,\n        quantity: Quantity,\n        price: Price,\n        _leverage: Decimal,\n        use_quote_for_inverse: Option<bool>,\n    ) -> anyhow::Result<Money> {\n        let use_quote = use_quote_for_inverse.unwrap_or(false);\n        let notional = instrument.try_calculate_notional_value(quantity, price, Some(use_quote))?;\n        let margin = notional\n            .as_decimal()\n            .abs()\n            .checked_mul(instrument.margin_maint())\n            .ok_or_else(|| anyhow::anyhow!(\"maintenance margin calculation overflow\"))?;\n        let currency = margin_currency(instrument, use_quote)?;\n        Money::from_decimal(margin, currency).map_err(Into::into)\n    }\n}\n\n/// Divides notional value by leverage before applying margin rates.\n///\n/// Margin is calculated as `(notional_value / leverage) * margin_rate`.\n/// This is the default model, appropriate for crypto exchanges and venues\n/// where leverage directly reduces margin requirements.\n#[derive(Debug, Clone, Copy)]\n#[cfg_attr(\n    feature = \"python\",\n    pyo3::pyclass(module = \"nautilus_trader.model\", from_py_object)\n)]\n#[cfg_attr(\n    feature = \"python\",\n    pyo3_stub_gen::derive::gen_stub_pyclass(module = \"nautilus_trader.model\")","sourceCodeStart":272,"sourceCodeEnd":308,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/model/src/accounts/margin_model.rs#L272-L308","documentation":"Same overflow guard as the initial margin variant, but in the leveraged maintenance margin path: |notional| × margin_maint is computed with checked_mul and any overflow, or a Money conversion failure at the currency precision, produces this error. It protects the account model from producing an invalid reserve requirement.","triggerScenarios":"calculate_maintenance_margin called with notional × margin_maint exceeding decimal limits, or a margin that Money::from_decimal cannot represent for the resolved currency.","commonSituations":"Huge price/quantity inputs in simulation; corrupt market data producing astronomic notionals; instruments with exaggerated margin_maint rates.","solutions":["Validate quantity/price magnitudes before the call","Check instrument.margin_maint() for a plausible rate","Propagate or handle the error instead of panicking; reject the position"],"exampleFix":"// before\nlet mm = model.calculate_maintenance_margin(&inst, qty, price, None).unwrap();\n// after\nlet mm = model.calculate_maintenance_margin(&inst, qty, price, None)?; // handle Err upstream","handlingStrategy":"try-catch","validationCode":"if notional.abs() > Decimal::from(1e18) { bail!(\"notional too large for maintenance margin\"); }","typeGuard":null,"tryCatchPattern":"match model.calculate_maintenance_margin(&inst, qty, price, use_quote) {\n    Ok(m) => m,\n    Err(e) if e.to_string().contains(\"overflow\") => { warn!(\"maintenance margin overflow\"); default_reserve }\n    Err(e) => return Err(e),\n}","preventionTips":["Sanity-check notional magnitude before margin calls","Keep margin_maint rates realistic","Propagate errors instead of panicking"],"tags":["rust","margin","overflow","arithmetic"],"backgroundTag":"value-out-of-range","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}