{"record":{"id":"71a13ea87e0b0c8e","repo":"nautechsystems/nautilus_trader","slug":"python-on-trade-failed-e-71a13e","errorCode":null,"errorMessage":"Python on_trade failed: {e}","messagePattern":"Python on_trade failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/trading/src/python/strategy.rs","lineNumber":1150,"sourceCode":"    }\n\n    fn on_instrument(&mut self, instrument: &InstrumentAny) -> anyhow::Result<()> {\n        Python::attach(|py| {\n            let py_instrument = instrument_any_to_pyobject(py, instrument.clone())\n                .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<()> {","sourceCodeStart":1132,"sourceCodeEnd":1168,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/trading/src/python/strategy.rs#L1132-L1168","documentation":"Wraps a Python exception raised inside the strategy's `on_trade` handler. `dispatch_on_trade` invokes the user's Python `on_trade(self, tick)` for each `TradeTick` forwarded by the Rust core; any unhandled exception becomes this anyhow error. It signals user strategy code failed while processing a trade print.","triggerScenarios":"Unhandled Python exception in `on_trade`: e.g. calling `tick.aggressor_side.name()` on unexpected values, dict lookups keyed by trade_id that were deleted, indexing `tick.trade_info` when absent, or arithmetic on None fields.","commonSituations":"Strategy logic ported from a quote-based design that mishandles trade ticks; accessing venue-specific `trade_info` fields that some venues never populate; stats accumulators crashing on out-of-sequence ticks after a reconnect.","solutions":["Read the chained `{e}` traceback to locate the failing line in the Python `on_trade`.","Add guards for optional tick fields (aggressor_side, trade_info) before use.","Wrap handler logic in try/except and log skipped ticks.","Replay the session data around the failing tick to reproduce and fix."],"exampleFix":"# before\ndef on_trade(self, tick):\n    info = tick.trade_info['trade_condition']  # KeyError when trade_info empty\n\n# after\ndef on_trade(self, tick):\n    condition = (tick.trade_info or {}).get('trade_condition')\n    if condition is None:\n        return","handlingStrategy":"validation","validationCode":"def trade_tick_complete(tick):\n    return tick.price is not None and tick.size is not None and tick.trade_id is not None","typeGuard":"def has_trade_info(tick):\n    return bool(getattr(tick, 'trade_info', None))","tryCatchPattern":"def on_trade(self, tick):\n    try:\n        self._on_trade(tick)\n    except Exception as e:\n        self.log.error(f\"on_trade failed for {tick.instrument_id}: {e}\", exc_info=True)","preventionTips":["Treat aggressor_side and trade_info as optional","Key state by instrument_id and initialize lazily","Replay recorded trade data in backtests before going live","Do not assume trade ordering or deduplication from the venue"],"tags":["python","strategy","callback","market-data"],"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-14T00:17:10.932Z"}