nautechsystems/nautilus_trader · error
Python on_load failed: {e}
Error message
Python on_load failed: {e} What it means
The strategy's Python-level `on_load` callback raised an exception. `dispatch_on_load()` (strategy.rs:396) converts the saved `IndexMap<String, Vec<u8>>` state to a Python dict via `state_to_pydict` and calls `on_load(py_state)`; any Python exception is wrapped at strategy.rs:1101 as `Python on_load failed: {e}`. The cause is inside the user's `on_load` (or, less commonly, in the state-to-dict conversion).
Source
Thrown at crates/trading/src/python/strategy.rs:1101
fn on_degrade(&mut self) -> anyhow::Result<()> {
self.dispatch_on_degrade()
.map_err(|e| anyhow::anyhow!("Python on_degrade failed: {e}"))
}
fn on_fault(&mut self) -> anyhow::Result<()> {
self.dispatch_on_fault()
.map_err(|e| anyhow::anyhow!("Python on_fault failed: {e}"))
}
fn on_save(&self) -> anyhow::Result<IndexMap<String, Vec<u8>>> {
self.dispatch_on_save()
.map_err(|e| anyhow::anyhow!("Python on_save failed: {e}"))
}
fn on_load(&mut self, state: IndexMap<String, Vec<u8>>) -> anyhow::Result<()> {
self.dispatch_on_load(&state)
.map_err(|e| anyhow::anyhow!("Python on_load failed: {e}"))
}
fn on_time_event(&mut self, event: &TimeEvent) -> anyhow::Result<()> {
route_time_event(self, event);
self.dispatch_on_time_event(event)
.map_err(|e| anyhow::anyhow!("Python on_time_event failed: {e}"))
}
#[allow(unused_variables)]
fn on_data(&mut self, data: &CustomData) -> anyhow::Result<()> {
Python::attach(|py| {
let py_data: Py<PyAny> = Py::new(py, data.clone())?.into_any();
self.dispatch_on_data(py_data)
.map_err(|e| anyhow::anyhow!("Python on_data failed: {e}"))
})
}
fn on_signal(&mut self, signal: &Signal) -> anyhow::Result<()> {View on GitHub (pinned to 18893faf8b)
Solutions
- Read `{e}` for the underlying Python error; usually a decode/unpickle error or missing key in the passed state dict.
- Use `.get(key, default)` for every state key in `on_load` so old snapshots load cleanly.
- Decode bytes with the exact codec used in `on_save` (e.g. `bytes.decode("utf-8")`), and version your saved state.
- Write a round-trip test: run `on_save`, feed the result to `on_load` on a fresh strategy instance.
Example fix
// before
def on_load(self, state):
self.position_qty = Decimal(state["position"].decode()) # KeyError on old snapshots
// after
def on_load(self, state):
raw = state.get("position")
self.position_qty = Decimal(raw.decode()) if raw is not None else Decimal(0) Defensive patterns
Strategy: validation
Validate before calling
def validate_state_for_load(state):
required = {"position"} # keys your on_load needs
missing = required - set(state)
assert not missing, f"snapshot missing keys: {missing}"
for v in state.values():
assert isinstance(v, (bytes, bytearray)) Type guard
def loadable(state, required_keys):
return isinstance(state, dict) and required_keys.issubset(state) and all(
isinstance(v, (bytes, bytearray)) for v in state.values()) Try / catch
try:
self.on_load(state)
except Exception as e:
self.log.error(f"state restore failed, starting fresh: {e}")
self._init_default_state() Prevention
- Use state.get(key, default) for every key so old snapshots load.
- Version your saved state and include a schema version key.
- Round-trip test: on_save -> on_load on a fresh instance in CI.
- Match decode codec exactly with what on_save encoded.
When it happens
Trigger: Restoring a saved snapshot: the framework calls `on_load(state)` with a dict of bytes values; the Python method raises, e.g. by decoding bytes with the wrong codec, unpickling data written by an older schema, or assuming a key exists in the loaded state.
Common situations: Loading state saved by a previous strategy version (schema drift / missing keys); `json.loads` or `pickle.loads` on bytes that were saved differently; `KeyError` on a state key; trying to mutate frozen/None attributes during load.
Related errors
- Invalid `strategy_id` type
- Failed to extract PyStrategy: {e}
- Failed to import json: {e}
- Failed to parse JSON: {e}
- Failed to call from_json: {e}
AI-assisted analysis of nautechsystems/nautilus_trader@18893faf8b (2026-09-08).
Data as JSON: /api/errors/0f67a69d9d8820c7.
Report an issue: GitHub.