{"record":{"id":"2333d4536214d71f","repo":"nautechsystems/nautilus_trader","slug":"failed-to-downcast-to-pystrategy-e","errorCode":null,"errorMessage":"Failed to downcast to PyStrategy: {e}","messagePattern":"Failed to downcast to PyStrategy: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/system/src/python/registration.rs","lineNumber":320,"sourceCode":"                .map_err(|e| anyhow::anyhow!(\"Failed to extract PyStrategy: {e}\"))?;\n\n            py_strategy_ref\n                .register(trader_id, clock, cache, portfolio)\n                .map_err(|e| anyhow::anyhow!(\"Failed to register PyStrategy: {e}\"))?;\n\n            log::debug!(\n                \"Internal PyStrategy registered: {}\",\n                py_strategy_ref.is_registered()\n            );\n\n            Ok(())\n        })?;\n\n        Python::attach(|py| -> anyhow::Result<()> {\n            let py_strategy = strategy.bind(py);\n            let py_strategy_ref = py_strategy\n                .cast::<PyStrategy>()\n                .map_err(|e| anyhow::anyhow!(\"Failed to downcast to PyStrategy: {e}\"))?;\n            py_strategy_ref.borrow().register_in_global_registries()?;\n            Ok(())\n        })?;\n\n        self.add_strategy_id_with_subscriptions::<PyStrategyInner>(strategy_id)\n    }\n\n    /// Adds a constructed [`PyExecutionAlgorithm`] instance to the trader.\n    ///\n    /// `wrapper` is the Python object which owns `algorithm`; the trader's registries keep it\n    /// alive for as long as the algorithm stays registered.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the trader already tracks a component under the algorithm's ID, or if\n    /// the algorithm cannot be registered or tracked.\n    pub fn add_py_execution_algorithm_instance(\n        &mut self,","sourceCodeStart":302,"sourceCodeEnd":338,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/system/src/python/registration.rs#L302-L338","documentation":"After registration, the code `cast::<PyStrategy>()`s the object to borrow it as the concrete Rust type and call `register_in_global_registries()`. A cast failure means the bound object is not actually a PyStrategy at the Rust level, and the error reports this downcast failure.","triggerScenarios":"Registration of a strategy object that passed earlier steps but cannot be cast to the concrete `PyStrategy` class — typically a subclass whose PyO3 class identity differs (duplicate/reloaded module) or a non-strategy object reaching this path.","commonSituations":"Strategy classes defined in a module that was reloaded after nautilus_trader imported its Rust class; multiple nautilus_trader builds on sys.path creating two distinct PyStrategy classes.","solutions":["Ensure only one nautilus_trader installation exists (`pip show nautilus_trader`, clean site-packages).","Avoid `importlib.reload` of strategy modules that subclass the Rust-backed Strategy within a running process.","Pass the strategy instance created from the same nautilus_trader import used by the trader."],"exampleFix":"// before\nimport importlib, my_strats\nimportlib.reload(my_strats)  # creates a NEW Strategy subclass identity\n\n// after\nimport my_strats  # import once per process; no reload after trader setup","handlingStrategy":"validation","validationCode":"import sys\npaths = [p for p in sys.path if \"site-packages\" in p]\nassert len({p.split(\"/\")[3] for p in paths}) >= 1  # inspect for duplicate installs\nfrom nautilus_trader.trading.strategy import Strategy\nassert isinstance(strategy, Strategy)","typeGuard":"def same_class_identity(obj) -> bool:\n    from nautilus_trader.trading.strategy import Strategy\n    return type(obj).__mro__[-2:] == Strategy.__mro__[-2:] or isinstance(obj, Strategy)","tryCatchPattern":"try:\n    trader.add_strategy(strategy)\nexcept Exception as e:\n    if \"downcast\" in str(e):\n        logging.error(\"Class identity mismatch — reload process or dedupe nautilus_trader installs\")\n    raise","preventionTips":["Never importlib.reload modules that subclass Rust-backed classes in a live process.","Check `pip list | grep nautilus` for duplicate/conflicting builds.","Create strategies within the same process that imported nautilus_trader."],"tags":["python","pyo3","downcast","strategy"],"backgroundTag":"type-mismatch","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}