nautechsystems/nautilus_trader · error

Python on_instrument_close failed: {e}

Error message

Python on_instrument_close failed: {e}

What it means

This error wraps any Python exception raised inside the actor's `on_instrument_close` callback when an `InstrumentClose` event is delivered to the Python subclass. The Rust `PyDataActor` calls the Python method via `call_method1` and converts the resulting `PyErr` into an anyhow error with this message. The real failure is in the user's Python handler or the Rust-to-Python conversion of the event.

Source

Thrown at crates/common/src/python/actor.rs:1153

    fn on_index_price(&mut self, index_price: &IndexPriceUpdate) -> anyhow::Result<()> {
        self.dispatch_on_index_price(*index_price)
            .map_err(|e| anyhow::anyhow!("Python on_index_price failed: {e}"))
    }

    fn on_funding_rate(&mut self, funding_rate: &FundingRateUpdate) -> anyhow::Result<()> {
        self.dispatch_on_funding_rate(*funding_rate)
            .map_err(|e| anyhow::anyhow!("Python on_funding_rate failed: {e}"))
    }

    fn on_instrument_status(&mut self, data: &InstrumentStatus) -> anyhow::Result<()> {
        self.dispatch_on_instrument_status(*data)
            .map_err(|e| anyhow::anyhow!("Python on_instrument_status failed: {e}"))
    }

    fn on_instrument_close(&mut self, update: &InstrumentClose) -> anyhow::Result<()> {
        self.dispatch_on_instrument_close(*update)
            .map_err(|e| anyhow::anyhow!("Python on_instrument_close failed: {e}"))
    }

    fn on_option_greeks(&mut self, greeks: &OptionGreeks) -> anyhow::Result<()> {
        self.dispatch_on_option_greeks(*greeks)
            .map_err(|e| anyhow::anyhow!("Python on_option_greeks failed: {e}"))
    }

    fn on_option_chain(&mut self, slice: &OptionChainSlice) -> anyhow::Result<()> {
        self.dispatch_on_option_chain(slice.clone())
            .map_err(|e| anyhow::anyhow!("Python on_option_chain failed: {e}"))
    }

    #[cfg(feature = "defi")]
    fn on_block(&mut self, block: &Block) -> anyhow::Result<()> {
        self.dispatch_on_block(block.clone())
            .map_err(|e| anyhow::anyhow!("Python on_block failed: {e}"))
    }

View on GitHub (pinned to 18893faf8b)

Solutions

  1. Inspect the Python traceback appended after 'Python on_instrument_close failed:' to find the raising line.
  2. Make the handler idempotent: check the instrument exists in strategy state before cleanup.
  3. Verify InstrumentClose field names against the installed nautilus_trader version.
  4. Clean up subscriptions/state defensively (use .pop/.get with defaults).

Example fix

// before
def on_instrument_close(self, update):
    self.subs.pop(update.instrument_id.value)
    del self.books[update.instrument_id.value]

// after
def on_instrument_close(self, update):
    iid = str(update.instrument_id)
    self.subs.pop(iid, None)
    self.books.pop(iid, None)
Defensive patterns

Strategy: validation

Validate before calling

iid = str(update.instrument_id)
if iid not in self.books and iid not in self.subs:
    return  # nothing to clean up

Type guard

def is_tracked_close(update, state):
    return str(getattr(update, "instrument_id", "")) in state.tracked

Try / catch

def on_instrument_close(self, update):
    try:
        self._cleanup(update)
    except Exception as e:
        self.log.error(f"on_instrument_close failed: {e}", exc_info=True)

Prevention

When it happens

Trigger: Any exception raised by the user's `on_instrument_close(self, update)` override — e.g. closing positions for an instrument not tracked in the strategy's state, removing from a list while iterating, or dereferencing fields absent from the converted InstrumentClose.

Common situations: Exchanges delisting or closing instruments mid-session while a strategy still holds subscriptions; handlers that assume a close always follows an open for the same instrument_id; stale version assumptions after a nautilus_trader upgrade.

Related errors


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