{"record":{"id":"e1e18d9673d64e8c","repo":"nautechsystems/nautilus_trader","slug":"python-on-data-failed-e-e1e18d","errorCode":null,"errorMessage":"Python on_data failed: {e}","messagePattern":"Python on_data failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/trading/src/python/strategy.rs","lineNumber":1115,"sourceCode":"    }\n\n    fn on_load(&mut self, state: IndexMap<String, Vec<u8>>) -> anyhow::Result<()> {\n        self.dispatch_on_load(&state)\n            .map_err(|e| anyhow::anyhow!(\"Python on_load failed: {e}\"))\n    }\n\n    fn on_time_event(&mut self, event: &TimeEvent) -> anyhow::Result<()> {\n        route_time_event(self, event);\n        self.dispatch_on_time_event(event)\n            .map_err(|e| anyhow::anyhow!(\"Python on_time_event failed: {e}\"))\n    }\n\n    #[allow(unused_variables)]\n    fn on_data(&mut self, data: &CustomData) -> anyhow::Result<()> {\n        Python::attach(|py| {\n            let py_data: Py<PyAny> = Py::new(py, data.clone())?.into_any();\n            self.dispatch_on_data(py_data)\n                .map_err(|e| anyhow::anyhow!(\"Python on_data failed: {e}\"))\n        })\n    }\n\n    fn on_signal(&mut self, signal: &Signal) -> anyhow::Result<()> {\n        self.dispatch_on_signal(signal)\n            .map_err(|e| anyhow::anyhow!(\"Python on_signal failed: {e}\"))\n    }\n\n    fn on_queue_state(&mut self, event: &QueueStateChanged) -> anyhow::Result<()> {\n        self.dispatch_on_queue_state(event)\n            .map_err(|e| anyhow::anyhow!(\"Python on_queue_state failed: {e}\"))\n    }\n\n    fn on_socket_state(&mut self, event: &SocketStateChanged) -> anyhow::Result<()> {\n        self.dispatch_on_socket_state(event)\n            .map_err(|e| anyhow::anyhow!(\"Python on_socket_state failed: {e}\"))\n    }\n","sourceCodeStart":1097,"sourceCodeEnd":1133,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/trading/src/python/strategy.rs#L1097-L1133","documentation":"The strategy's Python-level `on_data` callback raised an exception while processing custom data. The Rust hook clones the `CustomData` into a Python object (`Py::new`) and calls `dispatch_on_data`; a failure in either creating the Py object or in the Python handler is wrapped at strategy.rs:1115 as `Python on_data failed: {e}`.","triggerScenarios":"Custom data (e.g. from a user-defined data type subscribed via `subscribe_data`) arrives and is delivered to `on_data`; the Python method raises while unpacking/parsing the payload, or `Py::new` fails if the data type is not correctly registered as a pyo3-compatible class.","commonSituations":"Parsing raw custom-data payloads with a schema that changed upstream; assuming fields exist on the custom object; incorrect msgspec/dataclass definition of the custom data type causing conversion failures; exceptions in ML inference or external calls inside `on_data`.","solutions":["Read `{e}`: if it mentions object creation, check the custom data type's Python class registration; otherwise fix the handler parsing code.","Validate/defensively parse the custom data fields in `on_data` before use.","Confirm the published data schema matches what `on_data` unpacks (producer and consumer versions agree).","Wrap handler logic in try/except with logging so one bad message doesn't stop processing subsequent data."],"exampleFix":"// before\ndef on_data(self, data):\n    price, qty = data.value.split(\",\")  # ValueError when upstream adds a field\n\n// after\ndef on_data(self, data):\n    parts = data.value.split(\",\")\n    if len(parts) < 2:\n        self.log.warning(f\"malformed custom data: {data.value!r}\")\n        return\n    price, qty = parts[0], parts[1]","handlingStrategy":"validation","validationCode":"def validate_custom_data(data, required_fields):\n    missing = [f for f in required_fields if not hasattr(data, f)]\n    if missing:\n        raise AttributeError(f\"custom data missing fields: {missing}\")","typeGuard":"def is_parseable(data):\n    return hasattr(data, \"value\") and isinstance(data.value, (str, bytes)) and len(data.value) > 0","tryCatchPattern":"def on_data(self, data):\n    try:\n        self._handle(data)\n    except Exception as e:\n        self.log.error(f\"custom data handling failed for {data!r}: {e}\")","preventionTips":["Validate custom-data fields before unpacking; treat upstream schema as unstable.","Keep producer and consumer data-type definitions in one shared module.","Unit-test on_data with malformed payloads.","Confirm the custom data class is properly pyo3/msgspec registered."],"tags":["python","strategy","custom-data","callback"],"backgroundTag":"python-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"}