{"record":{"id":"84960ba42ad4ab7e","repo":"nautechsystems/nautilus_trader","slug":"python-on-bar-failed-e-84960b","errorCode":null,"errorMessage":"Python on_bar failed: {e}","messagePattern":"Python on_bar failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/trading/src/python/strategy.rs","lineNumber":1155,"sourceCode":"                .map_err(|e| anyhow::anyhow!(\"Failed to convert InstrumentAny to Python: {e}\"))?;\n            self.dispatch_on_instrument(py_instrument)\n                .map_err(|e| anyhow::anyhow!(\"Python on_instrument failed: {e}\"))\n        })\n    }\n\n    fn on_quote(&mut self, quote: &QuoteTick) -> anyhow::Result<()> {\n        self.dispatch_on_quote(*quote)\n            .map_err(|e| anyhow::anyhow!(\"Python on_quote failed: {e}\"))\n    }\n\n    fn on_trade(&mut self, tick: &TradeTick) -> anyhow::Result<()> {\n        self.dispatch_on_trade(*tick)\n            .map_err(|e| anyhow::anyhow!(\"Python on_trade failed: {e}\"))\n    }\n\n    fn on_bar(&mut self, bar: &Bar) -> anyhow::Result<()> {\n        self.dispatch_on_bar(*bar)\n            .map_err(|e| anyhow::anyhow!(\"Python on_bar failed: {e}\"))\n    }\n\n    fn on_book_deltas(&mut self, deltas: &OrderBookDeltas) -> anyhow::Result<()> {\n        self.dispatch_on_book_deltas(deltas)\n            .map_err(|e| anyhow::anyhow!(\"Python on_book_deltas failed: {e}\"))\n    }\n\n    fn on_book_depth(&mut self, depth: &OrderBookDepth10) -> anyhow::Result<()> {\n        self.dispatch_on_book_depth(depth)\n            .map_err(|e| anyhow::anyhow!(\"Python on_book_depth failed: {e}\"))\n    }\n\n    fn on_book(&mut self, order_book: &OrderBook) -> anyhow::Result<()> {\n        self.dispatch_on_book(order_book)\n            .map_err(|e| anyhow::anyhow!(\"Python on_book failed: {e}\"))\n    }\n\n    fn on_mark_price(&mut self, mark_price: &MarkPriceUpdate) -> anyhow::Result<()> {","sourceCodeStart":1137,"sourceCodeEnd":1173,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/trading/src/python/strategy.rs#L1137-L1173","documentation":"Wraps a Python exception raised inside the strategy's `on_bar` handler. `dispatch_on_bar` calls the user's Python `on_bar(self, bar)` for each `Bar` delivered by the Rust core; an unhandled exception is re-thrown as this anyhow error. It indicates user strategy code failed while processing an aggregated bar.","triggerScenarios":"Unhandled Python exception in `on_bar`: indicator update calls (e.g. feeding an uninitialized indicator), division by a zero bar close, lookups into deques/arrays shorter than expected on early bars, or `bar.close.as_double()` misuse after API changes.","commonSituations":"Indicator warm-up windows longer than the available history causing index errors; strategies assuming bars never have zero volume; version upgrades where Price/Quantity conversion helpers changed (e.g. `.as_double()` vs `float()`).","solutions":["Inspect the chained `{e}` traceback for the failing line in the Python `on_bar`.","Validate indicator warm-up length before indexing rolling buffers.","Wrap indicator updates in try/except during the first N bars.","Run a backtest over the same bar aggregation to reproduce offline."],"exampleFix":"# before\ndef on_bar(self, bar):\n    self.closes.append(bar.close)\n    avg = sum(self.closes[-self.window:]) / self.window  # short-buffer math errors early\n\n# after\ndef on_bar(self, bar):\n    self.closes.append(bar.close)\n    if len(self.closes) < self.window:\n        return\n    avg = sum(self.closes[-self.window:]) / self.window","handlingStrategy":"validation","validationCode":"# before using rolling state\ndef enough_history(closes, window):\n    return len(closes) >= window","typeGuard":"def is_valid_bar(bar):\n    return bar.open is not None and bar.high >= bar.low and bar.close is not None","tryCatchPattern":"def on_bar(self, bar):\n    try:\n        self._on_bar(bar)\n    except Exception as e:\n        self.log.error(f\"on_bar failed for {bar.bar_type}: {e}\", exc_info=True)","preventionTips":["Wait for indicator warm-up before reading rolling buffers","Validate bar integrity (high >= low, nonzero prices) before use","Pin and re-verify Price/Quantity conversion helpers after upgrades","Backtest with the exact bar aggregation used live"],"tags":["python","strategy","callback","bars"],"backgroundTag":"python-strategy-callback-failed","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"}