nautechsystems/nautilus_trader · error

Python on_trade failed: {e}

Error message

Python on_trade failed: {e}

What it means

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.

Source

Thrown at crates/trading/src/python/strategy.rs:1150

    }

    fn on_instrument(&mut self, instrument: &InstrumentAny) -> anyhow::Result<()> {
        Python::attach(|py| {
            let py_instrument = instrument_any_to_pyobject(py, instrument.clone())
                .map_err(|e| anyhow::anyhow!("Failed to convert InstrumentAny to Python: {e}"))?;
            self.dispatch_on_instrument(py_instrument)
                .map_err(|e| anyhow::anyhow!("Python on_instrument failed: {e}"))
        })
    }

    fn on_quote(&mut self, quote: &QuoteTick) -> anyhow::Result<()> {
        self.dispatch_on_quote(*quote)
            .map_err(|e| anyhow::anyhow!("Python on_quote failed: {e}"))
    }

    fn on_trade(&mut self, tick: &TradeTick) -> anyhow::Result<()> {
        self.dispatch_on_trade(*tick)
            .map_err(|e| anyhow::anyhow!("Python on_trade failed: {e}"))
    }

    fn on_bar(&mut self, bar: &Bar) -> anyhow::Result<()> {
        self.dispatch_on_bar(*bar)
            .map_err(|e| anyhow::anyhow!("Python on_bar failed: {e}"))
    }

    fn on_book_deltas(&mut self, deltas: &OrderBookDeltas) -> anyhow::Result<()> {
        self.dispatch_on_book_deltas(deltas)
            .map_err(|e| anyhow::anyhow!("Python on_book_deltas failed: {e}"))
    }

    fn on_book_depth(&mut self, depth: &OrderBookDepth10) -> anyhow::Result<()> {
        self.dispatch_on_book_depth(depth)
            .map_err(|e| anyhow::anyhow!("Python on_book_depth failed: {e}"))
    }

    fn on_book(&mut self, order_book: &OrderBook) -> anyhow::Result<()> {

View on GitHub (pinned to 18893faf8b)

Solutions

  1. Read the chained `{e}` traceback to locate the failing line in the Python `on_trade`.
  2. Add guards for optional tick fields (aggressor_side, trade_info) before use.
  3. Wrap handler logic in try/except and log skipped ticks.
  4. Replay the session data around the failing tick to reproduce and fix.

Example fix

# before
def on_trade(self, tick):
    info = tick.trade_info['trade_condition']  # KeyError when trade_info empty

# after
def on_trade(self, tick):
    condition = (tick.trade_info or {}).get('trade_condition')
    if condition is None:
        return
Defensive patterns

Strategy: validation

Validate before calling

def trade_tick_complete(tick):
    return tick.price is not None and tick.size is not None and tick.trade_id is not None

Type guard

def has_trade_info(tick):
    return bool(getattr(tick, 'trade_info', None))

Try / catch

def on_trade(self, tick):
    try:
        self._on_trade(tick)
    except Exception as e:
        self.log.error(f"on_trade failed for {tick.instrument_id}: {e}", exc_info=True)

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of nautechsystems/nautilus_trader@18893faf8b (2026-09-08). Data as JSON: /api/errors/71a13ea87e0b0c8e. Report an issue: GitHub.