{"record":{"id":"386bfa2fea8863b1","repo":"nautechsystems/nautilus_trader","slug":"initial-margin-calculation-overflow","errorCode":null,"errorMessage":"initial margin calculation overflow","messagePattern":"initial margin calculation overflow","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/model/src/accounts/margin_model.rs","lineNumber":271,"sourceCode":"    }\n\n    fn calculate_initial_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        // Spreads and options may quote negative, which carries the sign into the notional.\n        // A requirement is a reserve against exposure magnitude, so take it on `abs`.\n        let margin = notional\n            .as_decimal()\n            .abs()\n            .checked_mul(instrument.margin_init())\n            .ok_or_else(|| anyhow::anyhow!(\"initial margin calculation overflow\"))?;\n        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())","sourceCodeStart":253,"sourceCodeEnd":289,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/model/src/accounts/margin_model.rs#L253-L289","documentation":"Thrown by the leveraged (non-standard) initial margin path when the checked decimal multiplication of |notional| by margin_init overflows, or when the resulting margin cannot be converted to a Money value at the currency's precision. It is a guard against arithmetic overflow rather than a logic error, since margin amounts can be extremely large for high notionals or rates.","triggerScenarios":"calculate_initial_margin with an extremely large notional value (huge quantity × price) multiplied by margin_init such that the rust_decimal product overflows; also when Money::from_decimal cannot represent the margin at the currency precision.","commonSituations":"Backtests with oversized or malformed prices/quantities; instruments with unreasonably large margin_init rates; low-precision currencies receiving very large margins.","solutions":["Check the quantity and price inputs for unreasonable magnitude before calling","Verify instrument.margin_init() is a sane rate (e.g. 0.01–1.0, not 1000)","Handle the error and skip/reject the position instead of unwrapping"],"exampleFix":"// before\nlet margin = model.calculate_initial_margin(&inst, qty, price, None).unwrap();\n// after\nmatch model.calculate_initial_margin(&inst, qty, price, None) {\n    Ok(m) => ..., \n    Err(e) if e.to_string().contains(\"overflow\") => warn!(\"margin overflow, rejecting\"),\n    Err(e) => return Err(e),\n}","handlingStrategy":"try-catch","validationCode":"if qty.as_decimal().abs() * price.as_decimal() > Decimal::from(1e18) {\n    return Err(anyhow!(\"notional too large for margin calc\"));\n}","typeGuard":null,"tryCatchPattern":"match model.calculate_initial_margin(&inst, qty, price, use_quote) {\n    Ok(m) => m,\n    Err(e) if e.to_string().contains(\"overflow\") => { warn!(\"initial margin overflow: {e}\"); Money::zero(currency) }\n    Err(e) => return Err(e),\n}","preventionTips":["Bound quantity/price inputs from market data sanity checks","Keep margin_init rates in [0,1]","Never unwrap margin calculations in production paths"],"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"}