1use std::{cell::RefCell, collections::HashMap, rc::Rc};
26
27use nautilus_common::{
28 actor::{DataActorNative, data_actor::ImportableActorConfig},
29 python::{
30 actor::{
31 PyDataActor, PyDataActorInner, prepare_python_actor,
32 register_python_exec_algorithm_endpoint,
33 },
34 wrappers::retain_python_wrapper,
35 },
36};
37use nautilus_model::identifiers::{
38 ActorId, ComponentId, ExecAlgorithmId, StrategyId, normalize_order_id_tag,
39};
40use nautilus_trading::{
41 ImportableControllerConfig, ImportableStrategyConfig,
42 python::{
43 algorithm::PyExecutionAlgorithm,
44 strategy::{PyStrategy, PyStrategyInner},
45 },
46};
47use pyo3::{
48 prelude::*,
49 types::{PyDict, PyModule},
50};
51
52use crate::{
53 registration::{ensure_unique_order_id_tag, next_order_id_tag},
54 trader::Trader,
55};
56
57impl Trader {
58 pub fn add_actor_from_importable_config(
64 &mut self,
65 config: &ImportableActorConfig,
66 ) -> anyhow::Result<ActorId> {
67 self.validate_actor_or_strategy_registration()?;
68
69 let (python_actor, actor_id) = create_python_actor(config)?;
70 if self.actor_ids.contains(&actor_id) {
71 anyhow::bail!("Actor {actor_id} is already registered");
72 }
73
74 self.add_python_actor_instance(&python_actor, actor_id)?;
75
76 log::info!(
77 "Registered Python actor {actor_id} with trader {}",
78 self.trader_id
79 );
80 Ok(actor_id)
81 }
82
83 pub fn add_python_actor_instance(
93 &mut self,
94 actor: &Py<PyAny>,
95 actor_id: ActorId,
96 ) -> anyhow::Result<()> {
97 let component_id = ComponentId::from(actor_id);
98 self.ensure_component_id_available(component_id)?;
99
100 if let Err(e) = self.register_python_actor_components(actor, actor_id) {
101 self.release_component(component_id);
103 return Err(e);
104 }
105
106 Ok(())
107 }
108
109 fn register_python_actor_components(
110 &mut self,
111 actor: &Py<PyAny>,
112 actor_id: ActorId,
113 ) -> anyhow::Result<()> {
114 self.register_python_data_actor(actor, ComponentId::from(actor_id))?;
115
116 self.add_actor_id_for_lifecycle::<PyDataActorInner>(actor_id)
117 }
118
119 pub fn add_controller_from_importable_config(
125 trader: &Rc<RefCell<Self>>,
126 config: &ImportableControllerConfig,
127 ) -> anyhow::Result<ActorId> {
128 trader.borrow().validate_actor_or_strategy_registration()?;
129
130 let actor_config = ImportableActorConfig {
131 actor_path: config.controller_path.clone(),
132 config_path: config.config_path.clone(),
133 config: config.config.clone(),
134 };
135 let (python_controller, actor_id) = create_python_actor(&actor_config)?;
136 if trader.borrow().actor_ids.contains(&actor_id) {
137 anyhow::bail!("Actor {actor_id} is already registered");
138 }
139
140 crate::python::controller::bind_controller_trader(&python_controller, trader)?;
141
142 trader
143 .borrow_mut()
144 .add_python_actor_instance(&python_controller, actor_id)?;
145
146 log::info!(
147 "Registered Python controller {actor_id} with trader {}",
148 trader.borrow().trader_id
149 );
150 Ok(actor_id)
151 }
152
153 pub fn add_strategy_from_importable_config(
159 &mut self,
160 config: &ImportableStrategyConfig,
161 ) -> anyhow::Result<StrategyId> {
162 self.validate_actor_or_strategy_registration()?;
165
166 let python_strategy = create_python_strategy(config)?;
167
168 self.add_python_strategy_instance(&python_strategy)
169 }
170
171 pub fn add_python_strategy_instance(
182 &mut self,
183 strategy: &Py<PyAny>,
184 ) -> anyhow::Result<StrategyId> {
185 self.prepare_python_strategy_instance(strategy)?;
186 self.commit_python_strategy_instance(strategy)
187 }
188
189 pub fn prepare_python_strategy_instance(
196 &mut self,
197 strategy: &Py<PyAny>,
198 ) -> anyhow::Result<StrategyId> {
199 self.validate_actor_or_strategy_registration()?;
200
201 let existing_order_id_tags: Vec<&str> =
202 self.strategy_ids.iter().map(StrategyId::get_tag).collect();
203
204 let strategy_id = Python::attach(|py| -> anyhow::Result<StrategyId> {
205 let bound = strategy.bind(py);
206
207 let config_instance = bound
208 .getattr("config")
209 .ok()
210 .filter(|config| !config.is_none());
211
212 let class_name = bound.get_type().name()?.to_string();
213
214 let mut py_strategy_ref = bound
215 .extract::<PyRefMut<PyStrategy>>()
216 .map_err(Into::<PyErr>::into)
217 .map_err(|e| anyhow::anyhow!("Failed to extract PyStrategy: {e}"))?;
218
219 if let Some(config_obj) = config_instance.as_ref() {
220 configure_py_strategy(&mut py_strategy_ref, config_obj)?;
221 }
222
223 let runtime_order_id_tag = py_strategy_ref.order_id_tag();
226 let strategy_id = if let Some(strategy_id) = py_strategy_ref.configured_strategy_id() {
227 strategy_id
228 } else {
229 let order_id_tag = normalize_order_id_tag(runtime_order_id_tag.as_deref())
230 .map_or_else(
231 || next_order_id_tag(&existing_order_id_tags),
232 str::to_string,
233 );
234 StrategyId::new_checked(format!("{class_name}-{order_id_tag}"))?
235 };
236
237 if self.strategy_ids.contains(&strategy_id) {
238 anyhow::bail!("Strategy {strategy_id} is already registered");
239 }
240 ensure_unique_order_id_tag(&existing_order_id_tags, strategy_id.get_tag())?;
241
242 py_strategy_ref.set_strategy_id(strategy_id)?;
243 py_strategy_ref.set_python_instance(bound)?;
244
245 Ok(py_strategy_ref.strategy_id())
246 })?;
247
248 self.ensure_component_id_available(ComponentId::from(strategy_id))?;
251
252 Ok(strategy_id)
253 }
254
255 pub fn commit_python_strategy_instance(
262 &mut self,
263 strategy: &Py<PyAny>,
264 ) -> anyhow::Result<StrategyId> {
265 let strategy_id = Python::attach(|py| -> anyhow::Result<StrategyId> {
266 Ok(strategy
267 .bind(py)
268 .extract::<PyRef<PyStrategy>>()
269 .map_err(Into::<PyErr>::into)
270 .map_err(|e| anyhow::anyhow!("Failed to extract PyStrategy: {e}"))?
271 .strategy_id())
272 })?;
273
274 let component_id = ComponentId::from(strategy_id);
275 self.ensure_component_id_available(component_id)?;
276
277 if let Err(e) = self.register_python_strategy_components(strategy, strategy_id) {
278 self.release_component(component_id);
280 return Err(e);
281 }
282
283 log::info!(
284 "Registered Python strategy {strategy_id} with trader {}",
285 self.trader_id
286 );
287 Ok(strategy_id)
288 }
289
290 fn register_python_strategy_components(
291 &mut self,
292 strategy: &Py<PyAny>,
293 strategy_id: StrategyId,
294 ) -> anyhow::Result<()> {
295 let clock = self.create_component_clock(ComponentId::from(strategy_id));
296 let trader_id = self.trader_id;
297 let cache = self.cache.clone();
298 let portfolio = self.portfolio.clone();
299
300 Python::attach(|py| -> anyhow::Result<()> {
301 let py_strategy = strategy.bind(py);
302 let mut py_strategy_ref = py_strategy
303 .extract::<PyRefMut<PyStrategy>>()
304 .map_err(Into::<PyErr>::into)
305 .map_err(|e| anyhow::anyhow!("Failed to extract PyStrategy: {e}"))?;
306
307 py_strategy_ref
308 .register(trader_id, clock, cache, portfolio)
309 .map_err(|e| anyhow::anyhow!("Failed to register PyStrategy: {e}"))?;
310
311 log::debug!(
312 "Internal PyStrategy registered: {}",
313 py_strategy_ref.is_registered()
314 );
315
316 Ok(())
317 })?;
318
319 Python::attach(|py| -> anyhow::Result<()> {
320 let py_strategy = strategy.bind(py);
321 let py_strategy_ref = py_strategy
322 .cast::<PyStrategy>()
323 .map_err(|e| anyhow::anyhow!("Failed to downcast to PyStrategy: {e}"))?;
324 py_strategy_ref.borrow().register_in_global_registries()?;
325 Ok(())
326 })?;
327
328 self.add_strategy_id_with_subscriptions::<PyStrategyInner>(strategy_id)
329 }
330
331 pub fn add_py_execution_algorithm_instance(
341 &mut self,
342 algorithm: PyExecutionAlgorithm,
343 wrapper: &Py<PyAny>,
344 ) -> anyhow::Result<ExecAlgorithmId> {
345 let exec_algorithm_id = algorithm.exec_algorithm_id();
346
347 if self.exec_algorithm_ids.contains(&exec_algorithm_id) {
349 anyhow::bail!("Execution algorithm '{exec_algorithm_id}' is already registered");
350 }
351
352 let component_id = ComponentId::from(exec_algorithm_id);
353 self.ensure_component_id_available(component_id)?;
354
355 let message_bus = algorithm.core().message_bus();
356 if let Err(e) = self.add_exec_algorithm(algorithm) {
357 self.release_component(component_id);
359 return Err(e);
360 }
361
362 Python::attach(|py| {
363 retain_python_wrapper(component_id, wrapper.clone_ref(py), message_bus);
364 });
365
366 Ok(exec_algorithm_id)
367 }
368
369 pub fn add_python_exec_algorithm_instance(
379 &mut self,
380 exec_algorithm: &Py<PyAny>,
381 actor_id: ActorId,
382 ) -> anyhow::Result<ExecAlgorithmId> {
383 let exec_algorithm_id = ExecAlgorithmId::new(actor_id.inner());
384
385 if self.exec_algorithm_ids.contains(&exec_algorithm_id) {
386 anyhow::bail!("Execution algorithm '{exec_algorithm_id}' is already registered");
387 }
388
389 let component_id = ComponentId::from(exec_algorithm_id);
390 self.ensure_component_id_available(component_id)?;
391
392 if let Err(e) =
393 self.register_python_exec_algorithm_components(exec_algorithm, exec_algorithm_id)
394 {
395 self.release_component(component_id);
397 return Err(e);
398 }
399
400 Ok(exec_algorithm_id)
401 }
402
403 fn register_python_exec_algorithm_components(
404 &mut self,
405 exec_algorithm: &Py<PyAny>,
406 exec_algorithm_id: ExecAlgorithmId,
407 ) -> anyhow::Result<()> {
408 self.register_python_data_actor(exec_algorithm, ComponentId::from(exec_algorithm_id))?;
409
410 self.add_exec_algorithm_id_for_lifecycle(exec_algorithm_id)?;
411
412 register_python_exec_algorithm_endpoint(exec_algorithm_id);
414
415 Ok(())
416 }
417
418 fn register_python_data_actor(
421 &mut self,
422 actor: &Py<PyAny>,
423 component_id: ComponentId,
424 ) -> anyhow::Result<()> {
425 let clock = self.create_component_clock(component_id);
426 let trader_id = self.trader_id;
427 let cache = self.cache.clone();
428
429 Python::attach(|py| -> anyhow::Result<()> {
430 let py_actor = actor.bind(py);
431 let mut py_data_actor_ref = py_actor
432 .extract::<PyRefMut<PyDataActor>>()
433 .map_err(Into::<PyErr>::into)
434 .map_err(|e| anyhow::anyhow!("Failed to extract PyDataActor: {e}"))?;
435
436 py_data_actor_ref
437 .register(trader_id, clock, cache)
438 .map_err(|e| anyhow::anyhow!("Failed to register PyDataActor: {e}"))?;
439
440 log::debug!(
441 "Internal PyDataActor registered: {}, state: {:?}",
442 py_data_actor_ref.is_registered(),
443 py_data_actor_ref.state()
444 );
445
446 Ok(())
447 })?;
448
449 Python::attach(|py| -> anyhow::Result<()> {
450 let py_actor = actor.bind(py);
451 let py_data_actor_ref = py_actor
452 .cast::<PyDataActor>()
453 .map_err(|e| anyhow::anyhow!("Failed to downcast to PyDataActor: {e}"))?;
454 py_data_actor_ref.borrow().register_in_global_registries()?;
455 Ok(())
456 })
457 }
458}
459
460fn create_python_actor(config: &ImportableActorConfig) -> anyhow::Result<(Py<PyAny>, ActorId)> {
461 let (module_name, class_name) = split_import_path(&config.actor_path, "actor_path")?;
462
463 log::info!("Importing actor from module: {module_name} class: {class_name}");
464
465 Python::attach(|py| -> anyhow::Result<(Py<PyAny>, ActorId)> {
466 let actor_class = import_python_class(py, module_name, class_name)?;
467 let config_instance = create_config_instance(py, &config.config_path, &config.config)?;
468
469 let python_actor = if let Some(config_obj) = config_instance.as_ref() {
470 actor_class.call1((config_obj,))?
471 } else {
472 actor_class.call0()?
473 };
474
475 let actor_id = prepare_python_actor(&python_actor, config_instance.as_ref())?;
476
477 Ok((python_actor.unbind(), actor_id))
478 })
479}
480
481fn create_python_strategy(config: &ImportableStrategyConfig) -> anyhow::Result<Py<PyAny>> {
482 let (module_name, class_name) = split_import_path(&config.strategy_path, "strategy_path")?;
483
484 log::info!("Importing strategy from module: {module_name} class: {class_name}");
485
486 Python::attach(|py| -> anyhow::Result<Py<PyAny>> {
487 let strategy_class = import_python_class(py, module_name, class_name)?;
488 let config_instance = create_config_instance(py, &config.config_path, &config.config)?;
489
490 let python_strategy = if let Some(config_obj) = config_instance.as_ref() {
491 strategy_class.call1((config_obj,))?
492 } else {
493 strategy_class.call0()?
494 };
495
496 Ok(python_strategy.unbind())
497 })
498}
499
500fn split_import_path<'a>(path: &'a str, field: &str) -> anyhow::Result<(&'a str, &'a str)> {
501 let Some((module_name, class_name)) = path.split_once(':') else {
502 anyhow::bail!("{field} must be in format 'module.path:ClassName'");
503 };
504
505 if module_name.is_empty() || class_name.is_empty() || class_name.contains(':') {
506 anyhow::bail!("{field} must be in format 'module.path:ClassName'");
507 }
508
509 Ok((module_name, class_name))
510}
511
512fn import_python_class<'py>(
513 py: Python<'py>,
514 module_name: &str,
515 class_name: &str,
516) -> anyhow::Result<Bound<'py, PyAny>> {
517 let module = py
518 .import(module_name)
519 .map_err(|e| anyhow::anyhow!("Failed to import module {module_name}: {e}"))?;
520
521 module
522 .getattr(class_name)
523 .map_err(|e| anyhow::anyhow!("Failed to get class {class_name}: {e}"))
524}
525
526fn create_config_instance<'py>(
527 py: Python<'py>,
528 config_path: &str,
529 config: &HashMap<String, serde_json::Value>,
530) -> anyhow::Result<Option<Bound<'py, PyAny>>> {
531 if config_path.is_empty() && config.is_empty() {
532 log::debug!("No config_path or empty config, using None");
533 return Ok(None);
534 }
535
536 let Some((config_module_name, config_class_name)) = config_path.split_once(':') else {
537 anyhow::bail!("config_path must be in format 'module.path:ClassName', was {config_path}");
538 };
539
540 if config_module_name.is_empty()
541 || config_class_name.is_empty()
542 || config_class_name.contains(':')
543 {
544 anyhow::bail!("config_path must be in format 'module.path:ClassName', was {config_path}");
545 }
546
547 log::debug!(
548 "Importing config class from module: {config_module_name} class: {config_class_name}"
549 );
550
551 let config_module = py
552 .import(config_module_name)
553 .map_err(|e| anyhow::anyhow!("Failed to import config module {config_module_name}: {e}"))?;
554 let config_class = config_module
555 .getattr(config_class_name)
556 .map_err(|e| anyhow::anyhow!("Failed to get config class {config_class_name}: {e}"))?;
557 let py_dict = PyDict::new(py);
558
559 for (key, value) in config {
560 let py_value = config_value_to_py(py, key, value)?;
561 py_dict.set_item(key, py_value)?;
562 }
563
564 let config_instance = match config_class.call((), Some(&py_dict)) {
565 Ok(instance) => instance,
566 Err(kwargs_err) => match config_class.call0() {
567 Ok(instance) => {
568 for (key, value) in config {
569 let py_value = config_value_to_py(py, key, value)?;
570
571 if let Err(setattr_err) = instance.setattr(key, py_value) {
572 anyhow::bail!("Failed to set attribute {key}: {setattr_err}");
573 }
574 }
575
576 if instance.hasattr("__post_init__")? {
577 instance.call_method0("__post_init__")?;
578 }
579
580 instance
581 }
582 Err(default_err) => {
583 anyhow::bail!(
584 "Failed to create config instance. Tried kwargs: {kwargs_err}, default: {default_err}"
585 );
586 }
587 },
588 };
589
590 Ok(Some(config_instance))
591}
592
593fn config_value_to_py<'py>(
594 py: Python<'py>,
595 key: &str,
596 value: &serde_json::Value,
597) -> anyhow::Result<Bound<'py, PyAny>> {
598 if key == "actor_id"
599 && let Some(actor_id) = value.as_str()
600 {
601 return Ok(ActorId::new_checked(actor_id)?
602 .into_pyobject(py)?
603 .into_any());
604 }
605
606 if key == "strategy_id"
607 && let Some(strategy_id) = value.as_str()
608 {
609 return Ok(StrategyId::new_checked(strategy_id)?
610 .into_pyobject(py)?
611 .into_any());
612 }
613
614 let json_str = serde_json::to_string(value)
615 .map_err(|e| anyhow::anyhow!("Failed to serialize config value: {e}"))?;
616
617 Ok(PyModule::import(py, "json")?
618 .call_method("loads", (json_str,), None)?
619 .into_any())
620}
621
622fn configure_py_strategy(
623 strategy: &mut PyRefMut<'_, PyStrategy>,
624 config_obj: &Bound<'_, PyAny>,
625) -> anyhow::Result<()> {
626 if let Some(strategy_id) = config_obj
627 .getattr("strategy_id")
628 .ok()
629 .filter(|value| !value.is_none())
630 {
631 let strategy_id = if let Ok(strategy_id) = strategy_id.extract::<StrategyId>() {
632 strategy_id
633 } else if let Ok(strategy_id_str) = strategy_id.extract::<String>() {
634 StrategyId::new_checked(&strategy_id_str)?
635 } else {
636 anyhow::bail!("Invalid `strategy_id` type");
637 };
638 strategy.set_strategy_id(strategy_id)?;
639 }
640
641 if let Some(order_id_tag) = config_obj
642 .getattr("order_id_tag")
643 .ok()
644 .filter(|value| !value.is_none())
645 {
646 let order_id_tag = order_id_tag
647 .extract::<String>()
648 .map_err(|e| anyhow::anyhow!("Invalid `order_id_tag` type: {e}"))?;
649 strategy.set_order_id_tag(&order_id_tag)?;
650 }
651
652 if let Some(log_events) = extract_bool_config_attr(config_obj, "log_events") {
653 strategy.set_log_events(log_events);
654 }
655
656 if let Some(log_commands) = extract_bool_config_attr(config_obj, "log_commands") {
657 strategy.set_log_commands(log_commands);
658 }
659
660 Ok(())
661}
662
663fn extract_bool_config_attr(config_obj: &Bound<'_, PyAny>, attr: &str) -> Option<bool> {
664 config_obj
665 .getattr(attr)
666 .ok()
667 .and_then(|value| value.extract::<bool>().ok())
668}