{"record":{"id":"836ba3097efe45fd","repo":"nautechsystems/nautilus_trader","slug":"cannot-calculate-slippage-the-spot-price-before-i","errorCode":null,"errorMessage":"Cannot calculate slippage, the spot price before is not set","messagePattern":"Cannot calculate slippage, the spot price before is not set","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/model/src/defi/data/swap_trade_info.rs","lineNumber":125,"sourceCode":"    /// deviation from the spot price before the swap. This measures the total\n    /// cost to the trader.\n    ///\n    /// # Returns\n    /// Total slippage in basis points (10000 = 100%)\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the spot price before the swap is not set or is zero.\n    pub fn get_slippage_bps(&self) -> anyhow::Result<u32> {\n        if let Some(spot_price_before) = self.spot_price_before {\n            Self::check_spot_price_before(spot_price_before, PriceMetric::Slippage)?;\n            let price_change = self.execution_price - spot_price_before;\n            let slippage =\n                (price_change.as_decimal() / spot_price_before.as_decimal()).abs() * dec!(10_000);\n\n            Ok(slippage.round().to_u32().unwrap_or(0))\n        } else {\n            anyhow::bail!(\"Cannot calculate slippage, the spot price before is not set\")\n        }\n    }\n\n    fn check_spot_price_before(\n        spot_price_before: Price,\n        metric: PriceMetric,\n    ) -> anyhow::Result<()> {\n        let metric = metric.name();\n        anyhow::ensure!(\n            !spot_price_before.is_zero(),\n            \"Cannot calculate {metric}, the spot price before is zero\"\n        );\n        Ok(())\n    }\n}\n\nenum PriceMetric {\n    Impact,","sourceCodeStart":107,"sourceCodeEnd":143,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/model/src/defi/data/swap_trade_info.rs#L107-L143","documentation":"SwapTradeInfo::get_slippage_bps computes slippage as (execution_price - spot_price_before)/spot_price_before * 10_000 bps. It needs a positive pre-swap spot price as the reference; if spot_price_before is zero/unset the method bails rather than divide by zero. The same guard backs the sibling price-impact calculation, and check_spot_price_before enforces it.","triggerScenarios":"Calling get_slippage_bps with spot_price_before set to zero or a default Price, e.g. when the pre-trade price was not derived from the swap's before-sqrt-price.","commonSituations":"Building SwapTradeInfo from partial event data missing the pre-swap price; replay scripts that start mid-stream; tests validating the zero-price rejection.","solutions":["Populate spot_price_before from the pool's price before the swap (from sqrt price before the tick crossing)","Skip or defer the slippage calculation when no valid pre-price is available","Add a validation step in SwapTradeInfo construction so callers cannot build it without a spot price before","Use check_spot_price_before / a zero check before invoking the method"],"exampleFix":"// before\nlet slippage = swap.get_slippage_bps(spot_before)?;\n// after\nanyhow::ensure!(!spot_before.is_zero(), \"spot price before must be positive\");\nlet slippage = swap.get_slippage_bps(spot_before)?;","handlingStrategy":"validation","validationCode":"if spot_price_before.is_zero() {\n    // slippage not computable without a reference price\n}","typeGuard":"fn slippage_computable(p: &Price) -> bool { !p.is_zero() }","tryCatchPattern":"match swap.get_slippage_bps(spot_before) {\n    Ok(bps) => Some(bps),\n    Err(e) if e.to_string().contains(\"spot price before is not set\") => None,\n    Err(e) => return Err(e),\n}","preventionTips":["Derive spot_price_before from before-swap sqrt price data at ingestion","Reject or skip swaps lacking a pre-trade reference price","Validate SwapTradeInfo at construction time","Handle the None/absent case explicitly in reporting code"],"tags":["rust","defi","swap","division-by-zero","slippage"],"backgroundTag":"invalid-argument-value","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}