Skip to main content

nautilus_trading/python/
strategy.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Python bindings for Strategy with complete order and position management.
17
18use std::{
19    any::Any,
20    cell::{RefCell, UnsafeCell},
21    collections::HashMap,
22    fmt::Debug,
23    num::NonZeroUsize,
24    ops::{Deref, DerefMut},
25    rc::Rc,
26};
27
28use indexmap::IndexMap;
29use jiff::Timestamp;
30use nautilus_common::{
31    actor::{
32        Actor, DataActor, DataActorNative,
33        data_actor::DataActorCore,
34        registry::{try_get_actor_unchecked, with_actor_registry},
35    },
36    cache::Cache,
37    clock::Clock,
38    component::{Component, with_component_registry},
39    enums::ComponentState,
40    messages::{
41        data::{
42            DataResponseEnvelope, ensure_routable_bar_types, ensure_routable_instrument_ids,
43            ensure_subscription_routes, quote_routing,
44        },
45        system::{QueueStateChanged, SocketStateChanged},
46    },
47    msgbus::TypedHandler,
48    python::{
49        actor::{extract_bar_types, extract_instrument_ids},
50        cache::PyCache,
51        clock::PyClock,
52        config_error_to_pyvalue_err,
53        indicators::{registered_python_indicators, wrap_python_indicator},
54        logging::{PyLogger, format_exception},
55        order_factory::PyOrderFactory,
56        response::PyDataResponse,
57        wrappers::{get_python_message_bus, retain_python_wrapper},
58    },
59    runner::SystemChannel,
60    signal::Signal,
61    timer::{TimeEvent, TimeEventCallback},
62};
63use nautilus_core::{
64    Params, UnixNanos,
65    correctness::{CorrectnessResult, CorrectnessResultExt, FAILED},
66    from_pydict,
67    python::{to_pyruntime_err, to_pyvalue_err, upgrade_py_weakref},
68};
69use nautilus_model::{
70    data::{
71        Bar, BarType, CustomData, DataType, FundingRateUpdate, IndexPriceUpdate, InstrumentStatus,
72        MarkPriceUpdate, OrderBookDelta, OrderBookDeltas, OrderBookDepth, QuoteTick, TradeTick,
73        close::InstrumentClose,
74        option_chain::{OptionChainSlice, OptionGreeks},
75    },
76    enums::{BookType, OmsType, OrderSide, PositionSide, TimeInForce},
77    events::{
78        OrderAccepted, OrderCancelDenied, OrderCancelRejected, OrderCanceled, OrderDenied,
79        OrderEmulated, OrderEventAny, OrderExpired, OrderFillVoided, OrderFilled, OrderInitialized,
80        OrderModifyDenied, OrderModifyRejected, OrderPendingCancel, OrderPendingUpdate,
81        OrderRejected, OrderReleased, OrderSubmitted, OrderTriggered, OrderUpdated,
82        PositionChanged, PositionClosed, PositionEvent, PositionOpened,
83    },
84    identifiers::{
85        AccountId, ActorId, ClientId, ClientOrderId, InstrumentId, OptionSeriesId, PositionId,
86        StrategyId, TraderId, UNASSIGNED_ORDER_ID_TAG, Venue, normalize_order_id_tag,
87    },
88    instruments::{InstrumentAny, SyntheticInstrument},
89    orderbook::OrderBook,
90    orders::{Order, OrderAny},
91    position::Position,
92    python::{
93        data::option_chain::PyStrikeRange, events::order::order_event_to_pyobject,
94        instruments::instrument_any_to_pyobject, orders::pyobject_to_order_any,
95    },
96    types::{Price, Quantity},
97};
98use nautilus_portfolio::{portfolio::Portfolio, python::PyPortfolio};
99use pyo3::{
100    IntoPyObjectExt,
101    prelude::*,
102    types::{PyBytes, PyDict, PyList, PySet, PyWeakrefReference},
103};
104use ustr::Ustr;
105
106use crate::strategy::{
107    BatchModifyOrder, ImportableStrategyConfig, Strategy, StrategyConfig, StrategyCore,
108    StrategyNative, route_time_event,
109};
110
111#[pyo3::pymethods]
112#[pyo3_stub_gen::derive::gen_stub_pymethods]
113impl StrategyConfig {
114    /// The base model for all trading strategy configurations.
115    #[new]
116    #[pyo3(signature = (
117        strategy_id=None,
118        order_id_tag=None,
119        oms_type=None,
120        external_order_instrument_ids=None,
121        manage_contingent_orders=false,
122        manage_gtd_expiry=false,
123        manage_stop=false,
124        market_exit_interval_ms=100,
125        market_exit_max_attempts=100,
126        market_exit_time_in_force=TimeInForce::Gtc,
127        market_exit_reduce_only=true,
128        use_uuid_client_order_ids=false,
129        use_hyphens_in_client_order_ids=true,
130        log_events=true,
131        log_commands=true,
132        log_rejected_due_post_only_as_warning=true,
133        **_kwargs
134    ))]
135    #[expect(
136        clippy::fn_params_excessive_bools,
137        clippy::too_many_arguments,
138        reason = "constructor mirrors the existing Python keyword API"
139    )]
140    fn py_new(
141        strategy_id: Option<StrategyId>,
142        order_id_tag: Option<String>,
143        oms_type: Option<OmsType>,
144        external_order_instrument_ids: Option<Vec<InstrumentId>>,
145        manage_contingent_orders: bool,
146        manage_gtd_expiry: bool,
147        manage_stop: bool,
148        market_exit_interval_ms: u64,
149        market_exit_max_attempts: u64,
150        market_exit_time_in_force: TimeInForce,
151        market_exit_reduce_only: bool,
152        use_uuid_client_order_ids: bool,
153        use_hyphens_in_client_order_ids: bool,
154        log_events: bool,
155        log_commands: bool,
156        log_rejected_due_post_only_as_warning: bool,
157        _kwargs: Option<&Bound<'_, PyDict>>,
158    ) -> PyResult<Self> {
159        let config = Self {
160            strategy_id,
161            order_id_tag,
162            use_uuid_client_order_ids,
163            use_hyphens_in_client_order_ids,
164            oms_type,
165            external_order_instrument_ids,
166            manage_contingent_orders,
167            manage_gtd_expiry,
168            manage_stop,
169            market_exit_interval_ms,
170            market_exit_max_attempts,
171            market_exit_time_in_force,
172            market_exit_reduce_only,
173            log_events,
174            log_commands,
175            log_rejected_due_post_only_as_warning,
176        };
177        config.validate().map_err(config_error_to_pyvalue_err)?;
178        Ok(config)
179    }
180
181    #[getter]
182    fn strategy_id(&self) -> Option<StrategyId> {
183        self.strategy_id
184    }
185
186    #[getter]
187    fn order_id_tag(&self) -> Option<&String> {
188        self.order_id_tag.as_ref()
189    }
190
191    #[getter]
192    fn oms_type(&self) -> Option<OmsType> {
193        self.oms_type
194    }
195
196    #[getter]
197    fn external_order_instrument_ids(&self) -> Option<Vec<InstrumentId>> {
198        self.external_order_instrument_ids.clone()
199    }
200
201    #[getter]
202    fn manage_contingent_orders(&self) -> bool {
203        self.manage_contingent_orders
204    }
205
206    #[getter]
207    fn manage_gtd_expiry(&self) -> bool {
208        self.manage_gtd_expiry
209    }
210
211    #[getter]
212    fn manage_stop(&self) -> bool {
213        self.manage_stop
214    }
215
216    #[getter]
217    fn market_exit_interval_ms(&self) -> u64 {
218        self.market_exit_interval_ms
219    }
220
221    #[getter]
222    fn market_exit_max_attempts(&self) -> u64 {
223        self.market_exit_max_attempts
224    }
225
226    #[getter]
227    fn market_exit_time_in_force(&self) -> TimeInForce {
228        self.market_exit_time_in_force
229    }
230
231    #[getter]
232    fn market_exit_reduce_only(&self) -> bool {
233        self.market_exit_reduce_only
234    }
235
236    #[getter]
237    fn use_uuid_client_order_ids(&self) -> bool {
238        self.use_uuid_client_order_ids
239    }
240
241    #[getter]
242    fn use_hyphens_in_client_order_ids(&self) -> bool {
243        self.use_hyphens_in_client_order_ids
244    }
245
246    #[getter]
247    fn log_events(&self) -> bool {
248        self.log_events
249    }
250
251    #[getter]
252    fn log_commands(&self) -> bool {
253        self.log_commands
254    }
255
256    #[getter]
257    fn log_rejected_due_post_only_as_warning(&self) -> bool {
258        self.log_rejected_due_post_only_as_warning
259    }
260}
261
262#[pyo3::pymethods]
263#[pyo3_stub_gen::derive::gen_stub_pymethods]
264impl ImportableStrategyConfig {
265    /// Configuration for creating strategies from importable paths.
266    #[new]
267    #[expect(clippy::needless_pass_by_value)]
268    fn py_new(strategy_path: String, config_path: String, config: Py<PyDict>) -> PyResult<Self> {
269        let json_config = Python::attach(|py| -> PyResult<HashMap<String, serde_json::Value>> {
270            let kwargs = PyDict::new(py);
271            kwargs.set_item("default", py.eval(pyo3::ffi::c_str!("str"), None, None)?)?;
272            let json_str: String = PyModule::import(py, "json")?
273                .call_method("dumps", (config.bind(py),), Some(&kwargs))?
274                .extract()?;
275
276            let json_value: serde_json::Value =
277                serde_json::from_str(&json_str).map_err(to_pyvalue_err)?;
278
279            if let serde_json::Value::Object(map) = json_value {
280                Ok(map.into_iter().collect())
281            } else {
282                Err(to_pyvalue_err("Config must be a dictionary"))
283            }
284        })?;
285
286        Ok(Self {
287            strategy_path,
288            config_path,
289            config: json_config,
290        })
291    }
292
293    #[getter]
294    fn strategy_path(&self) -> &String {
295        &self.strategy_path
296    }
297
298    #[getter]
299    fn config_path(&self) -> &String {
300        &self.config_path
301    }
302
303    #[getter]
304    fn config(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
305        let py_dict = PyDict::new(py);
306
307        for (key, value) in &self.config {
308            let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
309            let py_value = PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
310            py_dict.set_item(key, py_value)?;
311        }
312        Ok(py_dict.unbind())
313    }
314}
315
316/// Inner state of `PyStrategy`, shared between Python wrapper and Rust registries.
317pub struct PyStrategyInner {
318    core: StrategyCore,
319    py_self: Option<Py<PyWeakrefReference>>,
320    config: Option<Py<PyAny>>,
321    clock: PyClock,
322    logger: PyLogger,
323}
324
325impl Debug for PyStrategyInner {
326    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327        f.debug_struct(stringify!(PyStrategyInner))
328            .field("core", &self.core)
329            .field(
330                "py_self",
331                &self.py_self.as_ref().map(|_| "<Py<PyWeakrefReference>>"),
332            )
333            .field("config", &self.config.as_ref().map(|_| "<Py<PyAny>>"))
334            .field("clock", &self.clock)
335            .field("logger", &self.logger)
336            .finish()
337    }
338}
339
340#[expect(
341    clippy::needless_pass_by_ref_mut,
342    reason = "dispatch methods share receiver shape with mutable DataActor hooks"
343)]
344impl PyStrategyInner {
345    fn dispatch_on_start(&self) -> PyResult<()> {
346        if let Some(py_self) = self.python_instance()? {
347            Python::attach(|py| py_self.call_method0(py, "on_start"))?;
348        }
349        Ok(())
350    }
351
352    fn dispatch_on_stop(&self) -> PyResult<()> {
353        if let Some(py_self) = self.python_instance()? {
354            Python::attach(|py| py_self.call_method0(py, "on_stop"))?;
355        }
356        Ok(())
357    }
358
359    fn dispatch_on_resume(&self) -> PyResult<()> {
360        if let Some(py_self) = self.python_instance()? {
361            Python::attach(|py| py_self.call_method0(py, "on_resume"))?;
362        }
363        Ok(())
364    }
365
366    fn dispatch_on_reset(&self) -> PyResult<()> {
367        if let Some(py_self) = self.python_instance()? {
368            Python::attach(|py| py_self.call_method0(py, "on_reset"))?;
369        }
370        Ok(())
371    }
372
373    fn dispatch_on_dispose(&self) -> PyResult<()> {
374        if let Some(py_self) = self.python_instance()? {
375            Python::attach(|py| py_self.call_method0(py, "on_dispose"))?;
376        }
377        Ok(())
378    }
379
380    fn dispatch_on_degrade(&self) -> PyResult<()> {
381        if let Some(py_self) = self.python_instance()? {
382            Python::attach(|py| py_self.call_method0(py, "on_degrade"))?;
383        }
384        Ok(())
385    }
386
387    fn dispatch_on_fault(&self) -> PyResult<()> {
388        if let Some(py_self) = self.python_instance()? {
389            Python::attach(|py| py_self.call_method0(py, "on_fault"))?;
390        }
391        Ok(())
392    }
393
394    fn dispatch_on_save(&self) -> PyResult<IndexMap<String, Vec<u8>>> {
395        if let Some(py_self) = self.python_instance()? {
396            Python::attach(|py| {
397                let py_state = py_self.call_method0(py, "on_save")?;
398                let py_state: &Bound<'_, PyDict> = py_state.cast_bound::<PyDict>(py)?;
399                pydict_to_state(py_state)
400            })
401        } else {
402            Ok(IndexMap::new())
403        }
404    }
405
406    fn dispatch_on_load(&self, state: &IndexMap<String, Vec<u8>>) -> PyResult<()> {
407        if let Some(py_self) = self.python_instance()? {
408            Python::attach(|py| -> PyResult<()> {
409                let py_state = state_to_pydict(py, state)?;
410                py_self.call_method1(py, "on_load", (py_state,))?;
411                Ok(())
412            })?;
413        }
414        Ok(())
415    }
416
417    fn dispatch_on_market_exit(&self) -> PyResult<()> {
418        if let Some(py_self) = self.python_instance()? {
419            Python::attach(|py| py_self.call_method0(py, "on_market_exit"))?;
420        }
421        Ok(())
422    }
423
424    fn dispatch_post_market_exit(&self) -> PyResult<()> {
425        if let Some(py_self) = self.python_instance()? {
426            Python::attach(|py| py_self.call_method0(py, "post_market_exit"))?;
427        }
428        Ok(())
429    }
430
431    fn dispatch_on_time_event(&self, event: &TimeEvent) -> PyResult<()> {
432        if let Some(py_self) = self.python_instance()? {
433            Python::attach(|py| {
434                py_self.call_method1(py, "on_time_event", (event.clone().into_py_any(py)?,))
435            })?;
436        }
437        Ok(())
438    }
439
440    fn dispatch_on_order_initialized(&self, event: OrderInitialized) -> PyResult<()> {
441        if let Some(py_self) = self.python_instance()? {
442            Python::attach(|py| {
443                py_self.call_method1(py, "on_order_initialized", (event.into_py_any(py)?,))
444            })?;
445        }
446        Ok(())
447    }
448
449    fn dispatch_on_order_event(&self, event: OrderEventAny) -> PyResult<()> {
450        if let Some(py_self) = self.python_instance()? {
451            Python::attach(|py| {
452                let py_event = order_event_to_pyobject(py, event)?;
453                py_self.call_method1(py, "on_order_event", (py_event,))
454            })?;
455        }
456        Ok(())
457    }
458
459    fn dispatch_on_order_denied(&self, event: OrderDenied) -> PyResult<()> {
460        if let Some(py_self) = self.python_instance()? {
461            Python::attach(|py| {
462                py_self.call_method1(py, "on_order_denied", (event.into_py_any(py)?,))
463            })?;
464        }
465        Ok(())
466    }
467
468    fn dispatch_on_order_emulated(&self, event: OrderEmulated) -> PyResult<()> {
469        if let Some(py_self) = self.python_instance()? {
470            Python::attach(|py| {
471                py_self.call_method1(py, "on_order_emulated", (event.into_py_any(py)?,))
472            })?;
473        }
474        Ok(())
475    }
476
477    fn dispatch_on_order_released(&self, event: OrderReleased) -> PyResult<()> {
478        if let Some(py_self) = self.python_instance()? {
479            Python::attach(|py| {
480                py_self.call_method1(py, "on_order_released", (event.into_py_any(py)?,))
481            })?;
482        }
483        Ok(())
484    }
485
486    fn dispatch_on_order_submitted(&self, event: OrderSubmitted) -> PyResult<()> {
487        if let Some(py_self) = self.python_instance()? {
488            Python::attach(|py| {
489                py_self.call_method1(py, "on_order_submitted", (event.into_py_any(py)?,))
490            })?;
491        }
492        Ok(())
493    }
494
495    fn dispatch_on_order_rejected(&self, event: OrderRejected) -> PyResult<()> {
496        if let Some(py_self) = self.python_instance()? {
497            Python::attach(|py| {
498                py_self.call_method1(py, "on_order_rejected", (event.into_py_any(py)?,))
499            })?;
500        }
501        Ok(())
502    }
503
504    fn dispatch_on_order_accepted(&self, event: OrderAccepted) -> PyResult<()> {
505        if let Some(py_self) = self.python_instance()? {
506            Python::attach(|py| {
507                py_self.call_method1(py, "on_order_accepted", (event.into_py_any(py)?,))
508            })?;
509        }
510        Ok(())
511    }
512
513    fn dispatch_on_order_expired(&self, event: OrderExpired) -> PyResult<()> {
514        if let Some(py_self) = self.python_instance()? {
515            Python::attach(|py| {
516                py_self.call_method1(py, "on_order_expired", (event.into_py_any(py)?,))
517            })?;
518        }
519        Ok(())
520    }
521
522    fn dispatch_on_order_triggered(&self, event: OrderTriggered) -> PyResult<()> {
523        if let Some(py_self) = self.python_instance()? {
524            Python::attach(|py| {
525                py_self.call_method1(py, "on_order_triggered", (event.into_py_any(py)?,))
526            })?;
527        }
528        Ok(())
529    }
530
531    fn dispatch_on_order_pending_update(&self, event: OrderPendingUpdate) -> PyResult<()> {
532        if let Some(py_self) = self.python_instance()? {
533            Python::attach(|py| {
534                py_self.call_method1(py, "on_order_pending_update", (event.into_py_any(py)?,))
535            })?;
536        }
537        Ok(())
538    }
539
540    fn dispatch_on_order_pending_cancel(&self, event: OrderPendingCancel) -> PyResult<()> {
541        if let Some(py_self) = self.python_instance()? {
542            Python::attach(|py| {
543                py_self.call_method1(py, "on_order_pending_cancel", (event.into_py_any(py)?,))
544            })?;
545        }
546        Ok(())
547    }
548
549    fn dispatch_on_order_modify_denied(&self, event: OrderModifyDenied) -> PyResult<()> {
550        if let Some(py_self) = self.python_instance()? {
551            Python::attach(|py| {
552                py_self.call_method1(py, "on_order_modify_denied", (event.into_py_any(py)?,))
553            })?;
554        }
555
556        Ok(())
557    }
558
559    fn dispatch_on_order_modify_rejected(&self, event: OrderModifyRejected) -> PyResult<()> {
560        if let Some(py_self) = self.python_instance()? {
561            Python::attach(|py| {
562                py_self.call_method1(py, "on_order_modify_rejected", (event.into_py_any(py)?,))
563            })?;
564        }
565        Ok(())
566    }
567
568    fn dispatch_on_order_cancel_denied(&self, event: OrderCancelDenied) -> PyResult<()> {
569        if let Some(py_self) = self.python_instance()? {
570            Python::attach(|py| {
571                py_self.call_method1(py, "on_order_cancel_denied", (event.into_py_any(py)?,))
572            })?;
573        }
574
575        Ok(())
576    }
577
578    fn dispatch_on_order_cancel_rejected(&self, event: OrderCancelRejected) -> PyResult<()> {
579        if let Some(py_self) = self.python_instance()? {
580            Python::attach(|py| {
581                py_self.call_method1(py, "on_order_cancel_rejected", (event.into_py_any(py)?,))
582            })?;
583        }
584        Ok(())
585    }
586
587    fn dispatch_on_order_updated(&self, event: &OrderUpdated) -> PyResult<()> {
588        if let Some(py_self) = self.python_instance()? {
589            Python::attach(|py| {
590                py_self.call_method1(py, "on_order_updated", ((*event).into_py_any(py)?,))
591            })?;
592        }
593        Ok(())
594    }
595
596    fn dispatch_on_order_canceled(&self, event: OrderCanceled) -> PyResult<()> {
597        if let Some(py_self) = self.python_instance()? {
598            Python::attach(|py| {
599                py_self.call_method1(py, "on_order_canceled", (event.into_py_any(py)?,))
600            })?;
601        }
602        Ok(())
603    }
604
605    fn dispatch_on_order_filled(&self, event: &OrderFilled) -> PyResult<()> {
606        if let Some(py_self) = self.python_instance()? {
607            Python::attach(|py| {
608                py_self.call_method1(py, "on_order_filled", (event.clone().into_py_any(py)?,))
609            })?;
610        }
611        Ok(())
612    }
613
614    fn dispatch_on_order_fill_voided(&self, event: &OrderFillVoided) -> PyResult<()> {
615        if let Some(py_self) = self.python_instance()? {
616            Python::attach(|py| {
617                py_self.call_method1(
618                    py,
619                    "on_order_fill_voided",
620                    (event.clone().into_py_any(py)?,),
621                )
622            })?;
623        }
624        Ok(())
625    }
626
627    fn dispatch_on_position_opened(&self, event: PositionOpened) -> PyResult<()> {
628        if let Some(py_self) = self.python_instance()? {
629            Python::attach(|py| {
630                py_self.call_method1(py, "on_position_opened", (event.into_py_any(py)?,))
631            })?;
632        }
633        Ok(())
634    }
635
636    fn dispatch_on_position_event(&self, event: PositionEvent) -> PyResult<()> {
637        if let Some(py_self) = self.python_instance()? {
638            Python::attach(|py| {
639                let py_event = match event {
640                    PositionEvent::PositionOpened(event) => event.into_py_any(py)?,
641                    PositionEvent::PositionChanged(event) => event.into_py_any(py)?,
642                    PositionEvent::PositionClosed(event) => event.into_py_any(py)?,
643                    PositionEvent::PositionAdjusted(event) => event.into_py_any(py)?,
644                };
645                py_self.call_method1(py, "on_position_event", (py_event,))
646            })?;
647        }
648        Ok(())
649    }
650
651    fn dispatch_on_position_changed(&self, event: PositionChanged) -> PyResult<()> {
652        if let Some(py_self) = self.python_instance()? {
653            Python::attach(|py| {
654                py_self.call_method1(py, "on_position_changed", (event.into_py_any(py)?,))
655            })?;
656        }
657        Ok(())
658    }
659
660    fn dispatch_on_position_closed(&self, event: PositionClosed) -> PyResult<()> {
661        if let Some(py_self) = self.python_instance()? {
662            Python::attach(|py| {
663                py_self.call_method1(py, "on_position_closed", (event.into_py_any(py)?,))
664            })?;
665        }
666        Ok(())
667    }
668
669    fn dispatch_on_data(&mut self, data: Py<PyAny>) -> PyResult<()> {
670        if let Some(py_self) = self.python_instance()? {
671            Python::attach(|py| py_self.call_method1(py, "on_data", (data,)))?;
672        }
673        Ok(())
674    }
675
676    fn dispatch_on_signal(&mut self, signal: &Signal) -> PyResult<()> {
677        if let Some(py_self) = self.python_instance()? {
678            Python::attach(|py| {
679                py_self.call_method1(py, "on_signal", (signal.clone().into_py_any(py)?,))
680            })?;
681        }
682        Ok(())
683    }
684
685    fn dispatch_on_queue_state(&mut self, event: &QueueStateChanged) -> PyResult<()> {
686        if let Some(py_self) = self.python_instance()? {
687            Python::attach(|py| {
688                py_self.call_method1(py, "on_queue_state", (event.clone().into_py_any(py)?,))
689            })?;
690        }
691        Ok(())
692    }
693
694    fn dispatch_on_socket_state(&mut self, event: &SocketStateChanged) -> PyResult<()> {
695        if let Some(py_self) = self.python_instance()? {
696            Python::attach(|py| {
697                py_self.call_method1(py, "on_socket_state", (event.clone().into_py_any(py)?,))
698            })?;
699        }
700        Ok(())
701    }
702
703    fn dispatch_on_instrument(&mut self, instrument: Py<PyAny>) -> PyResult<()> {
704        if let Some(py_self) = self.python_instance()? {
705            Python::attach(|py| py_self.call_method1(py, "on_instrument", (instrument,)))?;
706        }
707        Ok(())
708    }
709
710    fn dispatch_on_quote(&mut self, quote: QuoteTick) -> PyResult<()> {
711        if let Some(py_self) = self.python_instance()? {
712            Python::attach(|py| py_self.call_method1(py, "on_quote", (quote.into_py_any(py)?,)))?;
713        }
714        Ok(())
715    }
716
717    fn dispatch_on_trade(&mut self, trade: TradeTick) -> PyResult<()> {
718        if let Some(py_self) = self.python_instance()? {
719            Python::attach(|py| py_self.call_method1(py, "on_trade", (trade.into_py_any(py)?,)))?;
720        }
721        Ok(())
722    }
723
724    fn dispatch_on_bar(&mut self, bar: Bar) -> PyResult<()> {
725        if let Some(py_self) = self.python_instance()? {
726            Python::attach(|py| py_self.call_method1(py, "on_bar", (bar.into_py_any(py)?,)))?;
727        }
728        Ok(())
729    }
730
731    fn dispatch_on_book_deltas(&mut self, deltas: &OrderBookDeltas) -> PyResult<()> {
732        if let Some(py_self) = self.python_instance()? {
733            Python::attach(|py| {
734                py_self.call_method1(py, "on_book_deltas", (deltas.clone().into_py_any(py)?,))
735            })?;
736        }
737        Ok(())
738    }
739
740    fn dispatch_on_book_depth(&mut self, depth: &OrderBookDepth) -> PyResult<()> {
741        if let Some(py_self) = self.python_instance()? {
742            Python::attach(|py| {
743                py_self.call_method1(py, "on_book_depth", (depth.clone().into_py_any(py)?,))
744            })?;
745        }
746        Ok(())
747    }
748
749    fn dispatch_on_book(&mut self, book: &OrderBook) -> PyResult<()> {
750        if let Some(py_self) = self.python_instance()? {
751            Python::attach(|py| {
752                py_self.call_method1(py, "on_book", (book.clone().into_py_any(py)?,))
753            })?;
754        }
755        Ok(())
756    }
757
758    fn dispatch_on_mark_price(&mut self, mark_price: MarkPriceUpdate) -> PyResult<()> {
759        if let Some(py_self) = self.python_instance()? {
760            Python::attach(|py| {
761                py_self.call_method1(py, "on_mark_price", (mark_price.into_py_any(py)?,))
762            })?;
763        }
764        Ok(())
765    }
766
767    fn dispatch_on_index_price(&mut self, index_price: IndexPriceUpdate) -> PyResult<()> {
768        if let Some(py_self) = self.python_instance()? {
769            Python::attach(|py| {
770                py_self.call_method1(py, "on_index_price", (index_price.into_py_any(py)?,))
771            })?;
772        }
773        Ok(())
774    }
775
776    fn dispatch_on_funding_rate(&mut self, funding_rate: FundingRateUpdate) -> PyResult<()> {
777        if let Some(py_self) = self.python_instance()? {
778            Python::attach(|py| {
779                py_self.call_method1(py, "on_funding_rate", (funding_rate.into_py_any(py)?,))
780            })?;
781        }
782        Ok(())
783    }
784
785    fn dispatch_on_instrument_status(&mut self, data: InstrumentStatus) -> PyResult<()> {
786        if let Some(py_self) = self.python_instance()? {
787            Python::attach(|py| {
788                py_self.call_method1(py, "on_instrument_status", (data.into_py_any(py)?,))
789            })?;
790        }
791        Ok(())
792    }
793
794    fn dispatch_on_instrument_close(&mut self, update: InstrumentClose) -> PyResult<()> {
795        if let Some(py_self) = self.python_instance()? {
796            Python::attach(|py| {
797                py_self.call_method1(py, "on_instrument_close", (update.into_py_any(py)?,))
798            })?;
799        }
800        Ok(())
801    }
802
803    fn dispatch_on_option_greeks(&mut self, greeks: OptionGreeks) -> PyResult<()> {
804        if let Some(py_self) = self.python_instance()? {
805            Python::attach(|py| {
806                py_self.call_method1(py, "on_option_greeks", (greeks.into_py_any(py)?,))
807            })?;
808        }
809        Ok(())
810    }
811
812    fn dispatch_on_option_chain(&mut self, slice: &OptionChainSlice) -> PyResult<()> {
813        if let Some(py_self) = self.python_instance()? {
814            Python::attach(|py| {
815                py_self.call_method1(py, "on_option_chain", (slice.clone().into_py_any(py)?,))
816            })?;
817        }
818        Ok(())
819    }
820
821    fn dispatch_on_historical_data(&mut self, data: Py<PyAny>) -> PyResult<()> {
822        if let Some(py_self) = self.python_instance()? {
823            Python::attach(|py| py_self.call_method1(py, "on_historical_data", (data,)))?;
824        }
825        Ok(())
826    }
827
828    fn dispatch_on_historical_book_deltas(&mut self, deltas: Vec<OrderBookDelta>) -> PyResult<()> {
829        if let Some(py_self) = self.python_instance()? {
830            Python::attach(|py| {
831                let py_deltas = deltas
832                    .into_iter()
833                    .map(|delta| delta.into_py_any(py))
834                    .collect::<PyResult<Vec<_>>>()?;
835                py_self.call_method1(py, "on_historical_book_deltas", (py_deltas,))
836            })?;
837        }
838        Ok(())
839    }
840
841    fn dispatch_on_historical_book_depth(&mut self, depths: Vec<OrderBookDepth>) -> PyResult<()> {
842        if let Some(py_self) = self.python_instance()? {
843            Python::attach(|py| {
844                let py_depths = depths
845                    .into_iter()
846                    .map(|depth| depth.into_py_any(py))
847                    .collect::<PyResult<Vec<_>>>()?;
848                py_self.call_method1(py, "on_historical_book_depth", (py_depths,))
849            })?;
850        }
851        Ok(())
852    }
853
854    fn dispatch_on_historical_quotes(&mut self, quotes: Vec<QuoteTick>) -> PyResult<()> {
855        if let Some(py_self) = self.python_instance()? {
856            Python::attach(|py| {
857                let py_quotes = quotes
858                    .into_iter()
859                    .map(|quote| quote.into_py_any(py))
860                    .collect::<PyResult<Vec<_>>>()?;
861                py_self.call_method1(py, "on_historical_quotes", (py_quotes,))
862            })?;
863        }
864        Ok(())
865    }
866
867    fn dispatch_on_historical_trades(&mut self, trades: Vec<TradeTick>) -> PyResult<()> {
868        if let Some(py_self) = self.python_instance()? {
869            Python::attach(|py| {
870                let py_trades = trades
871                    .into_iter()
872                    .map(|trade| trade.into_py_any(py))
873                    .collect::<PyResult<Vec<_>>>()?;
874                py_self.call_method1(py, "on_historical_trades", (py_trades,))
875            })?;
876        }
877        Ok(())
878    }
879
880    fn dispatch_on_historical_funding_rates(
881        &mut self,
882        funding_rates: Vec<FundingRateUpdate>,
883    ) -> PyResult<()> {
884        if let Some(py_self) = self.python_instance()? {
885            Python::attach(|py| {
886                let py_funding_rates = funding_rates
887                    .into_iter()
888                    .map(|rate| rate.into_py_any(py))
889                    .collect::<PyResult<Vec<_>>>()?;
890                py_self.call_method1(py, "on_historical_funding_rates", (py_funding_rates,))
891            })?;
892        }
893        Ok(())
894    }
895
896    fn dispatch_on_historical_bars(&mut self, bars: Vec<Bar>) -> PyResult<()> {
897        if let Some(py_self) = self.python_instance()? {
898            Python::attach(|py| {
899                let py_bars = bars
900                    .into_iter()
901                    .map(|bar| bar.into_py_any(py))
902                    .collect::<PyResult<Vec<_>>>()?;
903                py_self.call_method1(py, "on_historical_bars", (py_bars,))
904            })?;
905        }
906        Ok(())
907    }
908
909    fn dispatch_on_historical_mark_prices(
910        &mut self,
911        mark_prices: Vec<MarkPriceUpdate>,
912    ) -> PyResult<()> {
913        if let Some(py_self) = self.python_instance()? {
914            Python::attach(|py| {
915                let py_mark_prices = mark_prices
916                    .into_iter()
917                    .map(|price| price.into_py_any(py))
918                    .collect::<PyResult<Vec<_>>>()?;
919                py_self.call_method1(py, "on_historical_mark_prices", (py_mark_prices,))
920            })?;
921        }
922        Ok(())
923    }
924
925    fn dispatch_on_historical_index_prices(
926        &mut self,
927        index_prices: Vec<IndexPriceUpdate>,
928    ) -> PyResult<()> {
929        if let Some(py_self) = self.python_instance()? {
930            Python::attach(|py| {
931                let py_index_prices = index_prices
932                    .into_iter()
933                    .map(|price| price.into_py_any(py))
934                    .collect::<PyResult<Vec<_>>>()?;
935                py_self.call_method1(py, "on_historical_index_prices", (py_index_prices,))
936            })?;
937        }
938        Ok(())
939    }
940
941    // The trader owns the wrapper for as long as the strategy stays registered, so a collected
942    // wrapper propagates as an error rather than a skipped callback.
943    fn python_instance(&self) -> PyResult<Option<Py<PyAny>>> {
944        upgrade_py_weakref(
945            self.py_self.as_ref(),
946            &DataActorNative::core(&self.core).actor_id,
947        )
948    }
949}
950
951impl Deref for PyStrategyInner {
952    type Target = DataActorCore;
953
954    fn deref(&self) -> &Self::Target {
955        DataActorNative::core(&self.core)
956    }
957}
958
959impl DerefMut for PyStrategyInner {
960    fn deref_mut(&mut self) -> &mut Self::Target {
961        DataActorNative::core_mut(&mut self.core)
962    }
963}
964
965impl DataActorNative for PyStrategyInner {
966    fn core(&self) -> &DataActorCore {
967        DataActorNative::core(&self.core)
968    }
969
970    fn core_mut(&mut self) -> &mut DataActorCore {
971        DataActorNative::core_mut(&mut self.core)
972    }
973}
974
975impl StrategyNative for PyStrategyInner {
976    fn strategy_core(&self) -> &StrategyCore {
977        &self.core
978    }
979
980    fn strategy_core_mut(&mut self) -> &mut StrategyCore {
981        &mut self.core
982    }
983}
984
985impl Strategy for PyStrategyInner {
986    fn external_order_instrument_ids(&self) -> Option<Vec<InstrumentId>> {
987        self.core.config.external_order_instrument_ids.clone()
988    }
989
990    fn on_market_exit(&mut self) {
991        self.logger
992            .log_callback_error("on_market_exit", self.dispatch_on_market_exit());
993    }
994
995    fn post_market_exit(&mut self) {
996        self.logger
997            .log_callback_error("post_market_exit", self.dispatch_post_market_exit());
998    }
999
1000    fn on_order_initialized(&mut self, event: OrderInitialized) {
1001        self.logger.log_callback_error(
1002            "on_order_initialized",
1003            self.dispatch_on_order_initialized(event),
1004        );
1005    }
1006
1007    fn on_order_event(&mut self, event: OrderEventAny) {
1008        self.logger
1009            .log_callback_error("on_order_event", self.dispatch_on_order_event(event));
1010    }
1011
1012    fn on_order_denied(&mut self, event: OrderDenied) {
1013        self.logger
1014            .log_callback_error("on_order_denied", self.dispatch_on_order_denied(event));
1015    }
1016
1017    fn on_order_emulated(&mut self, event: OrderEmulated) {
1018        self.logger
1019            .log_callback_error("on_order_emulated", self.dispatch_on_order_emulated(event));
1020    }
1021
1022    fn on_order_released(&mut self, event: OrderReleased) {
1023        self.logger
1024            .log_callback_error("on_order_released", self.dispatch_on_order_released(event));
1025    }
1026
1027    fn on_order_submitted(&mut self, event: OrderSubmitted) {
1028        self.logger.log_callback_error(
1029            "on_order_submitted",
1030            self.dispatch_on_order_submitted(event),
1031        );
1032    }
1033
1034    fn on_order_rejected(&mut self, event: OrderRejected) {
1035        self.logger
1036            .log_callback_error("on_order_rejected", self.dispatch_on_order_rejected(event));
1037    }
1038
1039    fn on_order_accepted(&mut self, event: OrderAccepted) {
1040        self.logger
1041            .log_callback_error("on_order_accepted", self.dispatch_on_order_accepted(event));
1042    }
1043
1044    fn on_order_expired(&mut self, event: OrderExpired) {
1045        self.logger
1046            .log_callback_error("on_order_expired", self.dispatch_on_order_expired(event));
1047    }
1048
1049    fn on_order_triggered(&mut self, event: OrderTriggered) {
1050        self.logger.log_callback_error(
1051            "on_order_triggered",
1052            self.dispatch_on_order_triggered(event),
1053        );
1054    }
1055
1056    fn on_order_pending_update(&mut self, event: OrderPendingUpdate) {
1057        self.logger.log_callback_error(
1058            "on_order_pending_update",
1059            self.dispatch_on_order_pending_update(event),
1060        );
1061    }
1062
1063    fn on_order_pending_cancel(&mut self, event: OrderPendingCancel) {
1064        self.logger.log_callback_error(
1065            "on_order_pending_cancel",
1066            self.dispatch_on_order_pending_cancel(event),
1067        );
1068    }
1069
1070    fn on_order_modify_denied(&mut self, event: OrderModifyDenied) {
1071        self.logger.log_callback_error(
1072            "on_order_modify_denied",
1073            self.dispatch_on_order_modify_denied(event),
1074        );
1075    }
1076
1077    fn on_order_modify_rejected(&mut self, event: OrderModifyRejected) {
1078        self.logger.log_callback_error(
1079            "on_order_modify_rejected",
1080            self.dispatch_on_order_modify_rejected(event),
1081        );
1082    }
1083
1084    fn on_order_cancel_denied(&mut self, event: OrderCancelDenied) {
1085        self.logger.log_callback_error(
1086            "on_order_cancel_denied",
1087            self.dispatch_on_order_cancel_denied(event),
1088        );
1089    }
1090
1091    fn on_order_cancel_rejected(&mut self, event: OrderCancelRejected) {
1092        self.logger.log_callback_error(
1093            "on_order_cancel_rejected",
1094            self.dispatch_on_order_cancel_rejected(event),
1095        );
1096    }
1097
1098    fn on_order_updated(&mut self, event: OrderUpdated) {
1099        self.logger
1100            .log_callback_error("on_order_updated", self.dispatch_on_order_updated(&event));
1101    }
1102
1103    fn on_order_canceled(&mut self, event: &OrderCanceled) {
1104        self.logger
1105            .log_callback_error("on_order_canceled", self.dispatch_on_order_canceled(*event));
1106    }
1107
1108    fn on_order_filled(&mut self, event: &OrderFilled) {
1109        self.logger
1110            .log_callback_error("on_order_filled", self.dispatch_on_order_filled(event));
1111    }
1112
1113    fn on_order_fill_voided(&mut self, event: &OrderFillVoided) {
1114        self.logger.log_callback_error(
1115            "on_order_fill_voided",
1116            self.dispatch_on_order_fill_voided(event),
1117        );
1118    }
1119
1120    fn on_position_opened(&mut self, event: PositionOpened) {
1121        self.logger.log_callback_error(
1122            "on_position_opened",
1123            self.dispatch_on_position_opened(event),
1124        );
1125    }
1126
1127    fn on_position_event(&mut self, event: PositionEvent) {
1128        self.logger
1129            .log_callback_error("on_position_event", self.dispatch_on_position_event(event));
1130    }
1131
1132    fn on_position_changed(&mut self, event: PositionChanged) {
1133        self.logger.log_callback_error(
1134            "on_position_changed",
1135            self.dispatch_on_position_changed(event),
1136        );
1137    }
1138
1139    fn on_position_closed(&mut self, event: PositionClosed) {
1140        self.logger.log_callback_error(
1141            "on_position_closed",
1142            self.dispatch_on_position_closed(event),
1143        );
1144    }
1145}
1146
1147impl DataActor for PyStrategyInner {
1148    fn response_handler(&self) -> TypedHandler<DataResponseEnvelope> {
1149        nautilus_common::python::response::response_handler(
1150            self.core().actor_id().inner(),
1151            Self::python_instance,
1152            None,
1153        )
1154    }
1155
1156    fn on_start(&mut self) -> anyhow::Result<()> {
1157        Strategy::on_start(self)?;
1158        self.dispatch_on_start()
1159            .map_err(|e| anyhow::anyhow!("Python on_start failed:\n{}", format_exception(&e)))
1160    }
1161
1162    fn on_stop(&mut self) -> anyhow::Result<()> {
1163        self.dispatch_on_stop()
1164            .map_err(|e| anyhow::anyhow!("Python on_stop failed:\n{}", format_exception(&e)))
1165    }
1166
1167    fn on_resume(&mut self) -> anyhow::Result<()> {
1168        self.dispatch_on_resume()
1169            .map_err(|e| anyhow::anyhow!("Python on_resume failed:\n{}", format_exception(&e)))
1170    }
1171
1172    fn on_reset(&mut self) -> anyhow::Result<()> {
1173        self.dispatch_on_reset()
1174            .map_err(|e| anyhow::anyhow!("Python on_reset failed:\n{}", format_exception(&e)))
1175    }
1176
1177    fn on_dispose(&mut self) -> anyhow::Result<()> {
1178        self.dispatch_on_dispose()
1179            .map_err(|e| anyhow::anyhow!("Python on_dispose failed:\n{}", format_exception(&e)))
1180    }
1181
1182    fn on_degrade(&mut self) -> anyhow::Result<()> {
1183        self.dispatch_on_degrade()
1184            .map_err(|e| anyhow::anyhow!("Python on_degrade failed:\n{}", format_exception(&e)))
1185    }
1186
1187    fn on_fault(&mut self) -> anyhow::Result<()> {
1188        self.dispatch_on_fault()
1189            .map_err(|e| anyhow::anyhow!("Python on_fault failed:\n{}", format_exception(&e)))
1190    }
1191
1192    fn on_save(&self) -> anyhow::Result<IndexMap<String, Vec<u8>>> {
1193        self.dispatch_on_save()
1194            .map_err(|e| anyhow::anyhow!("Python on_save failed:\n{}", format_exception(&e)))
1195    }
1196
1197    fn on_load(&mut self, state: IndexMap<String, Vec<u8>>) -> anyhow::Result<()> {
1198        self.dispatch_on_load(&state)
1199            .map_err(|e| anyhow::anyhow!("Python on_load failed:\n{}", format_exception(&e)))
1200    }
1201
1202    fn on_time_event(&mut self, event: &TimeEvent) -> anyhow::Result<()> {
1203        route_time_event(self, event);
1204        self.dispatch_on_time_event(event)
1205            .map_err(|e| anyhow::anyhow!("Python on_time_event failed:\n{}", format_exception(&e)))
1206    }
1207
1208    #[allow(unused_variables)]
1209    fn on_data(&mut self, data: &CustomData) -> anyhow::Result<()> {
1210        Python::attach(|py| {
1211            let py_data: Py<PyAny> = Py::new(py, data.clone())?.into_any();
1212            self.dispatch_on_data(py_data)
1213                .map_err(|e| anyhow::anyhow!("Python on_data failed:\n{}", format_exception(&e)))
1214        })
1215    }
1216
1217    fn on_signal(&mut self, signal: &Signal) -> anyhow::Result<()> {
1218        self.dispatch_on_signal(signal)
1219            .map_err(|e| anyhow::anyhow!("Python on_signal failed:\n{}", format_exception(&e)))
1220    }
1221
1222    fn on_queue_state(&mut self, event: &QueueStateChanged) -> anyhow::Result<()> {
1223        self.dispatch_on_queue_state(event)
1224            .map_err(|e| anyhow::anyhow!("Python on_queue_state failed:\n{}", format_exception(&e)))
1225    }
1226
1227    fn on_socket_state(&mut self, event: &SocketStateChanged) -> anyhow::Result<()> {
1228        self.dispatch_on_socket_state(event).map_err(|e| {
1229            anyhow::anyhow!("Python on_socket_state failed:\n{}", format_exception(&e))
1230        })
1231    }
1232
1233    fn on_instrument(&mut self, instrument: &InstrumentAny) -> anyhow::Result<()> {
1234        Python::attach(|py| {
1235            let py_instrument = instrument_any_to_pyobject(py, instrument.clone())
1236                .map_err(|e| anyhow::anyhow!("Failed to convert InstrumentAny to Python: {e}"))?;
1237            self.dispatch_on_instrument(py_instrument).map_err(|e| {
1238                anyhow::anyhow!("Python on_instrument failed:\n{}", format_exception(&e))
1239            })
1240        })
1241    }
1242
1243    fn on_quote(&mut self, quote: &QuoteTick) -> anyhow::Result<()> {
1244        self.dispatch_on_quote(*quote)
1245            .map_err(|e| anyhow::anyhow!("Python on_quote failed:\n{}", format_exception(&e)))
1246    }
1247
1248    fn on_trade(&mut self, tick: &TradeTick) -> anyhow::Result<()> {
1249        self.dispatch_on_trade(*tick)
1250            .map_err(|e| anyhow::anyhow!("Python on_trade failed:\n{}", format_exception(&e)))
1251    }
1252
1253    fn on_bar(&mut self, bar: &Bar) -> anyhow::Result<()> {
1254        self.dispatch_on_bar(*bar)
1255            .map_err(|e| anyhow::anyhow!("Python on_bar failed:\n{}", format_exception(&e)))
1256    }
1257
1258    fn on_book_deltas(&mut self, deltas: &OrderBookDeltas) -> anyhow::Result<()> {
1259        self.dispatch_on_book_deltas(deltas)
1260            .map_err(|e| anyhow::anyhow!("Python on_book_deltas failed:\n{}", format_exception(&e)))
1261    }
1262
1263    fn on_book_depth(&mut self, depth: &OrderBookDepth) -> anyhow::Result<()> {
1264        self.dispatch_on_book_depth(depth)
1265            .map_err(|e| anyhow::anyhow!("Python on_book_depth failed:\n{}", format_exception(&e)))
1266    }
1267
1268    fn on_book(&mut self, order_book: &OrderBook) -> anyhow::Result<()> {
1269        self.dispatch_on_book(order_book)
1270            .map_err(|e| anyhow::anyhow!("Python on_book failed:\n{}", format_exception(&e)))
1271    }
1272
1273    fn on_mark_price(&mut self, mark_price: &MarkPriceUpdate) -> anyhow::Result<()> {
1274        self.dispatch_on_mark_price(*mark_price)
1275            .map_err(|e| anyhow::anyhow!("Python on_mark_price failed:\n{}", format_exception(&e)))
1276    }
1277
1278    fn on_index_price(&mut self, index_price: &IndexPriceUpdate) -> anyhow::Result<()> {
1279        self.dispatch_on_index_price(*index_price)
1280            .map_err(|e| anyhow::anyhow!("Python on_index_price failed:\n{}", format_exception(&e)))
1281    }
1282
1283    fn on_funding_rate(&mut self, funding_rate: &FundingRateUpdate) -> anyhow::Result<()> {
1284        self.dispatch_on_funding_rate(*funding_rate).map_err(|e| {
1285            anyhow::anyhow!("Python on_funding_rate failed:\n{}", format_exception(&e))
1286        })
1287    }
1288
1289    fn on_instrument_status(&mut self, data: &InstrumentStatus) -> anyhow::Result<()> {
1290        self.dispatch_on_instrument_status(*data).map_err(|e| {
1291            anyhow::anyhow!(
1292                "Python on_instrument_status failed:\n{}",
1293                format_exception(&e)
1294            )
1295        })
1296    }
1297
1298    fn on_instrument_close(&mut self, update: &InstrumentClose) -> anyhow::Result<()> {
1299        self.dispatch_on_instrument_close(*update).map_err(|e| {
1300            anyhow::anyhow!(
1301                "Python on_instrument_close failed:\n{}",
1302                format_exception(&e)
1303            )
1304        })
1305    }
1306
1307    fn on_option_greeks(&mut self, greeks: &OptionGreeks) -> anyhow::Result<()> {
1308        self.dispatch_on_option_greeks(*greeks).map_err(|e| {
1309            anyhow::anyhow!("Python on_option_greeks failed:\n{}", format_exception(&e))
1310        })
1311    }
1312
1313    fn on_option_chain(&mut self, slice: &OptionChainSlice) -> anyhow::Result<()> {
1314        self.dispatch_on_option_chain(slice).map_err(|e| {
1315            anyhow::anyhow!("Python on_option_chain failed:\n{}", format_exception(&e))
1316        })
1317    }
1318
1319    fn on_historical_data(&mut self, data: &dyn Any) -> anyhow::Result<()> {
1320        Python::attach(|py| {
1321            let py_data: Py<PyAny> = if let Some(custom_data) = data.downcast_ref::<CustomData>() {
1322                Py::new(py, custom_data.clone())?.into_any()
1323            } else if let Some(custom_data) = data.downcast_ref::<Vec<CustomData>>() {
1324                custom_data.clone().into_py_any(py)?
1325            } else {
1326                anyhow::bail!("Failed to convert historical data to Python: unsupported type");
1327            };
1328
1329            self.dispatch_on_historical_data(py_data).map_err(|e| {
1330                anyhow::anyhow!(
1331                    "Python on_historical_data failed:\n{}",
1332                    format_exception(&e)
1333                )
1334            })
1335        })
1336    }
1337
1338    fn on_historical_book_deltas(&mut self, deltas: &[OrderBookDelta]) -> anyhow::Result<()> {
1339        self.dispatch_on_historical_book_deltas(deltas.to_vec())
1340            .map_err(|e| {
1341                anyhow::anyhow!(
1342                    "Python on_historical_book_deltas failed:\n{}",
1343                    format_exception(&e)
1344                )
1345            })
1346    }
1347
1348    fn on_historical_book_depth(&mut self, depths: &[OrderBookDepth]) -> anyhow::Result<()> {
1349        self.dispatch_on_historical_book_depth(depths.to_vec())
1350            .map_err(|e| {
1351                anyhow::anyhow!(
1352                    "Python on_historical_book_depth failed:\n{}",
1353                    format_exception(&e)
1354                )
1355            })
1356    }
1357
1358    fn on_historical_quotes(&mut self, quotes: &[QuoteTick]) -> anyhow::Result<()> {
1359        self.dispatch_on_historical_quotes(quotes.to_vec())
1360            .map_err(|e| {
1361                anyhow::anyhow!(
1362                    "Python on_historical_quotes failed:\n{}",
1363                    format_exception(&e)
1364                )
1365            })
1366    }
1367
1368    fn on_historical_trades(&mut self, trades: &[TradeTick]) -> anyhow::Result<()> {
1369        self.dispatch_on_historical_trades(trades.to_vec())
1370            .map_err(|e| {
1371                anyhow::anyhow!(
1372                    "Python on_historical_trades failed:\n{}",
1373                    format_exception(&e)
1374                )
1375            })
1376    }
1377
1378    fn on_historical_funding_rates(
1379        &mut self,
1380        funding_rates: &[FundingRateUpdate],
1381    ) -> anyhow::Result<()> {
1382        self.dispatch_on_historical_funding_rates(funding_rates.to_vec())
1383            .map_err(|e| {
1384                anyhow::anyhow!(
1385                    "Python on_historical_funding_rates failed:\n{}",
1386                    format_exception(&e)
1387                )
1388            })
1389    }
1390
1391    fn on_historical_bars(&mut self, bars: &[Bar]) -> anyhow::Result<()> {
1392        self.dispatch_on_historical_bars(bars.to_vec())
1393            .map_err(|e| {
1394                anyhow::anyhow!(
1395                    "Python on_historical_bars failed:\n{}",
1396                    format_exception(&e)
1397                )
1398            })
1399    }
1400
1401    fn on_historical_mark_prices(&mut self, mark_prices: &[MarkPriceUpdate]) -> anyhow::Result<()> {
1402        self.dispatch_on_historical_mark_prices(mark_prices.to_vec())
1403            .map_err(|e| {
1404                anyhow::anyhow!(
1405                    "Python on_historical_mark_prices failed:\n{}",
1406                    format_exception(&e)
1407                )
1408            })
1409    }
1410
1411    fn on_historical_index_prices(
1412        &mut self,
1413        index_prices: &[IndexPriceUpdate],
1414    ) -> anyhow::Result<()> {
1415        self.dispatch_on_historical_index_prices(index_prices.to_vec())
1416            .map_err(|e| {
1417                anyhow::anyhow!(
1418                    "Python on_historical_index_prices failed:\n{}",
1419                    format_exception(&e)
1420                )
1421            })
1422    }
1423}
1424
1425fn state_to_pydict(py: Python<'_>, state: &IndexMap<String, Vec<u8>>) -> PyResult<Py<PyDict>> {
1426    let py_state = PyDict::new(py);
1427    for (key, value) in state {
1428        py_state.set_item(key, PyBytes::new(py, value))?;
1429    }
1430    Ok(py_state.unbind())
1431}
1432
1433fn pydict_to_state(state: &Bound<'_, PyDict>) -> PyResult<IndexMap<String, Vec<u8>>> {
1434    let mut rust_state = IndexMap::with_capacity(state.len());
1435    for (key, value) in state.iter() {
1436        rust_state.insert(key.extract()?, value.extract()?);
1437    }
1438    Ok(rust_state)
1439}
1440
1441/// Python-facing wrapper for Strategy.
1442#[allow(non_camel_case_types)]
1443#[pyo3::pyclass(
1444    module = "nautilus_trader.trading",
1445    name = "Strategy",
1446    unsendable,
1447    subclass,
1448    weakref
1449)]
1450#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.trading")]
1451pub struct PyStrategy {
1452    inner: Rc<UnsafeCell<PyStrategyInner>>,
1453}
1454
1455impl Debug for PyStrategy {
1456    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1457        f.debug_struct(stringify!(PyStrategy))
1458            .field("inner", &self.inner())
1459            .finish()
1460    }
1461}
1462
1463impl PyStrategy {
1464    #[inline]
1465    #[allow(unsafe_code)]
1466    pub(crate) fn inner(&self) -> &PyStrategyInner {
1467        // SAFETY: `PyStrategy` is `unsendable` so access is single-threaded, and
1468        // callers never hold a mutable and shared reference simultaneously.
1469        unsafe { &*self.inner.get() }
1470    }
1471
1472    #[inline]
1473    #[allow(unsafe_code, clippy::mut_from_ref)]
1474    pub(crate) fn inner_mut(&self) -> &mut PyStrategyInner {
1475        // SAFETY: `PyStrategy` is `unsendable` so access is single-threaded, and
1476        // callers never hold a mutable and shared reference simultaneously.
1477        unsafe { &mut *self.inner.get() }
1478    }
1479}
1480
1481impl PyStrategy {
1482    /// Creates a new `PyStrategy` instance with correctness checking.
1483    ///
1484    /// # Errors
1485    ///
1486    /// Returns an error if the configured order ID tag contains the '-' strategy ID separator,
1487    /// or if composing it into the strategy ID does not produce a valid `StrategyId`.
1488    pub fn new_checked(config: Option<StrategyConfig>) -> CorrectnessResult<Self> {
1489        let config = config.unwrap_or_default();
1490        let core = StrategyCore::new_checked(config)?;
1491        let clock = PyClock::new_test();
1492        let logger = PyLogger::new(core.actor.actor_id.as_str());
1493
1494        let inner = PyStrategyInner {
1495            core,
1496            py_self: None,
1497            config: None,
1498            clock,
1499            logger,
1500        };
1501
1502        Ok(Self {
1503            inner: Rc::new(UnsafeCell::new(inner)),
1504        })
1505    }
1506
1507    /// Creates a new `PyStrategy` instance.
1508    ///
1509    /// # Panics
1510    ///
1511    /// Panics if the configured order ID tag contains the '-' strategy ID separator,
1512    /// or if composing it into the strategy ID does not produce a valid `StrategyId`.
1513    #[must_use]
1514    pub fn new(config: Option<StrategyConfig>) -> Self {
1515        Self::new_checked(config).expect_display(FAILED)
1516    }
1517
1518    /// Sets the Python instance reference for method dispatch.
1519    ///
1520    /// Only a weak reference is stored, so the caller keeps ownership of `py_obj`. The trader
1521    /// owns registered wrappers; an unregistered strategy stays collectable.
1522    ///
1523    /// # Errors
1524    ///
1525    /// Returns an error if `py_obj` cannot be weakly referenced.
1526    pub fn set_python_instance(&mut self, py_obj: &Bound<'_, PyAny>) -> PyResult<()> {
1527        self.inner_mut().py_self = Some(PyWeakrefReference::new(py_obj)?.unbind());
1528        Ok(())
1529    }
1530
1531    /// Stores the original Python config object passed at construction.
1532    ///
1533    /// Retained so the constructed instance exposes `.config` and instance-based registration can
1534    /// source strategy ID, order ID tag, and logging flags from the same single config object.
1535    pub fn set_config(&mut self, config: Option<Py<PyAny>>) {
1536        self.inner_mut().config = config;
1537    }
1538
1539    /// Updates the configured external order instrument IDs before registration.
1540    pub fn set_external_order_instrument_ids(
1541        &mut self,
1542        external_order_instrument_ids: Option<Vec<InstrumentId>>,
1543    ) {
1544        self.inner_mut().core.config.external_order_instrument_ids = external_order_instrument_ids;
1545    }
1546
1547    /// Returns the configured external order instrument IDs.
1548    #[must_use]
1549    pub fn external_order_instrument_ids(&self) -> Option<Vec<InstrumentId>> {
1550        self.inner().external_order_instrument_ids()
1551    }
1552
1553    /// Updates the runtime component identity used until a strategy ID is assigned.
1554    ///
1555    /// Must only be called before registration. See `PyDataActor::set_actor_id`.
1556    pub fn set_actor_id(&mut self, actor_id: ActorId) {
1557        let inner = self.inner_mut();
1558        inner.core.actor.config.actor_id = Some(actor_id);
1559        inner.core.actor.actor_id = actor_id;
1560        inner.logger = PyLogger::new(actor_id.as_str());
1561    }
1562
1563    /// Updates the runtime strategy ID.
1564    ///
1565    /// Must only be called before registration. See `PyDataActor::set_actor_id`.
1566    ///
1567    /// # Errors
1568    ///
1569    /// Returns an error if composing the current order ID tag into `strategy_id` does not
1570    /// produce a valid `StrategyId`.
1571    pub fn set_strategy_id(&mut self, strategy_id: StrategyId) -> anyhow::Result<()> {
1572        let inner = self.inner_mut();
1573        inner.core.change_id(strategy_id)?;
1574        inner.logger = PyLogger::new(inner.core.actor.actor_id.as_str());
1575        Ok(())
1576    }
1577
1578    /// Updates the runtime order ID tag.
1579    ///
1580    /// # Errors
1581    ///
1582    /// Returns an error if `order_id_tag` contains the '-' strategy ID separator, or if
1583    /// composing it into the current strategy ID does not produce a valid `StrategyId`.
1584    pub fn set_order_id_tag(&mut self, order_id_tag: &str) -> anyhow::Result<()> {
1585        let inner = self.inner_mut();
1586        inner.core.change_order_id_tag(order_id_tag)?;
1587        inner.logger = PyLogger::new(inner.core.actor.actor_id.as_str());
1588        Ok(())
1589    }
1590
1591    /// Updates the runtime `log_events` setting.
1592    pub fn set_log_events(&mut self, log_events: bool) {
1593        let inner = self.inner_mut();
1594        inner.core.actor.config.log_events = log_events;
1595    }
1596
1597    /// Updates the runtime `log_commands` setting.
1598    pub fn set_log_commands(&mut self, log_commands: bool) {
1599        let inner = self.inner_mut();
1600        inner.core.actor.config.log_commands = log_commands;
1601    }
1602
1603    /// Returns the strategy ID.
1604    ///
1605    /// Until registration assigns an order ID tag, an unconfigured strategy reports the
1606    /// class-derived ID with the unassigned tag, such as `MyStrategy-None`.
1607    #[must_use]
1608    pub fn strategy_id(&self) -> StrategyId {
1609        StrategyId::new(self.inner().core.actor.actor_id.inner())
1610    }
1611
1612    /// Returns the strategy ID once configured or assigned, otherwise `None`.
1613    #[must_use]
1614    pub fn configured_strategy_id(&self) -> Option<StrategyId> {
1615        self.inner().core.strategy_id()
1616    }
1617
1618    /// Returns the runtime order ID tag.
1619    #[must_use]
1620    pub fn order_id_tag(&self) -> Option<String> {
1621        self.inner().core.order_id_tag().map(str::to_string)
1622    }
1623
1624    /// Returns a value indicating whether the strategy has been registered with a trader.
1625    #[must_use]
1626    pub fn is_registered(&self) -> bool {
1627        self.inner().core.actor.is_registered()
1628    }
1629
1630    /// Register the strategy with a trader.
1631    ///
1632    /// # Errors
1633    ///
1634    /// Returns an error if registration fails.
1635    pub fn register(
1636        &mut self,
1637        trader_id: TraderId,
1638        clock: Rc<RefCell<dyn Clock>>,
1639        cache: Rc<RefCell<Cache>>,
1640        portfolio: Rc<RefCell<Portfolio>>,
1641    ) -> anyhow::Result<()> {
1642        let inner = self.inner_mut();
1643        inner.core.register(trader_id, clock, cache, portfolio)?;
1644
1645        inner.clock = PyClock::from_rc(inner.core.actor.clock_rc());
1646
1647        let actor_id = inner.core.actor.actor_id.inner();
1648        let callback = TimeEventCallback::from(move |event: TimeEvent| {
1649            if let Some(mut strategy) = try_get_actor_unchecked::<PyStrategyInner>(&actor_id) {
1650                strategy.handle_time_event(&event);
1651            } else {
1652                log::error!("Strategy {actor_id} not found for time event handling");
1653            }
1654        });
1655
1656        inner.clock.inner_mut().register_default_handler(callback);
1657
1658        Component::initialize(inner)
1659    }
1660
1661    /// Registers this strategy in the global component, actor, and wrapper registries.
1662    ///
1663    /// The Python wrapper is retained as part of the same act, so a registered strategy always has
1664    /// an owner for the wrapper its inner only weakly references.
1665    ///
1666    /// # Errors
1667    ///
1668    /// Returns an error if no Python wrapper is attached, or if the attached wrapper has already
1669    /// been collected. Nothing is registered in that case.
1670    pub fn register_in_global_registries(&self) -> PyResult<()> {
1671        let inner = self.inner();
1672        let component_id = Component::component_id(inner);
1673        let actor_id = Actor::id(inner);
1674
1675        let Some(wrapper) = inner.python_instance()? else {
1676            return Err(to_pyruntime_err(format!(
1677                "Cannot register strategy {actor_id} without a Python wrapper, call `set_python_instance` first"
1678            )));
1679        };
1680
1681        let inner_ref: Rc<UnsafeCell<PyStrategyInner>> = self.inner.clone();
1682
1683        let component_trait_ref: Rc<UnsafeCell<dyn Component>> = inner_ref.clone();
1684        with_component_registry(|registry| {
1685            registry.insert(component_id.inner(), component_trait_ref);
1686        });
1687
1688        let actor_trait_ref: Rc<UnsafeCell<dyn Actor>> = inner_ref;
1689        with_actor_registry(|registry| registry.insert(actor_id, actor_trait_ref));
1690
1691        retain_python_wrapper(component_id, wrapper, inner.core.actor.message_bus());
1692
1693        Ok(())
1694    }
1695}
1696
1697#[pyo3::pymethods]
1698#[pyo3_stub_gen::derive::gen_stub_pymethods]
1699#[allow(
1700    clippy::large_types_passed_by_value,
1701    reason = "PyO3 callbacks accept Python-owned event values"
1702)]
1703impl PyStrategy {
1704    /// Creates a new [`PyStrategy`] instance.
1705    ///
1706    /// Accepts `None` or any Python object. If the object is a [`StrategyConfig`]
1707    /// (or can be extracted as one via `from_py_object`), its values are used;
1708    /// otherwise the strategy falls back to [`StrategyConfig::default()`].
1709    ///
1710    /// This permissive signature is required so that Python subclasses can pass
1711    /// a **custom** config dataclass to their `__init__`. The original object is
1712    /// retained here in `__new__`, which always receives the constructor arguments,
1713    /// so `.config` and registration see the config even when a subclass omits
1714    /// forwarding it to `super().__init__()`.
1715    #[new]
1716    #[pyo3(signature = (config=None))]
1717    fn py_new(config: Option<Py<PyAny>>) -> PyResult<Self> {
1718        let strategy_config = config
1719            .as_ref()
1720            .and_then(|obj| Python::attach(|py| obj.extract::<StrategyConfig>(py).ok()));
1721        let mut strategy = Self::new_checked(strategy_config).map_err(to_pyvalue_err)?;
1722        strategy.set_config(config);
1723        Ok(strategy)
1724    }
1725
1726    /// Captures the Python self reference for Rust→Python event dispatch.
1727    #[pyo3(signature = (config=None))]
1728    fn __init__(slf: &Bound<'_, Self>, config: Option<Py<PyAny>>) -> PyResult<()> {
1729        {
1730            let mut borrowed = slf.borrow_mut();
1731            borrowed.set_python_instance(slf.as_any())?;
1732            // `__new__` retained the config; only a forwarded config overrides it
1733            if config.is_some() {
1734                borrowed.set_config(config);
1735            }
1736        }
1737
1738        if !has_configured_strategy_id(slf) {
1739            let py_type = slf.get_type();
1740            let type_name = py_type.name()?;
1741            let actor_id = class_derived_actor_id(slf, type_name.to_str()?)?;
1742            slf.borrow_mut().set_actor_id(actor_id);
1743        }
1744
1745        Ok(())
1746    }
1747
1748    #[getter]
1749    #[pyo3(name = "trader_id")]
1750    fn py_trader_id(&self) -> Option<TraderId> {
1751        self.inner().core.trader_id()
1752    }
1753
1754    #[getter]
1755    #[pyo3(name = "strategy_id")]
1756    fn py_strategy_id(&self) -> StrategyId {
1757        self.strategy_id()
1758    }
1759
1760    #[getter]
1761    #[pyo3(name = "config")]
1762    fn py_config(&self, py: Python<'_>) -> Option<Py<PyAny>> {
1763        self.inner()
1764            .config
1765            .as_ref()
1766            .map(|config| config.clone_ref(py))
1767    }
1768
1769    #[getter]
1770    #[pyo3(name = "clock")]
1771    fn py_clock(&self) -> PyResult<PyClock> {
1772        let inner = self.inner();
1773        if inner.core.actor.is_registered() {
1774            Ok(inner.clock.clone())
1775        } else {
1776            Err(to_pyruntime_err(
1777                "Strategy must be registered with a trader before accessing clock",
1778            ))
1779        }
1780    }
1781
1782    #[getter]
1783    #[pyo3(name = "cache")]
1784    fn py_cache(&self) -> PyResult<PyCache> {
1785        let inner = self.inner();
1786        if inner.core.actor.is_registered() {
1787            Ok(PyCache::from_rc(inner.core.actor.cache_rc()))
1788        } else {
1789            Err(to_pyruntime_err(
1790                "Strategy must be registered with a trader before accessing cache",
1791            ))
1792        }
1793    }
1794
1795    /// Replaces this strategy's active external order claims with `instrument_ids`.
1796    ///
1797    /// Passing an empty list releases every claim owned by the strategy. Existing cached orders
1798    /// keep their assigned strategy ID. The original Python config object is not changed.
1799    ///
1800    /// # Errors
1801    ///
1802    /// Returns an error if the strategy is not registered, the cache is already borrowed, an
1803    /// instrument is repeated, or an instrument is claimed by another strategy.
1804    #[pyo3(name = "set_external_order_instrument_ids")]
1805    fn py_set_external_order_instrument_ids(
1806        &mut self,
1807        instrument_ids: Vec<InstrumentId>,
1808    ) -> PyResult<()> {
1809        Strategy::set_external_order_instrument_ids(self.inner_mut(), instrument_ids)
1810            .map_err(to_pyruntime_err)
1811    }
1812
1813    #[getter]
1814    #[pyo3(name = "portfolio")]
1815    fn py_portfolio(&self) -> PyResult<PyPortfolio> {
1816        let inner = self.inner();
1817        if inner.core.actor.is_registered() {
1818            Ok(PyPortfolio::from_rc(inner.portfolio_rc()))
1819        } else {
1820            Err(to_pyruntime_err(
1821                "Strategy must be registered with a trader before accessing portfolio",
1822            ))
1823        }
1824    }
1825
1826    #[getter]
1827    #[pyo3(name = "order_factory")]
1828    fn py_order_factory(&self) -> PyResult<PyOrderFactory> {
1829        let inner = self.inner();
1830        if inner.core.actor.is_registered() {
1831            Ok(PyOrderFactory::from_rc(inner.order_factory_rc()))
1832        } else {
1833            Err(to_pyruntime_err(
1834                "Strategy must be registered with a trader before accessing order_factory",
1835            ))
1836        }
1837    }
1838
1839    #[getter]
1840    #[pyo3(name = "log")]
1841    fn py_log(&self) -> PyLogger {
1842        self.inner().logger.clone()
1843    }
1844
1845    #[pyo3(name = "state")]
1846    fn py_state(&self) -> ComponentState {
1847        self.inner().core.actor.state()
1848    }
1849
1850    #[pyo3(name = "is_ready")]
1851    fn py_is_ready(&self) -> bool {
1852        Component::is_ready(self.inner())
1853    }
1854
1855    #[pyo3(name = "is_running")]
1856    fn py_is_running(&self) -> bool {
1857        Component::is_running(self.inner())
1858    }
1859
1860    #[pyo3(name = "is_stopped")]
1861    fn py_is_stopped(&self) -> bool {
1862        Component::is_stopped(self.inner())
1863    }
1864
1865    #[pyo3(name = "is_disposed")]
1866    fn py_is_disposed(&self) -> bool {
1867        Component::is_disposed(self.inner())
1868    }
1869
1870    #[pyo3(name = "is_degraded")]
1871    fn py_is_degraded(&self) -> bool {
1872        Component::is_degraded(self.inner())
1873    }
1874
1875    #[pyo3(name = "is_faulted")]
1876    fn py_is_faulted(&self) -> bool {
1877        Component::is_faulted(self.inner())
1878    }
1879
1880    #[pyo3(name = "start")]
1881    fn py_start(&mut self) -> PyResult<()> {
1882        Component::start(self.inner_mut()).map_err(to_pyruntime_err)
1883    }
1884
1885    #[pyo3(name = "stop")]
1886    fn py_stop(&mut self) -> PyResult<()> {
1887        let inner = self.inner_mut();
1888        if Strategy::stop(inner) {
1889            Component::stop(inner).map_err(to_pyruntime_err)
1890        } else {
1891            Ok(())
1892        }
1893    }
1894
1895    #[pyo3(name = "market_exit")]
1896    fn py_market_exit(&mut self) -> PyResult<()> {
1897        Strategy::market_exit(self.inner_mut()).map_err(to_pyruntime_err)
1898    }
1899
1900    #[pyo3(name = "is_exiting")]
1901    fn py_is_exiting(&self) -> bool {
1902        Strategy::is_exiting(self.inner())
1903    }
1904
1905    #[pyo3(name = "save")]
1906    fn py_save(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
1907        let state = DataActor::on_save(self.inner()).map_err(to_pyruntime_err)?;
1908        state_to_pydict(py, &state)
1909    }
1910
1911    #[pyo3(name = "load")]
1912    fn py_load(&mut self, state: &Bound<'_, PyDict>) -> PyResult<()> {
1913        let state = pydict_to_state(state)?;
1914        DataActor::on_load(self.inner_mut(), state).map_err(to_pyruntime_err)
1915    }
1916
1917    #[pyo3(name = "publish_data")]
1918    fn py_publish_data(&self, data_type: &DataType, data: &CustomData) -> PyResult<()> {
1919        self.ensure_registered_for_data()?;
1920        DataActor::publish_data(self.inner(), data_type, data);
1921        Ok(())
1922    }
1923
1924    #[pyo3(name = "publish_signal")]
1925    #[pyo3(signature = (name, value, ts_event=0))]
1926    #[expect(
1927        clippy::needless_pass_by_value,
1928        reason = "PyO3 accepts an owned PyAny handle for Python signal values"
1929    )]
1930    fn py_publish_signal(
1931        &self,
1932        py: Python<'_>,
1933        name: &str,
1934        value: Py<PyAny>,
1935        ts_event: u64,
1936    ) -> PyResult<()> {
1937        self.ensure_registered_for_data()?;
1938        let value_str: String = value.bind(py).str()?.extract()?;
1939        DataActor::publish_signal(self.inner(), name, value_str, UnixNanos::from(ts_event));
1940        Ok(())
1941    }
1942
1943    #[pyo3(name = "add_synthetic")]
1944    fn py_add_synthetic(&self, synthetic: SyntheticInstrument) -> PyResult<()> {
1945        self.ensure_registered_for_data()?;
1946        DataActor::add_synthetic(self.inner(), synthetic).map_err(to_pyvalue_err)
1947    }
1948
1949    #[pyo3(name = "update_synthetic")]
1950    fn py_update_synthetic(&self, synthetic: SyntheticInstrument) -> PyResult<()> {
1951        self.ensure_registered_for_data()?;
1952        DataActor::update_synthetic(self.inner(), synthetic).map_err(to_pyvalue_err)
1953    }
1954
1955    #[pyo3(name = "resume")]
1956    fn py_resume(&mut self) -> PyResult<()> {
1957        Component::resume(self.inner_mut()).map_err(to_pyruntime_err)
1958    }
1959
1960    #[pyo3(name = "reset")]
1961    fn py_reset(&mut self) -> PyResult<()> {
1962        Component::reset(self.inner_mut()).map_err(to_pyruntime_err)
1963    }
1964
1965    #[pyo3(name = "dispose")]
1966    fn py_dispose(&mut self) -> PyResult<()> {
1967        Component::dispose(self.inner_mut()).map_err(to_pyruntime_err)
1968    }
1969
1970    #[pyo3(name = "degrade")]
1971    fn py_degrade(&mut self) -> PyResult<()> {
1972        Component::degrade(self.inner_mut()).map_err(to_pyruntime_err)
1973    }
1974
1975    #[pyo3(name = "fault")]
1976    fn py_fault(&mut self) -> PyResult<()> {
1977        Component::fault(self.inner_mut()).map_err(to_pyruntime_err)
1978    }
1979
1980    #[pyo3(name = "shutdown_system")]
1981    #[pyo3(signature = (reason=None))]
1982    fn py_shutdown_system(&self, reason: Option<String>) -> PyResult<()> {
1983        let inner = self.inner();
1984        if !inner.core.actor.is_registered() {
1985            return Err(to_pyruntime_err(
1986                "Strategy must be registered with a trader before shutting down the system",
1987            ));
1988        }
1989
1990        DataActor::shutdown_system(inner, reason);
1991        Ok(())
1992    }
1993
1994    #[getter]
1995    #[pyo3(name = "registered_indicators")]
1996    fn py_registered_indicators(&self, py: Python<'_>) -> PyResult<Py<PyList>> {
1997        let inner = self.inner();
1998        registered_python_indicators(
1999            py,
2000            DataActorNative::core(&inner.core).registered_indicators(),
2001        )
2002    }
2003
2004    #[pyo3(name = "indicators_initialized")]
2005    fn py_indicators_initialized(&self, _py: Python<'_>) -> PyResult<bool> {
2006        let inner = self.inner();
2007        DataActorNative::core(&inner.core)
2008            .indicators_initialized()
2009            .map_err(to_pyruntime_err)
2010    }
2011
2012    #[pyo3(name = "register_indicator_for_quote_ticks")]
2013    fn py_register_indicator_for_quote_ticks(
2014        &mut self,
2015        py: Python<'_>,
2016        instrument_id: InstrumentId,
2017        indicator: Py<PyAny>,
2018    ) {
2019        let indicator = wrap_python_indicator(py, indicator);
2020        let inner = self.inner_mut();
2021        DataActorNative::core_mut(&mut inner.core)
2022            .register_indicator_for_quote_ticks(instrument_id, indicator);
2023    }
2024
2025    #[pyo3(name = "register_indicator_for_trade_ticks")]
2026    fn py_register_indicator_for_trade_ticks(
2027        &mut self,
2028        py: Python<'_>,
2029        instrument_id: InstrumentId,
2030        indicator: Py<PyAny>,
2031    ) {
2032        let indicator = wrap_python_indicator(py, indicator);
2033        let inner = self.inner_mut();
2034        DataActorNative::core_mut(&mut inner.core)
2035            .register_indicator_for_trade_ticks(instrument_id, indicator);
2036    }
2037
2038    #[pyo3(name = "register_indicator_for_bars")]
2039    fn py_register_indicator_for_bars(
2040        &mut self,
2041        py: Python<'_>,
2042        bar_type: BarType,
2043        indicator: Py<PyAny>,
2044    ) {
2045        let indicator = wrap_python_indicator(py, indicator);
2046        let inner = self.inner_mut();
2047        DataActorNative::core_mut(&mut inner.core).register_indicator_for_bars(bar_type, indicator);
2048    }
2049
2050    #[pyo3(name = "submit_order")]
2051    #[pyo3(signature = (order, position_id=None, client_id=None, params=None))]
2052    fn py_submit_order(
2053        &mut self,
2054        py: Python<'_>,
2055        order: Py<PyAny>,
2056        position_id: Option<PositionId>,
2057        client_id: Option<ClientId>,
2058        params: Option<Py<PyDict>>,
2059    ) -> PyResult<()> {
2060        let order = pyobject_to_order_any(py, order)?;
2061        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2062            match params {
2063                Some(dict) => from_pydict(py, &dict),
2064                None => Ok(None),
2065            }
2066        })?;
2067        let inner = self.inner_mut();
2068
2069        Strategy::submit_order(inner, order, position_id, client_id, params_map)
2070            .map_err(to_pyruntime_err)
2071    }
2072
2073    #[pyo3(name = "submit_order_list")]
2074    #[pyo3(signature = (order_list, position_id=None, client_id=None, params=None))]
2075    #[expect(
2076        clippy::needless_pass_by_value,
2077        reason = "PyO3 owns extracted method arguments before Rust conversion"
2078    )]
2079    fn py_submit_order_list(
2080        &mut self,
2081        py: Python<'_>,
2082        order_list: Py<PyAny>,
2083        position_id: Option<PositionId>,
2084        client_id: Option<ClientId>,
2085        params: Option<Py<PyDict>>,
2086    ) -> PyResult<()> {
2087        let orders = py_order_list_to_orders(py, &order_list)?;
2088        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2089            match params {
2090                Some(dict) => from_pydict(py, &dict),
2091                None => Ok(None),
2092            }
2093        })?;
2094        let inner = self.inner_mut();
2095
2096        Strategy::submit_order_list(inner, orders, position_id, client_id, params_map)
2097            .map_err(to_pyruntime_err)
2098    }
2099
2100    #[pyo3(name = "modify_order")]
2101    #[pyo3(signature = (client_order_id, quantity=None, price=None, trigger_price=None, client_id=None, params=None))]
2102    fn py_modify_order(
2103        &mut self,
2104        client_order_id: ClientOrderId,
2105        quantity: Option<Quantity>,
2106        price: Option<Price>,
2107        trigger_price: Option<Price>,
2108        client_id: Option<ClientId>,
2109        params: Option<Py<PyDict>>,
2110    ) -> PyResult<()> {
2111        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2112            match params {
2113                Some(dict) => from_pydict(py, &dict),
2114                None => Ok(None),
2115            }
2116        })?;
2117        let inner = self.inner_mut();
2118
2119        Strategy::modify_order(
2120            inner,
2121            client_order_id,
2122            quantity,
2123            price,
2124            trigger_price,
2125            client_id,
2126            params_map,
2127        )
2128        .map_err(to_pyruntime_err)
2129    }
2130
2131    #[pyo3(name = "modify_orders")]
2132    #[pyo3(signature = (updates, client_id=None, params=None))]
2133    fn py_modify_orders(
2134        &mut self,
2135        updates: Vec<BatchModifyOrder>,
2136        client_id: Option<ClientId>,
2137        params: Option<Py<PyDict>>,
2138    ) -> PyResult<()> {
2139        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2140            match params {
2141                Some(dict) => from_pydict(py, &dict),
2142                None => Ok(None),
2143            }
2144        })?;
2145
2146        Strategy::modify_orders(self.inner_mut(), updates, client_id, params_map)
2147            .map_err(to_pyruntime_err)
2148    }
2149
2150    #[pyo3(name = "cancel_order")]
2151    #[pyo3(signature = (client_order_id, client_id=None, params=None))]
2152    fn py_cancel_order(
2153        &mut self,
2154        client_order_id: ClientOrderId,
2155        client_id: Option<ClientId>,
2156        params: Option<Py<PyDict>>,
2157    ) -> PyResult<()> {
2158        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2159            match params {
2160                Some(dict) => from_pydict(py, &dict),
2161                None => Ok(None),
2162            }
2163        })?;
2164        let inner = self.inner_mut();
2165
2166        Strategy::cancel_order(inner, client_order_id, client_id, params_map)
2167            .map_err(to_pyruntime_err)
2168    }
2169
2170    /// Cancels the managed GTD expiry for the given order.
2171    #[pyo3(name = "cancel_gtd_expiry")]
2172    #[pyo3(signature = (order))]
2173    fn py_cancel_gtd_expiry(&mut self, py: Python<'_>, order: Py<PyAny>) -> PyResult<()> {
2174        let order = pyobject_to_order_any(py, order)?;
2175
2176        Strategy::cancel_gtd_expiry(self.inner_mut(), &order.client_order_id());
2177        Ok(())
2178    }
2179
2180    #[pyo3(name = "cancel_orders")]
2181    #[pyo3(signature = (client_order_ids, client_id=None, params=None))]
2182    fn py_cancel_orders(
2183        &mut self,
2184        client_order_ids: Vec<ClientOrderId>,
2185        client_id: Option<ClientId>,
2186        params: Option<Py<PyDict>>,
2187    ) -> PyResult<()> {
2188        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2189            match params {
2190                Some(dict) => from_pydict(py, &dict),
2191                None => Ok(None),
2192            }
2193        })?;
2194
2195        Strategy::cancel_orders(self.inner_mut(), client_order_ids, client_id, params_map)
2196            .map_err(to_pyruntime_err)
2197    }
2198
2199    #[pyo3(name = "cancel_all_orders")]
2200    #[pyo3(signature = (instrument_id, order_side=None, client_id=None, strategy_only=true, params=None))]
2201    fn py_cancel_all_orders(
2202        &mut self,
2203        instrument_id: InstrumentId,
2204        order_side: Option<OrderSide>,
2205        client_id: Option<ClientId>,
2206        strategy_only: bool,
2207        params: Option<Py<PyDict>>,
2208    ) -> PyResult<()> {
2209        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2210            match params {
2211                Some(dict) => from_pydict(py, &dict),
2212                None => Ok(None),
2213            }
2214        })?;
2215        Strategy::cancel_all_orders(
2216            self.inner_mut(),
2217            instrument_id,
2218            order_side,
2219            client_id,
2220            strategy_only,
2221            params_map,
2222        )
2223        .map_err(to_pyruntime_err)
2224    }
2225
2226    #[pyo3(name = "close_position")]
2227    #[pyo3(signature = (position, client_id=None, tags=None, time_in_force=None, reduce_only=None, quote_quantity=None, params=None))]
2228    #[expect(clippy::too_many_arguments)]
2229    fn py_close_position(
2230        &mut self,
2231        position: &Position,
2232        client_id: Option<ClientId>,
2233        tags: Option<Vec<String>>,
2234        time_in_force: Option<TimeInForce>,
2235        reduce_only: Option<bool>,
2236        quote_quantity: Option<bool>,
2237        params: Option<Py<PyDict>>,
2238    ) -> PyResult<()> {
2239        let tags = tags.map(|t| t.into_iter().map(|s| Ustr::from(&s)).collect());
2240        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2241            match params {
2242                Some(dict) => from_pydict(py, &dict),
2243                None => Ok(None),
2244            }
2245        })?;
2246        Strategy::close_position(
2247            self.inner_mut(),
2248            position,
2249            client_id,
2250            tags,
2251            time_in_force,
2252            reduce_only,
2253            quote_quantity,
2254            params_map,
2255        )
2256        .map_err(to_pyruntime_err)
2257    }
2258
2259    #[pyo3(name = "close_all_positions")]
2260    #[pyo3(signature = (instrument_id, position_side=None, client_id=None, tags=None, time_in_force=None, reduce_only=None, quote_quantity=None, params=None))]
2261    #[expect(clippy::too_many_arguments)]
2262    fn py_close_all_positions(
2263        &mut self,
2264        instrument_id: InstrumentId,
2265        position_side: Option<PositionSide>,
2266        client_id: Option<ClientId>,
2267        tags: Option<Vec<String>>,
2268        time_in_force: Option<TimeInForce>,
2269        reduce_only: Option<bool>,
2270        quote_quantity: Option<bool>,
2271        params: Option<Py<PyDict>>,
2272    ) -> PyResult<()> {
2273        let tags = tags.map(|t| t.into_iter().map(|s| Ustr::from(&s)).collect());
2274        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2275            match params {
2276                Some(dict) => from_pydict(py, &dict),
2277                None => Ok(None),
2278            }
2279        })?;
2280        Strategy::close_all_positions(
2281            self.inner_mut(),
2282            instrument_id,
2283            position_side,
2284            client_id,
2285            tags,
2286            time_in_force,
2287            reduce_only,
2288            quote_quantity,
2289            params_map,
2290        )
2291        .map_err(to_pyruntime_err)
2292    }
2293
2294    #[pyo3(name = "query_account")]
2295    #[pyo3(signature = (account_id, client_id=None, params=None))]
2296    fn py_query_account(
2297        &mut self,
2298        py: Python<'_>,
2299        account_id: AccountId,
2300        client_id: Option<ClientId>,
2301        params: Option<Py<PyDict>>,
2302    ) -> PyResult<()> {
2303        let params_map = match params {
2304            Some(dict) => from_pydict(py, &dict)?,
2305            None => None,
2306        };
2307        Strategy::query_account(self.inner_mut(), account_id, client_id, params_map)
2308            .map_err(to_pyruntime_err)
2309    }
2310
2311    #[pyo3(name = "query_order")]
2312    #[pyo3(signature = (order, client_id=None, params=None))]
2313    fn py_query_order(
2314        &mut self,
2315        py: Python<'_>,
2316        order: Py<PyAny>,
2317        client_id: Option<ClientId>,
2318        params: Option<Py<PyDict>>,
2319    ) -> PyResult<()> {
2320        let order = pyobject_to_order_any(py, order)?;
2321        let order = self
2322            .inner()
2323            .try_cache_ref()
2324            .map_err(to_pyruntime_err)?
2325            .order_owned(&order.client_order_id())
2326            .unwrap_or(order);
2327
2328        let params_map = match params {
2329            Some(dict) => from_pydict(py, &dict)?,
2330            None => None,
2331        };
2332        Strategy::query_order(self.inner_mut(), &order, client_id, params_map)
2333            .map_err(to_pyruntime_err)
2334    }
2335
2336    #[pyo3(name = "on_start")]
2337    fn py_on_start(_slf: &Bound<'_, Self>) {}
2338
2339    #[pyo3(name = "on_stop")]
2340    fn py_on_stop(_slf: &Bound<'_, Self>) {}
2341
2342    #[pyo3(name = "on_resume")]
2343    fn py_on_resume(_slf: &Bound<'_, Self>) {}
2344
2345    #[pyo3(name = "on_reset")]
2346    fn py_on_reset(_slf: &Bound<'_, Self>) {}
2347
2348    #[pyo3(name = "on_dispose")]
2349    fn py_on_dispose(_slf: &Bound<'_, Self>) {}
2350
2351    #[pyo3(name = "on_degrade")]
2352    fn py_on_degrade(_slf: &Bound<'_, Self>) {}
2353
2354    #[pyo3(name = "on_fault")]
2355    fn py_on_fault(_slf: &Bound<'_, Self>) {}
2356
2357    #[pyo3(name = "on_save")]
2358    fn py_on_save(_slf: &Bound<'_, Self>, py: Python<'_>) -> Py<PyDict> {
2359        PyDict::new(py).unbind()
2360    }
2361
2362    #[allow(unused_variables)]
2363    #[pyo3(name = "on_load")]
2364    fn py_on_load(_slf: &Bound<'_, Self>, state: &Bound<'_, PyDict>) {}
2365
2366    #[allow(unused_variables, clippy::needless_pass_by_value)]
2367    #[pyo3(name = "on_time_event")]
2368    fn py_on_time_event(_slf: &Bound<'_, Self>, event: TimeEvent) {}
2369
2370    #[allow(unused_variables, clippy::needless_pass_by_value)]
2371    #[pyo3(name = "on_data")]
2372    fn py_on_data(_slf: &Bound<'_, Self>, data: Py<PyAny>) {}
2373
2374    #[allow(unused_variables)]
2375    #[pyo3(name = "on_signal")]
2376    fn py_on_signal(_slf: &Bound<'_, Self>, signal: &Signal) {}
2377
2378    #[allow(unused_variables, clippy::needless_pass_by_value)]
2379    #[pyo3(name = "on_queue_state")]
2380    fn py_on_queue_state(_slf: &Bound<'_, Self>, event: QueueStateChanged) {}
2381
2382    #[allow(unused_variables, clippy::needless_pass_by_value)]
2383    #[pyo3(name = "on_socket_state")]
2384    fn py_on_socket_state(_slf: &Bound<'_, Self>, event: SocketStateChanged) {}
2385
2386    #[allow(unused_variables, clippy::needless_pass_by_value)]
2387    #[pyo3(name = "on_instrument")]
2388    fn py_on_instrument(_slf: &Bound<'_, Self>, instrument: Py<PyAny>) {}
2389
2390    #[allow(unused_variables)]
2391    #[pyo3(name = "on_quote")]
2392    fn py_on_quote(_slf: &Bound<'_, Self>, quote: QuoteTick) {}
2393
2394    #[allow(unused_variables)]
2395    #[pyo3(name = "on_trade")]
2396    fn py_on_trade(_slf: &Bound<'_, Self>, trade: TradeTick) {}
2397
2398    #[allow(unused_variables)]
2399    #[pyo3(name = "on_bar")]
2400    fn py_on_bar(_slf: &Bound<'_, Self>, bar: Bar) {}
2401
2402    #[allow(unused_variables, clippy::needless_pass_by_value)]
2403    #[pyo3(name = "on_book_deltas")]
2404    fn py_on_book_deltas(_slf: &Bound<'_, Self>, deltas: OrderBookDeltas) {}
2405
2406    #[allow(unused_variables)]
2407    #[pyo3(name = "on_book_depth")]
2408    fn py_on_book_depth(_slf: &Bound<'_, Self>, depth: &OrderBookDepth) {}
2409
2410    #[allow(unused_variables)]
2411    #[pyo3(name = "on_book")]
2412    fn py_on_book(_slf: &Bound<'_, Self>, book: &OrderBook) {}
2413
2414    #[allow(unused_variables)]
2415    #[pyo3(name = "on_mark_price")]
2416    fn py_on_mark_price(_slf: &Bound<'_, Self>, mark_price: MarkPriceUpdate) {}
2417
2418    #[allow(unused_variables)]
2419    #[pyo3(name = "on_index_price")]
2420    fn py_on_index_price(_slf: &Bound<'_, Self>, index_price: IndexPriceUpdate) {}
2421
2422    #[allow(unused_variables)]
2423    #[pyo3(name = "on_funding_rate")]
2424    fn py_on_funding_rate(_slf: &Bound<'_, Self>, funding_rate: FundingRateUpdate) {}
2425
2426    #[allow(unused_variables)]
2427    #[pyo3(name = "on_instrument_status")]
2428    fn py_on_instrument_status(_slf: &Bound<'_, Self>, status: InstrumentStatus) {}
2429
2430    #[allow(unused_variables)]
2431    #[pyo3(name = "on_instrument_close")]
2432    fn py_on_instrument_close(_slf: &Bound<'_, Self>, close: InstrumentClose) {}
2433
2434    #[allow(unused_variables)]
2435    #[pyo3(name = "on_option_greeks")]
2436    fn py_on_option_greeks(_slf: &Bound<'_, Self>, greeks: OptionGreeks) {}
2437
2438    #[allow(unused_variables, clippy::needless_pass_by_value)]
2439    #[pyo3(name = "on_option_chain")]
2440    fn py_on_option_chain(_slf: &Bound<'_, Self>, slice: OptionChainSlice) {}
2441
2442    #[pyo3(name = "on_market_exit")]
2443    fn py_on_market_exit(_slf: &Bound<'_, Self>) {}
2444
2445    #[pyo3(name = "post_market_exit")]
2446    fn py_post_market_exit(_slf: &Bound<'_, Self>) {}
2447
2448    #[allow(unused_variables, clippy::needless_pass_by_value)]
2449    #[pyo3(name = "on_order_initialized")]
2450    fn py_on_order_initialized(_slf: &Bound<'_, Self>, event: OrderInitialized) {}
2451
2452    #[allow(unused_variables, clippy::needless_pass_by_value)]
2453    #[pyo3(name = "on_order_event")]
2454    fn py_on_order_event(_slf: &Bound<'_, Self>, event: Py<PyAny>) {}
2455
2456    #[allow(unused_variables)]
2457    #[pyo3(name = "on_order_denied")]
2458    fn py_on_order_denied(_slf: &Bound<'_, Self>, event: OrderDenied) {}
2459
2460    #[allow(unused_variables)]
2461    #[pyo3(name = "on_order_emulated")]
2462    fn py_on_order_emulated(_slf: &Bound<'_, Self>, event: OrderEmulated) {}
2463
2464    #[allow(unused_variables)]
2465    #[pyo3(name = "on_order_released")]
2466    fn py_on_order_released(_slf: &Bound<'_, Self>, event: OrderReleased) {}
2467
2468    #[allow(unused_variables)]
2469    #[pyo3(name = "on_order_submitted")]
2470    fn py_on_order_submitted(_slf: &Bound<'_, Self>, event: OrderSubmitted) {}
2471
2472    #[allow(unused_variables)]
2473    #[pyo3(name = "on_order_rejected")]
2474    fn py_on_order_rejected(_slf: &Bound<'_, Self>, event: OrderRejected) {}
2475
2476    #[allow(unused_variables)]
2477    #[pyo3(name = "on_order_accepted")]
2478    fn py_on_order_accepted(_slf: &Bound<'_, Self>, event: OrderAccepted) {}
2479
2480    #[allow(unused_variables)]
2481    #[pyo3(name = "on_order_expired")]
2482    fn py_on_order_expired(_slf: &Bound<'_, Self>, event: OrderExpired) {}
2483
2484    #[allow(unused_variables)]
2485    #[pyo3(name = "on_order_triggered")]
2486    fn py_on_order_triggered(_slf: &Bound<'_, Self>, event: OrderTriggered) {}
2487
2488    #[allow(unused_variables)]
2489    #[pyo3(name = "on_order_pending_update")]
2490    fn py_on_order_pending_update(_slf: &Bound<'_, Self>, event: OrderPendingUpdate) {}
2491
2492    #[allow(unused_variables)]
2493    #[pyo3(name = "on_order_pending_cancel")]
2494    fn py_on_order_pending_cancel(_slf: &Bound<'_, Self>, event: OrderPendingCancel) {}
2495
2496    #[allow(unused_variables)]
2497    #[pyo3(name = "on_order_modify_denied")]
2498    fn py_on_order_modify_denied(_slf: &Bound<'_, Self>, event: OrderModifyDenied) {}
2499
2500    #[allow(unused_variables)]
2501    #[pyo3(name = "on_order_modify_rejected")]
2502    fn py_on_order_modify_rejected(_slf: &Bound<'_, Self>, event: OrderModifyRejected) {}
2503
2504    #[allow(unused_variables)]
2505    #[pyo3(name = "on_order_cancel_denied")]
2506    fn py_on_order_cancel_denied(_slf: &Bound<'_, Self>, event: OrderCancelDenied) {}
2507
2508    #[allow(unused_variables)]
2509    #[pyo3(name = "on_order_cancel_rejected")]
2510    fn py_on_order_cancel_rejected(_slf: &Bound<'_, Self>, event: OrderCancelRejected) {}
2511
2512    #[allow(unused_variables)]
2513    #[pyo3(name = "on_order_updated")]
2514    fn py_on_order_updated(_slf: &Bound<'_, Self>, event: OrderUpdated) {}
2515
2516    #[allow(unused_variables)]
2517    #[pyo3(name = "on_order_canceled")]
2518    fn py_on_order_canceled(_slf: &Bound<'_, Self>, event: OrderCanceled) {}
2519
2520    #[allow(unused_variables, clippy::needless_pass_by_value)]
2521    #[pyo3(name = "on_order_filled")]
2522    fn py_on_order_filled(_slf: &Bound<'_, Self>, event: OrderFilled) {}
2523
2524    #[allow(unused_variables, clippy::needless_pass_by_value)]
2525    #[pyo3(name = "on_order_fill_voided")]
2526    fn py_on_order_fill_voided(_slf: &Bound<'_, Self>, event: OrderFillVoided) {}
2527
2528    #[allow(unused_variables, clippy::needless_pass_by_value)]
2529    #[pyo3(name = "on_position_opened")]
2530    fn py_on_position_opened(_slf: &Bound<'_, Self>, event: PositionOpened) {}
2531
2532    #[allow(unused_variables, clippy::needless_pass_by_value)]
2533    #[pyo3(name = "on_position_event")]
2534    fn py_on_position_event(_slf: &Bound<'_, Self>, event: Py<PyAny>) {}
2535
2536    #[allow(unused_variables, clippy::needless_pass_by_value)]
2537    #[pyo3(name = "on_position_changed")]
2538    fn py_on_position_changed(_slf: &Bound<'_, Self>, event: PositionChanged) {}
2539
2540    #[allow(unused_variables, clippy::needless_pass_by_value)]
2541    #[pyo3(name = "on_position_closed")]
2542    fn py_on_position_closed(_slf: &Bound<'_, Self>, event: PositionClosed) {}
2543
2544    #[allow(unused_variables, clippy::needless_pass_by_value)]
2545    #[pyo3(name = "on_data_response")]
2546    fn py_on_data_response(_slf: &Bound<'_, Self>, response: Py<PyDataResponse>) {}
2547
2548    #[allow(unused_variables, clippy::needless_pass_by_value)]
2549    #[pyo3(name = "on_historical_data")]
2550    fn py_on_historical_data(_slf: &Bound<'_, Self>, data: Py<PyAny>) {
2551        // Default implementation - can be overridden in Python subclasses
2552    }
2553
2554    #[allow(unused_variables, clippy::needless_pass_by_value)]
2555    #[pyo3(name = "on_historical_book_deltas")]
2556    fn py_on_historical_book_deltas(_slf: &Bound<'_, Self>, deltas: Vec<OrderBookDelta>) {}
2557
2558    #[allow(unused_variables, clippy::needless_pass_by_value)]
2559    #[pyo3(name = "on_historical_book_depth")]
2560    fn py_on_historical_book_depth(_slf: &Bound<'_, Self>, depths: Vec<OrderBookDepth>) {}
2561
2562    #[allow(unused_variables, clippy::needless_pass_by_value)]
2563    #[pyo3(name = "on_historical_quotes")]
2564    fn py_on_historical_quotes(_slf: &Bound<'_, Self>, quotes: Vec<QuoteTick>) {
2565        // Default implementation - can be overridden in Python subclasses
2566    }
2567
2568    #[allow(unused_variables, clippy::needless_pass_by_value)]
2569    #[pyo3(name = "on_historical_trades")]
2570    fn py_on_historical_trades(_slf: &Bound<'_, Self>, trades: Vec<TradeTick>) {
2571        // Default implementation - can be overridden in Python subclasses
2572    }
2573
2574    #[allow(unused_variables, clippy::needless_pass_by_value)]
2575    #[pyo3(name = "on_historical_funding_rates")]
2576    fn py_on_historical_funding_rates(
2577        _slf: &Bound<'_, Self>,
2578        funding_rates: Vec<FundingRateUpdate>,
2579    ) {
2580        // Default implementation - can be overridden in Python subclasses
2581    }
2582
2583    #[allow(unused_variables, clippy::needless_pass_by_value)]
2584    #[pyo3(name = "on_historical_bars")]
2585    fn py_on_historical_bars(_slf: &Bound<'_, Self>, bars: Vec<Bar>) {
2586        // Default implementation - can be overridden in Python subclasses
2587    }
2588
2589    #[allow(unused_variables, clippy::needless_pass_by_value)]
2590    #[pyo3(name = "on_historical_mark_prices")]
2591    fn py_on_historical_mark_prices(_slf: &Bound<'_, Self>, mark_prices: Vec<MarkPriceUpdate>) {
2592        // Default implementation - can be overridden in Python subclasses
2593    }
2594
2595    #[allow(unused_variables, clippy::needless_pass_by_value)]
2596    #[pyo3(name = "on_historical_index_prices")]
2597    fn py_on_historical_index_prices(_slf: &Bound<'_, Self>, index_prices: Vec<IndexPriceUpdate>) {
2598        // Default implementation - can be overridden in Python subclasses
2599    }
2600
2601    #[pyo3(name = "subscribe_data")]
2602    #[pyo3(signature = (data_type, client_id=None, params=None))]
2603    fn py_subscribe_data(
2604        &mut self,
2605        data_type: DataType,
2606        client_id: Option<ClientId>,
2607        params: Option<Py<PyDict>>,
2608    ) -> PyResult<()> {
2609        self.ensure_registered()?;
2610        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2611            match params {
2612                Some(dict) => from_pydict(py, &dict),
2613                None => Ok(None),
2614            }
2615        })?;
2616        DataActor::subscribe_data(self.inner_mut(), data_type, client_id, params_map);
2617        Ok(())
2618    }
2619
2620    #[pyo3(name = "subscribe_signal")]
2621    #[pyo3(signature = (name="", priority=None))]
2622    fn py_subscribe_signal(&mut self, name: &str, priority: Option<u32>) -> PyResult<()> {
2623        self.ensure_registered()?;
2624        DataActor::subscribe_signal(self.inner_mut(), name, priority);
2625        Ok(())
2626    }
2627
2628    #[pyo3(name = "subscribe_queue_state")]
2629    #[pyo3(signature = (channel=None, priority=None))]
2630    fn py_subscribe_queue_state(
2631        &mut self,
2632        channel: Option<SystemChannel>,
2633        priority: Option<u32>,
2634    ) -> PyResult<()> {
2635        self.ensure_registered()?;
2636        DataActor::subscribe_queue_state(self.inner_mut(), channel, priority);
2637        Ok(())
2638    }
2639
2640    #[pyo3(name = "subscribe_socket_state")]
2641    #[pyo3(signature = (client_id=None, endpoint=None, priority=None))]
2642    fn py_subscribe_socket_state(
2643        &mut self,
2644        client_id: Option<ClientId>,
2645        endpoint: Option<&str>,
2646        priority: Option<u32>,
2647    ) -> PyResult<()> {
2648        self.ensure_registered()?;
2649        DataActor::subscribe_socket_state(self.inner_mut(), client_id, endpoint, priority);
2650        Ok(())
2651    }
2652
2653    #[pyo3(name = "subscribe_instruments")]
2654    #[pyo3(signature = (venue, client_id=None, params=None))]
2655    fn py_subscribe_instruments(
2656        &mut self,
2657        venue: Venue,
2658        client_id: Option<ClientId>,
2659        params: Option<Py<PyDict>>,
2660    ) -> PyResult<()> {
2661        self.ensure_registered()?;
2662        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2663            match params {
2664                Some(dict) => from_pydict(py, &dict),
2665                None => Ok(None),
2666            }
2667        })?;
2668        DataActor::subscribe_instruments(self.inner_mut(), venue, client_id, params_map);
2669        Ok(())
2670    }
2671
2672    #[pyo3(name = "subscribe_instrument")]
2673    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
2674    fn py_subscribe_instrument(
2675        &mut self,
2676        #[gen_stub(override_type(
2677            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
2678        ))]
2679        instrument_id: &Bound<'_, PyAny>,
2680        client_id: Option<ClientId>,
2681        params: Option<Py<PyDict>>,
2682    ) -> PyResult<()> {
2683        self.ensure_registered()?;
2684        let instrument_id = extract_instrument_ids(instrument_id)?;
2685        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
2686            .map_err(to_pyvalue_err)?;
2687        ensure_subscription_routes(
2688            &instrument_id,
2689            client_id.as_ref(),
2690            &DataActorNative::cache_ref(self.inner()),
2691        )
2692        .map_err(to_pyvalue_err)?;
2693
2694        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2695            match params {
2696                Some(dict) => from_pydict(py, &dict),
2697                None => Ok(None),
2698            }
2699        })?;
2700        DataActor::subscribe_instrument(self.inner_mut(), instrument_id, client_id, params_map);
2701        Ok(())
2702    }
2703
2704    #[pyo3(name = "subscribe_book_deltas")]
2705    #[pyo3(signature = (instrument_id, book_type, depth=None, client_id=None, managed=false, params=None))]
2706    fn py_subscribe_book_deltas(
2707        &mut self,
2708        #[gen_stub(override_type(
2709            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
2710        ))]
2711        instrument_id: &Bound<'_, PyAny>,
2712        book_type: BookType,
2713        depth: Option<usize>,
2714        client_id: Option<ClientId>,
2715        managed: bool,
2716        params: Option<Py<PyDict>>,
2717    ) -> PyResult<()> {
2718        self.ensure_registered()?;
2719        let instrument_id = extract_instrument_ids(instrument_id)?;
2720        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
2721            .map_err(to_pyvalue_err)?;
2722        ensure_subscription_routes(
2723            &instrument_id,
2724            client_id.as_ref(),
2725            &DataActorNative::cache_ref(self.inner()),
2726        )
2727        .map_err(to_pyvalue_err)?;
2728
2729        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2730            match params {
2731                Some(dict) => from_pydict(py, &dict),
2732                None => Ok(None),
2733            }
2734        })?;
2735        let depth = depth.and_then(NonZeroUsize::new);
2736        DataActor::subscribe_book_deltas(
2737            self.inner_mut(),
2738            instrument_id,
2739            book_type,
2740            depth,
2741            client_id,
2742            managed,
2743            params_map,
2744        );
2745        Ok(())
2746    }
2747
2748    #[pyo3(name = "subscribe_book_depth")]
2749    #[pyo3(signature = (instrument_id, book_type, depth=None, client_id=None, managed=false, params=None))]
2750    fn py_subscribe_book_depth(
2751        &mut self,
2752        #[gen_stub(override_type(
2753            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
2754        ))]
2755        instrument_id: &Bound<'_, PyAny>,
2756        book_type: BookType,
2757        depth: Option<usize>,
2758        client_id: Option<ClientId>,
2759        managed: bool,
2760        params: Option<Py<PyDict>>,
2761    ) -> PyResult<()> {
2762        self.ensure_registered()?;
2763        let instrument_id = extract_instrument_ids(instrument_id)?;
2764        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
2765            .map_err(to_pyvalue_err)?;
2766        ensure_subscription_routes(
2767            &instrument_id,
2768            client_id.as_ref(),
2769            &DataActorNative::cache_ref(self.inner()),
2770        )
2771        .map_err(to_pyvalue_err)?;
2772
2773        let depth = depth
2774            .map(|value| {
2775                NonZeroUsize::new(value).ok_or_else(|| to_pyvalue_err("depth must be positive"))
2776            })
2777            .transpose()?;
2778
2779        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2780            match params {
2781                Some(dict) => from_pydict(py, &dict),
2782                None => Ok(None),
2783            }
2784        })?;
2785        DataActor::subscribe_book_depth(
2786            self.inner_mut(),
2787            instrument_id,
2788            book_type,
2789            depth,
2790            client_id,
2791            managed,
2792            params_map,
2793        );
2794        Ok(())
2795    }
2796
2797    #[pyo3(name = "subscribe_book_at_interval")]
2798    #[pyo3(signature = (instrument_id, book_type, interval_ms, depth=None, client_id=None, params=None))]
2799    fn py_subscribe_book_at_interval(
2800        &mut self,
2801        #[gen_stub(override_type(
2802            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
2803        ))]
2804        instrument_id: &Bound<'_, PyAny>,
2805        book_type: BookType,
2806        interval_ms: usize,
2807        depth: Option<usize>,
2808        client_id: Option<ClientId>,
2809        params: Option<Py<PyDict>>,
2810    ) -> PyResult<()> {
2811        let interval_ms = NonZeroUsize::new(interval_ms)
2812            .ok_or_else(|| to_pyvalue_err("interval_ms must be > 0"))?;
2813
2814        self.ensure_registered()?;
2815        let instrument_id = extract_instrument_ids(instrument_id)?;
2816        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
2817            .map_err(to_pyvalue_err)?;
2818        ensure_subscription_routes(
2819            &instrument_id,
2820            client_id.as_ref(),
2821            &DataActorNative::cache_ref(self.inner()),
2822        )
2823        .map_err(to_pyvalue_err)?;
2824
2825        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2826            match params {
2827                Some(dict) => from_pydict(py, &dict),
2828                None => Ok(None),
2829            }
2830        })?;
2831        let depth = depth.and_then(NonZeroUsize::new);
2832        DataActor::subscribe_book_at_interval(
2833            self.inner_mut(),
2834            instrument_id,
2835            book_type,
2836            depth,
2837            interval_ms,
2838            client_id,
2839            params_map,
2840        );
2841        Ok(())
2842    }
2843
2844    #[pyo3(name = "subscribe_quotes")]
2845    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
2846    fn py_subscribe_quotes(
2847        &mut self,
2848        #[gen_stub(override_type(
2849            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
2850        ))]
2851        instrument_id: &Bound<'_, PyAny>,
2852        client_id: Option<ClientId>,
2853        params: Option<Py<PyDict>>,
2854    ) -> PyResult<()> {
2855        self.ensure_registered()?;
2856        let instrument_ids = extract_instrument_ids(instrument_id)?;
2857        ensure_routable_instrument_ids(&instrument_ids, client_id.is_some())
2858            .map_err(to_pyvalue_err)?;
2859
2860        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2861            match params {
2862                Some(dict) => from_pydict(py, &dict),
2863                None => Ok(None),
2864            }
2865        })?;
2866
2867        quote_routing(
2868            &instrument_ids,
2869            client_id.as_ref(),
2870            params_map.as_ref(),
2871            &DataActorNative::cache_ref(self.inner()),
2872        )
2873        .map_err(to_pyvalue_err)?;
2874        DataActor::subscribe_quotes(self.inner_mut(), instrument_ids, client_id, params_map);
2875        Ok(())
2876    }
2877
2878    #[pyo3(name = "subscribe_trades")]
2879    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
2880    fn py_subscribe_trades(
2881        &mut self,
2882        #[gen_stub(override_type(
2883            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
2884        ))]
2885        instrument_id: &Bound<'_, PyAny>,
2886        client_id: Option<ClientId>,
2887        params: Option<Py<PyDict>>,
2888    ) -> PyResult<()> {
2889        self.ensure_registered()?;
2890        let instrument_ids = extract_instrument_ids(instrument_id)?;
2891        ensure_routable_instrument_ids(&instrument_ids, client_id.is_some())
2892            .map_err(to_pyvalue_err)?;
2893
2894        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2895            match params {
2896                Some(dict) => from_pydict(py, &dict),
2897                None => Ok(None),
2898            }
2899        })?;
2900
2901        DataActor::subscribe_trades(self.inner_mut(), instrument_ids, client_id, params_map);
2902        Ok(())
2903    }
2904
2905    #[pyo3(name = "subscribe_bars")]
2906    #[pyo3(signature = (bar_type, client_id=None, params=None))]
2907    fn py_subscribe_bars(
2908        &mut self,
2909        #[gen_stub(override_type(type_repr = "model.BarType | typing.Sequence[model.BarType]"))]
2910        bar_type: &Bound<'_, PyAny>,
2911        client_id: Option<ClientId>,
2912        params: Option<Py<PyDict>>,
2913    ) -> PyResult<()> {
2914        self.ensure_registered()?;
2915        let bar_types = extract_bar_types(bar_type)?;
2916        ensure_routable_bar_types(&bar_types, client_id.is_some()).map_err(to_pyvalue_err)?;
2917
2918        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2919            match params {
2920                Some(dict) => from_pydict(py, &dict),
2921                None => Ok(None),
2922            }
2923        })?;
2924
2925        DataActor::subscribe_bars(self.inner_mut(), bar_types, client_id, params_map);
2926        Ok(())
2927    }
2928
2929    #[pyo3(name = "subscribe_mark_prices")]
2930    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
2931    fn py_subscribe_mark_prices(
2932        &mut self,
2933        #[gen_stub(override_type(
2934            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
2935        ))]
2936        instrument_id: &Bound<'_, PyAny>,
2937        client_id: Option<ClientId>,
2938        params: Option<Py<PyDict>>,
2939    ) -> PyResult<()> {
2940        self.ensure_registered()?;
2941        let instrument_id = extract_instrument_ids(instrument_id)?;
2942        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
2943            .map_err(to_pyvalue_err)?;
2944
2945        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2946            match params {
2947                Some(dict) => from_pydict(py, &dict),
2948                None => Ok(None),
2949            }
2950        })?;
2951        DataActor::subscribe_mark_prices(self.inner_mut(), instrument_id, client_id, params_map);
2952        Ok(())
2953    }
2954
2955    #[pyo3(name = "subscribe_index_prices")]
2956    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
2957    fn py_subscribe_index_prices(
2958        &mut self,
2959        #[gen_stub(override_type(
2960            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
2961        ))]
2962        instrument_id: &Bound<'_, PyAny>,
2963        client_id: Option<ClientId>,
2964        params: Option<Py<PyDict>>,
2965    ) -> PyResult<()> {
2966        self.ensure_registered()?;
2967        let instrument_id = extract_instrument_ids(instrument_id)?;
2968        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
2969            .map_err(to_pyvalue_err)?;
2970
2971        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2972            match params {
2973                Some(dict) => from_pydict(py, &dict),
2974                None => Ok(None),
2975            }
2976        })?;
2977        DataActor::subscribe_index_prices(self.inner_mut(), instrument_id, client_id, params_map);
2978        Ok(())
2979    }
2980
2981    #[pyo3(name = "subscribe_funding_rates")]
2982    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
2983    fn py_subscribe_funding_rates(
2984        &mut self,
2985        #[gen_stub(override_type(
2986            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
2987        ))]
2988        instrument_id: &Bound<'_, PyAny>,
2989        client_id: Option<ClientId>,
2990        params: Option<Py<PyDict>>,
2991    ) -> PyResult<()> {
2992        self.ensure_registered()?;
2993        let instrument_id = extract_instrument_ids(instrument_id)?;
2994        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
2995            .map_err(to_pyvalue_err)?;
2996
2997        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
2998            match params {
2999                Some(dict) => from_pydict(py, &dict),
3000                None => Ok(None),
3001            }
3002        })?;
3003        DataActor::subscribe_funding_rates(self.inner_mut(), instrument_id, client_id, params_map);
3004        Ok(())
3005    }
3006
3007    #[pyo3(name = "subscribe_option_greeks")]
3008    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3009    fn py_subscribe_option_greeks(
3010        &mut self,
3011        #[gen_stub(override_type(
3012            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3013        ))]
3014        instrument_id: &Bound<'_, PyAny>,
3015        client_id: Option<ClientId>,
3016        params: Option<Py<PyDict>>,
3017    ) -> PyResult<()> {
3018        self.ensure_registered()?;
3019        let instrument_id = extract_instrument_ids(instrument_id)?;
3020        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3021            .map_err(to_pyvalue_err)?;
3022        ensure_subscription_routes(
3023            &instrument_id,
3024            client_id.as_ref(),
3025            &DataActorNative::cache_ref(self.inner()),
3026        )
3027        .map_err(to_pyvalue_err)?;
3028
3029        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3030            match params {
3031                Some(dict) => from_pydict(py, &dict),
3032                None => Ok(None),
3033            }
3034        })?;
3035        DataActor::subscribe_option_greeks(self.inner_mut(), instrument_id, client_id, params_map);
3036        Ok(())
3037    }
3038
3039    #[pyo3(name = "subscribe_instrument_status")]
3040    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3041    fn py_subscribe_instrument_status(
3042        &mut self,
3043        #[gen_stub(override_type(
3044            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3045        ))]
3046        instrument_id: &Bound<'_, PyAny>,
3047        client_id: Option<ClientId>,
3048        params: Option<Py<PyDict>>,
3049    ) -> PyResult<()> {
3050        self.ensure_registered()?;
3051        let instrument_id = extract_instrument_ids(instrument_id)?;
3052        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3053            .map_err(to_pyvalue_err)?;
3054        ensure_subscription_routes(
3055            &instrument_id,
3056            client_id.as_ref(),
3057            &DataActorNative::cache_ref(self.inner()),
3058        )
3059        .map_err(to_pyvalue_err)?;
3060
3061        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3062            match params {
3063                Some(dict) => from_pydict(py, &dict),
3064                None => Ok(None),
3065            }
3066        })?;
3067        DataActor::subscribe_instrument_status(
3068            self.inner_mut(),
3069            instrument_id,
3070            client_id,
3071            params_map,
3072        );
3073        Ok(())
3074    }
3075
3076    #[pyo3(name = "subscribe_instrument_close")]
3077    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3078    fn py_subscribe_instrument_close(
3079        &mut self,
3080        #[gen_stub(override_type(
3081            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3082        ))]
3083        instrument_id: &Bound<'_, PyAny>,
3084        client_id: Option<ClientId>,
3085        params: Option<Py<PyDict>>,
3086    ) -> PyResult<()> {
3087        self.ensure_registered()?;
3088        let instrument_id = extract_instrument_ids(instrument_id)?;
3089        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3090            .map_err(to_pyvalue_err)?;
3091        ensure_subscription_routes(
3092            &instrument_id,
3093            client_id.as_ref(),
3094            &DataActorNative::cache_ref(self.inner()),
3095        )
3096        .map_err(to_pyvalue_err)?;
3097
3098        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3099            match params {
3100                Some(dict) => from_pydict(py, &dict),
3101                None => Ok(None),
3102            }
3103        })?;
3104        DataActor::subscribe_instrument_close(
3105            self.inner_mut(),
3106            instrument_id,
3107            client_id,
3108            params_map,
3109        );
3110        Ok(())
3111    }
3112
3113    #[pyo3(name = "subscribe_option_chain")]
3114    #[pyo3(signature = (series_id, strike_range, snapshot_interval_ms=None, client_id=None, params=None))]
3115    fn py_subscribe_option_chain(
3116        &mut self,
3117        py: Python<'_>,
3118        series_id: OptionSeriesId,
3119        strike_range: PyStrikeRange,
3120        snapshot_interval_ms: Option<u64>,
3121        client_id: Option<ClientId>,
3122        params: Option<Py<PyDict>>,
3123    ) -> PyResult<()> {
3124        self.ensure_registered()?;
3125        let params_map = match params {
3126            Some(dict) => from_pydict(py, &dict)?,
3127            None => None,
3128        };
3129        DataActor::subscribe_option_chain(
3130            self.inner_mut(),
3131            series_id,
3132            strike_range.inner,
3133            snapshot_interval_ms,
3134            client_id,
3135            params_map,
3136        )
3137        .map_err(to_pyvalue_err)?;
3138        Ok(())
3139    }
3140
3141    #[pyo3(name = "unsubscribe_data")]
3142    #[pyo3(signature = (data_type, client_id=None, params=None))]
3143    fn py_unsubscribe_data(
3144        &mut self,
3145        data_type: DataType,
3146        client_id: Option<ClientId>,
3147        params: Option<Py<PyDict>>,
3148    ) -> PyResult<()> {
3149        self.ensure_registered()?;
3150        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3151            match params {
3152                Some(dict) => from_pydict(py, &dict),
3153                None => Ok(None),
3154            }
3155        })?;
3156        DataActor::unsubscribe_data(self.inner_mut(), data_type, client_id, params_map);
3157        Ok(())
3158    }
3159
3160    #[pyo3(name = "unsubscribe_signal")]
3161    fn py_unsubscribe_signal(&mut self, name: &str) -> PyResult<()> {
3162        self.ensure_registered()?;
3163        DataActor::unsubscribe_signal(self.inner_mut(), name);
3164        Ok(())
3165    }
3166
3167    #[pyo3(name = "unsubscribe_queue_state")]
3168    #[pyo3(signature = (channel=None))]
3169    fn py_unsubscribe_queue_state(&mut self, channel: Option<SystemChannel>) -> PyResult<()> {
3170        self.ensure_registered()?;
3171        DataActor::unsubscribe_queue_state(self.inner_mut(), channel);
3172        Ok(())
3173    }
3174
3175    #[pyo3(name = "unsubscribe_socket_state")]
3176    #[pyo3(signature = (client_id=None, endpoint=None))]
3177    fn py_unsubscribe_socket_state(
3178        &mut self,
3179        client_id: Option<ClientId>,
3180        endpoint: Option<&str>,
3181    ) -> PyResult<()> {
3182        self.ensure_registered()?;
3183        DataActor::unsubscribe_socket_state(self.inner_mut(), client_id, endpoint);
3184        Ok(())
3185    }
3186
3187    #[pyo3(name = "unsubscribe_instruments")]
3188    #[pyo3(signature = (venue, client_id=None, params=None))]
3189    fn py_unsubscribe_instruments(
3190        &mut self,
3191        venue: Venue,
3192        client_id: Option<ClientId>,
3193        params: Option<Py<PyDict>>,
3194    ) -> PyResult<()> {
3195        self.ensure_registered()?;
3196        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3197            match params {
3198                Some(dict) => from_pydict(py, &dict),
3199                None => Ok(None),
3200            }
3201        })?;
3202        DataActor::unsubscribe_instruments(self.inner_mut(), venue, client_id, params_map);
3203        Ok(())
3204    }
3205
3206    #[pyo3(name = "unsubscribe_instrument")]
3207    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3208    fn py_unsubscribe_instrument(
3209        &mut self,
3210        #[gen_stub(override_type(
3211            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3212        ))]
3213        instrument_id: &Bound<'_, PyAny>,
3214        client_id: Option<ClientId>,
3215        params: Option<Py<PyDict>>,
3216    ) -> PyResult<()> {
3217        self.ensure_registered()?;
3218        let instrument_id = extract_instrument_ids(instrument_id)?;
3219        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3220            .map_err(to_pyvalue_err)?;
3221
3222        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3223            match params {
3224                Some(dict) => from_pydict(py, &dict),
3225                None => Ok(None),
3226            }
3227        })?;
3228        DataActor::unsubscribe_instrument(self.inner_mut(), instrument_id, client_id, params_map);
3229        Ok(())
3230    }
3231
3232    #[pyo3(name = "unsubscribe_book_deltas")]
3233    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3234    fn py_unsubscribe_book_deltas(
3235        &mut self,
3236        #[gen_stub(override_type(
3237            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3238        ))]
3239        instrument_id: &Bound<'_, PyAny>,
3240        client_id: Option<ClientId>,
3241        params: Option<Py<PyDict>>,
3242    ) -> PyResult<()> {
3243        self.ensure_registered()?;
3244        let instrument_id = extract_instrument_ids(instrument_id)?;
3245        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3246            .map_err(to_pyvalue_err)?;
3247
3248        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3249            match params {
3250                Some(dict) => from_pydict(py, &dict),
3251                None => Ok(None),
3252            }
3253        })?;
3254        DataActor::unsubscribe_book_deltas(self.inner_mut(), instrument_id, client_id, params_map);
3255        Ok(())
3256    }
3257
3258    #[pyo3(name = "unsubscribe_book_depth")]
3259    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3260    fn py_unsubscribe_book_depth(
3261        &mut self,
3262        #[gen_stub(override_type(
3263            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3264        ))]
3265        instrument_id: &Bound<'_, PyAny>,
3266        client_id: Option<ClientId>,
3267        params: Option<Py<PyDict>>,
3268    ) -> PyResult<()> {
3269        self.ensure_registered()?;
3270        let instrument_id = extract_instrument_ids(instrument_id)?;
3271        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3272            .map_err(to_pyvalue_err)?;
3273
3274        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3275            match params {
3276                Some(dict) => from_pydict(py, &dict),
3277                None => Ok(None),
3278            }
3279        })?;
3280        DataActor::unsubscribe_book_depth(self.inner_mut(), instrument_id, client_id, params_map);
3281        Ok(())
3282    }
3283
3284    #[pyo3(name = "unsubscribe_book_at_interval")]
3285    #[pyo3(signature = (instrument_id, interval_ms, client_id=None, params=None))]
3286    fn py_unsubscribe_book_at_interval(
3287        &mut self,
3288        #[gen_stub(override_type(
3289            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3290        ))]
3291        instrument_id: &Bound<'_, PyAny>,
3292        interval_ms: usize,
3293        client_id: Option<ClientId>,
3294        params: Option<Py<PyDict>>,
3295    ) -> PyResult<()> {
3296        let interval_ms = NonZeroUsize::new(interval_ms)
3297            .ok_or_else(|| to_pyvalue_err("interval_ms must be > 0"))?;
3298
3299        self.ensure_registered()?;
3300        let instrument_id = extract_instrument_ids(instrument_id)?;
3301        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3302            .map_err(to_pyvalue_err)?;
3303
3304        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3305            match params {
3306                Some(dict) => from_pydict(py, &dict),
3307                None => Ok(None),
3308            }
3309        })?;
3310        DataActor::unsubscribe_book_at_interval(
3311            self.inner_mut(),
3312            instrument_id,
3313            interval_ms,
3314            client_id,
3315            params_map,
3316        );
3317        Ok(())
3318    }
3319
3320    #[pyo3(name = "unsubscribe_quotes")]
3321    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3322    fn py_unsubscribe_quotes(
3323        &mut self,
3324        #[gen_stub(override_type(
3325            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3326        ))]
3327        instrument_id: &Bound<'_, PyAny>,
3328        client_id: Option<ClientId>,
3329        params: Option<Py<PyDict>>,
3330    ) -> PyResult<()> {
3331        self.ensure_registered()?;
3332        let instrument_ids = extract_instrument_ids(instrument_id)?;
3333        ensure_routable_instrument_ids(&instrument_ids, client_id.is_some())
3334            .map_err(to_pyvalue_err)?;
3335
3336        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3337            match params {
3338                Some(dict) => from_pydict(py, &dict),
3339                None => Ok(None),
3340            }
3341        })?;
3342
3343        DataActor::unsubscribe_quotes(self.inner_mut(), instrument_ids, client_id, params_map);
3344        Ok(())
3345    }
3346
3347    #[pyo3(name = "unsubscribe_trades")]
3348    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3349    fn py_unsubscribe_trades(
3350        &mut self,
3351        #[gen_stub(override_type(
3352            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3353        ))]
3354        instrument_id: &Bound<'_, PyAny>,
3355        client_id: Option<ClientId>,
3356        params: Option<Py<PyDict>>,
3357    ) -> PyResult<()> {
3358        self.ensure_registered()?;
3359        let instrument_ids = extract_instrument_ids(instrument_id)?;
3360        ensure_routable_instrument_ids(&instrument_ids, client_id.is_some())
3361            .map_err(to_pyvalue_err)?;
3362
3363        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3364            match params {
3365                Some(dict) => from_pydict(py, &dict),
3366                None => Ok(None),
3367            }
3368        })?;
3369
3370        DataActor::unsubscribe_trades(self.inner_mut(), instrument_ids, client_id, params_map);
3371        Ok(())
3372    }
3373
3374    #[pyo3(name = "unsubscribe_bars")]
3375    #[pyo3(signature = (bar_type, client_id=None, params=None))]
3376    fn py_unsubscribe_bars(
3377        &mut self,
3378        #[gen_stub(override_type(type_repr = "model.BarType | typing.Sequence[model.BarType]"))]
3379        bar_type: &Bound<'_, PyAny>,
3380        client_id: Option<ClientId>,
3381        params: Option<Py<PyDict>>,
3382    ) -> PyResult<()> {
3383        self.ensure_registered()?;
3384        let bar_types = extract_bar_types(bar_type)?;
3385        ensure_routable_bar_types(&bar_types, client_id.is_some()).map_err(to_pyvalue_err)?;
3386
3387        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3388            match params {
3389                Some(dict) => from_pydict(py, &dict),
3390                None => Ok(None),
3391            }
3392        })?;
3393
3394        DataActor::unsubscribe_bars(self.inner_mut(), bar_types, client_id, params_map);
3395        Ok(())
3396    }
3397
3398    #[pyo3(name = "unsubscribe_mark_prices")]
3399    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3400    fn py_unsubscribe_mark_prices(
3401        &mut self,
3402        #[gen_stub(override_type(
3403            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3404        ))]
3405        instrument_id: &Bound<'_, PyAny>,
3406        client_id: Option<ClientId>,
3407        params: Option<Py<PyDict>>,
3408    ) -> PyResult<()> {
3409        self.ensure_registered()?;
3410        let instrument_id = extract_instrument_ids(instrument_id)?;
3411        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3412            .map_err(to_pyvalue_err)?;
3413
3414        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3415            match params {
3416                Some(dict) => from_pydict(py, &dict),
3417                None => Ok(None),
3418            }
3419        })?;
3420        DataActor::unsubscribe_mark_prices(self.inner_mut(), instrument_id, client_id, params_map);
3421        Ok(())
3422    }
3423
3424    #[pyo3(name = "unsubscribe_index_prices")]
3425    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3426    fn py_unsubscribe_index_prices(
3427        &mut self,
3428        #[gen_stub(override_type(
3429            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3430        ))]
3431        instrument_id: &Bound<'_, PyAny>,
3432        client_id: Option<ClientId>,
3433        params: Option<Py<PyDict>>,
3434    ) -> PyResult<()> {
3435        self.ensure_registered()?;
3436        let instrument_id = extract_instrument_ids(instrument_id)?;
3437        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3438            .map_err(to_pyvalue_err)?;
3439
3440        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3441            match params {
3442                Some(dict) => from_pydict(py, &dict),
3443                None => Ok(None),
3444            }
3445        })?;
3446        DataActor::unsubscribe_index_prices(self.inner_mut(), instrument_id, client_id, params_map);
3447        Ok(())
3448    }
3449
3450    #[pyo3(name = "unsubscribe_funding_rates")]
3451    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3452    fn py_unsubscribe_funding_rates(
3453        &mut self,
3454        #[gen_stub(override_type(
3455            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3456        ))]
3457        instrument_id: &Bound<'_, PyAny>,
3458        client_id: Option<ClientId>,
3459        params: Option<Py<PyDict>>,
3460    ) -> PyResult<()> {
3461        self.ensure_registered()?;
3462        let instrument_id = extract_instrument_ids(instrument_id)?;
3463        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3464            .map_err(to_pyvalue_err)?;
3465
3466        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3467            match params {
3468                Some(dict) => from_pydict(py, &dict),
3469                None => Ok(None),
3470            }
3471        })?;
3472        DataActor::unsubscribe_funding_rates(
3473            self.inner_mut(),
3474            instrument_id,
3475            client_id,
3476            params_map,
3477        );
3478        Ok(())
3479    }
3480
3481    #[pyo3(name = "unsubscribe_option_greeks")]
3482    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3483    fn py_unsubscribe_option_greeks(
3484        &mut self,
3485        #[gen_stub(override_type(
3486            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3487        ))]
3488        instrument_id: &Bound<'_, PyAny>,
3489        client_id: Option<ClientId>,
3490        params: Option<Py<PyDict>>,
3491    ) -> PyResult<()> {
3492        self.ensure_registered()?;
3493        let instrument_id = extract_instrument_ids(instrument_id)?;
3494        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3495            .map_err(to_pyvalue_err)?;
3496
3497        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3498            match params {
3499                Some(dict) => from_pydict(py, &dict),
3500                None => Ok(None),
3501            }
3502        })?;
3503        DataActor::unsubscribe_option_greeks(
3504            self.inner_mut(),
3505            instrument_id,
3506            client_id,
3507            params_map,
3508        );
3509        Ok(())
3510    }
3511
3512    #[pyo3(name = "unsubscribe_instrument_status")]
3513    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3514    fn py_unsubscribe_instrument_status(
3515        &mut self,
3516        #[gen_stub(override_type(
3517            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3518        ))]
3519        instrument_id: &Bound<'_, PyAny>,
3520        client_id: Option<ClientId>,
3521        params: Option<Py<PyDict>>,
3522    ) -> PyResult<()> {
3523        self.ensure_registered()?;
3524        let instrument_id = extract_instrument_ids(instrument_id)?;
3525        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3526            .map_err(to_pyvalue_err)?;
3527
3528        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3529            match params {
3530                Some(dict) => from_pydict(py, &dict),
3531                None => Ok(None),
3532            }
3533        })?;
3534        DataActor::unsubscribe_instrument_status(
3535            self.inner_mut(),
3536            instrument_id,
3537            client_id,
3538            params_map,
3539        );
3540        Ok(())
3541    }
3542
3543    #[pyo3(name = "unsubscribe_instrument_close")]
3544    #[pyo3(signature = (instrument_id, client_id=None, params=None))]
3545    fn py_unsubscribe_instrument_close(
3546        &mut self,
3547        #[gen_stub(override_type(
3548            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3549        ))]
3550        instrument_id: &Bound<'_, PyAny>,
3551        client_id: Option<ClientId>,
3552        params: Option<Py<PyDict>>,
3553    ) -> PyResult<()> {
3554        self.ensure_registered()?;
3555        let instrument_id = extract_instrument_ids(instrument_id)?;
3556        ensure_routable_instrument_ids(&instrument_id, client_id.is_some())
3557            .map_err(to_pyvalue_err)?;
3558
3559        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3560            match params {
3561                Some(dict) => from_pydict(py, &dict),
3562                None => Ok(None),
3563            }
3564        })?;
3565        DataActor::unsubscribe_instrument_close(
3566            self.inner_mut(),
3567            instrument_id,
3568            client_id,
3569            params_map,
3570        );
3571        Ok(())
3572    }
3573
3574    #[pyo3(name = "unsubscribe_option_chain")]
3575    #[pyo3(signature = (series_id, client_id=None))]
3576    fn py_unsubscribe_option_chain(
3577        &mut self,
3578        series_id: OptionSeriesId,
3579        client_id: Option<ClientId>,
3580    ) -> PyResult<()> {
3581        self.ensure_registered()?;
3582        DataActor::unsubscribe_option_chain(self.inner_mut(), series_id, client_id);
3583        Ok(())
3584    }
3585
3586    #[pyo3(name = "request_data")]
3587    #[pyo3(signature = (data_type, client_id, start=None, end=None, limit=None, params=None, callback=None))]
3588    #[expect(clippy::too_many_arguments)]
3589    fn py_request_data(
3590        slf: &Bound<'_, Self>,
3591        py: Python<'_>,
3592        data_type: DataType,
3593        client_id: ClientId,
3594        start: Option<Timestamp>,
3595        end: Option<Timestamp>,
3596        limit: Option<usize>,
3597        params: Option<Py<PyDict>>,
3598        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
3599        callback: Option<Py<PyAny>>,
3600    ) -> PyResult<String> {
3601        let actor = Self {
3602            inner: Rc::clone(&slf.try_borrow()?.inner),
3603        };
3604
3605        actor.ensure_registered_for_data()?;
3606
3607        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3608            match params {
3609                Some(dict) => from_pydict(py, &dict),
3610                None => Ok(None),
3611            }
3612        })?;
3613        let limit = limit.and_then(NonZeroUsize::new);
3614        let handler = nautilus_common::python::response::request_handler(
3615            py,
3616            actor.inner().core().actor_id().inner(),
3617            PyStrategyInner::python_instance,
3618            callback,
3619        )?;
3620        let request_id = DataActorCore::request_data(
3621            actor.inner().core(),
3622            data_type,
3623            client_id,
3624            start,
3625            end,
3626            limit,
3627            params_map,
3628            handler,
3629        )
3630        .map_err(to_pyvalue_err)?;
3631        Ok(request_id.to_string())
3632    }
3633
3634    #[pyo3(name = "request_instrument")]
3635    #[pyo3(signature = (instrument_id, start=None, end=None, client_id=None, params=None, callback=None))]
3636    #[expect(clippy::too_many_arguments)]
3637    fn py_request_instrument(
3638        slf: &Bound<'_, Self>,
3639        py: Python<'_>,
3640        #[gen_stub(override_type(
3641            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3642        ))]
3643        instrument_id: &Bound<'_, PyAny>,
3644        start: Option<Timestamp>,
3645        end: Option<Timestamp>,
3646        client_id: Option<ClientId>,
3647        params: Option<Py<PyDict>>,
3648        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
3649        callback: Option<Py<PyAny>>,
3650    ) -> PyResult<String> {
3651        let actor = Self {
3652            inner: Rc::clone(&slf.try_borrow()?.inner),
3653        };
3654
3655        let instrument_id = extract_instrument_ids(instrument_id)?;
3656        actor.ensure_registered_for_data()?;
3657
3658        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3659            match params {
3660                Some(dict) => from_pydict(py, &dict),
3661                None => Ok(None),
3662            }
3663        })?;
3664
3665        let handler = nautilus_common::python::response::request_handler(
3666            py,
3667            actor.inner().core().actor_id().inner(),
3668            PyStrategyInner::python_instance,
3669            callback,
3670        )?;
3671        let request_id = DataActorCore::request_instrument(
3672            actor.inner().core(),
3673            instrument_id,
3674            start,
3675            end,
3676            client_id,
3677            params_map,
3678            handler,
3679        )
3680        .map_err(to_pyvalue_err)?;
3681        Ok(request_id.to_string())
3682    }
3683
3684    #[pyo3(name = "request_instruments")]
3685    #[pyo3(signature = (venue=None, start=None, end=None, client_id=None, params=None, callback=None))]
3686    #[expect(clippy::too_many_arguments)]
3687    fn py_request_instruments(
3688        slf: &Bound<'_, Self>,
3689        py: Python<'_>,
3690        venue: Option<Venue>,
3691        start: Option<Timestamp>,
3692        end: Option<Timestamp>,
3693        client_id: Option<ClientId>,
3694        params: Option<Py<PyDict>>,
3695        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
3696        callback: Option<Py<PyAny>>,
3697    ) -> PyResult<String> {
3698        let actor = Self {
3699            inner: Rc::clone(&slf.try_borrow()?.inner),
3700        };
3701
3702        actor.ensure_registered_for_data()?;
3703
3704        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3705            match params {
3706                Some(dict) => from_pydict(py, &dict),
3707                None => Ok(None),
3708            }
3709        })?;
3710
3711        let handler = nautilus_common::python::response::request_handler(
3712            py,
3713            actor.inner().core().actor_id().inner(),
3714            PyStrategyInner::python_instance,
3715            callback,
3716        )?;
3717        let request_id = DataActorCore::request_instruments(
3718            actor.inner().core(),
3719            venue,
3720            start,
3721            end,
3722            client_id,
3723            params_map,
3724            handler,
3725        )
3726        .map_err(to_pyvalue_err)?;
3727        Ok(request_id.to_string())
3728    }
3729
3730    #[pyo3(name = "request_book_snapshot")]
3731    #[pyo3(signature = (instrument_id, depth=None, client_id=None, params=None, callback=None))]
3732    fn py_request_book_snapshot(
3733        slf: &Bound<'_, Self>,
3734        py: Python<'_>,
3735        #[gen_stub(override_type(
3736            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3737        ))]
3738        instrument_id: &Bound<'_, PyAny>,
3739        depth: Option<usize>,
3740        client_id: Option<ClientId>,
3741        params: Option<Py<PyDict>>,
3742        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
3743        callback: Option<Py<PyAny>>,
3744    ) -> PyResult<String> {
3745        let actor = Self {
3746            inner: Rc::clone(&slf.try_borrow()?.inner),
3747        };
3748
3749        let instrument_id = extract_instrument_ids(instrument_id)?;
3750        actor.ensure_registered_for_data()?;
3751
3752        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3753            match params {
3754                Some(dict) => from_pydict(py, &dict),
3755                None => Ok(None),
3756            }
3757        })?;
3758        let depth = depth.and_then(NonZeroUsize::new);
3759
3760        let handler = nautilus_common::python::response::request_handler(
3761            py,
3762            actor.inner().core().actor_id().inner(),
3763            PyStrategyInner::python_instance,
3764            callback,
3765        )?;
3766        let request_id = DataActorCore::request_book_snapshot(
3767            actor.inner().core(),
3768            instrument_id,
3769            depth,
3770            client_id,
3771            params_map,
3772            handler,
3773        )
3774        .map_err(to_pyvalue_err)?;
3775        Ok(request_id.to_string())
3776    }
3777
3778    #[pyo3(name = "request_book_deltas")]
3779    #[pyo3(signature = (instrument_id, start=None, end=None, limit=None, client_id=None, params=None, callback=None))]
3780    #[expect(clippy::too_many_arguments)]
3781    fn py_request_book_deltas(
3782        slf: &Bound<'_, Self>,
3783        py: Python<'_>,
3784        #[gen_stub(override_type(
3785            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3786        ))]
3787        instrument_id: &Bound<'_, PyAny>,
3788        start: Option<Timestamp>,
3789        end: Option<Timestamp>,
3790        limit: Option<usize>,
3791        client_id: Option<ClientId>,
3792        params: Option<Py<PyDict>>,
3793        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
3794        callback: Option<Py<PyAny>>,
3795    ) -> PyResult<String> {
3796        let actor = Self {
3797            inner: Rc::clone(&slf.try_borrow()?.inner),
3798        };
3799
3800        let instrument_id = extract_instrument_ids(instrument_id)?;
3801        actor.ensure_registered_for_data()?;
3802
3803        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3804            match params {
3805                Some(dict) => from_pydict(py, &dict),
3806                None => Ok(None),
3807            }
3808        })?;
3809        let limit = limit.and_then(NonZeroUsize::new);
3810        let handler = nautilus_common::python::response::request_handler(
3811            py,
3812            actor.inner().core().actor_id().inner(),
3813            PyStrategyInner::python_instance,
3814            callback,
3815        )?;
3816        let request_id = DataActorCore::request_book_deltas(
3817            actor.inner().core(),
3818            instrument_id,
3819            start,
3820            end,
3821            limit,
3822            client_id,
3823            params_map,
3824            handler,
3825        )
3826        .map_err(to_pyvalue_err)?;
3827        Ok(request_id.to_string())
3828    }
3829
3830    #[pyo3(name = "request_book_depth")]
3831    #[pyo3(signature = (instrument_id, start=None, end=None, limit=None, depth=None, client_id=None, params=None, callback=None))]
3832    #[expect(clippy::too_many_arguments)]
3833    fn py_request_book_depth(
3834        slf: &Bound<'_, Self>,
3835        py: Python<'_>,
3836        #[gen_stub(override_type(
3837            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3838        ))]
3839        instrument_id: &Bound<'_, PyAny>,
3840        start: Option<Timestamp>,
3841        end: Option<Timestamp>,
3842        limit: Option<usize>,
3843        depth: Option<usize>,
3844        client_id: Option<ClientId>,
3845        params: Option<Py<PyDict>>,
3846        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
3847        callback: Option<Py<PyAny>>,
3848    ) -> PyResult<String> {
3849        let actor = Self {
3850            inner: Rc::clone(&slf.try_borrow()?.inner),
3851        };
3852
3853        let instrument_id = extract_instrument_ids(instrument_id)?;
3854        actor.ensure_registered_for_data()?;
3855
3856        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3857            match params {
3858                Some(dict) => from_pydict(py, &dict),
3859                None => Ok(None),
3860            }
3861        })?;
3862        let limit = limit.and_then(NonZeroUsize::new);
3863        let depth = depth.and_then(NonZeroUsize::new);
3864        let handler = nautilus_common::python::response::request_handler(
3865            py,
3866            actor.inner().core().actor_id().inner(),
3867            PyStrategyInner::python_instance,
3868            callback,
3869        )?;
3870        let request_id = DataActorCore::request_book_depth(
3871            actor.inner().core(),
3872            instrument_id,
3873            start,
3874            end,
3875            limit,
3876            depth,
3877            client_id,
3878            params_map,
3879            handler,
3880        )
3881        .map_err(to_pyvalue_err)?;
3882        Ok(request_id.to_string())
3883    }
3884
3885    #[pyo3(name = "request_quotes")]
3886    #[pyo3(signature = (instrument_id, start=None, end=None, limit=None, client_id=None, params=None, callback=None))]
3887    #[expect(clippy::too_many_arguments)]
3888    fn py_request_quotes(
3889        slf: &Bound<'_, Self>,
3890        py: Python<'_>,
3891        #[gen_stub(override_type(
3892            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3893        ))]
3894        instrument_id: &Bound<'_, PyAny>,
3895        start: Option<Timestamp>,
3896        end: Option<Timestamp>,
3897        limit: Option<usize>,
3898        client_id: Option<ClientId>,
3899        params: Option<Py<PyDict>>,
3900        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
3901        callback: Option<Py<PyAny>>,
3902    ) -> PyResult<String> {
3903        let actor = Self {
3904            inner: Rc::clone(&slf.try_borrow()?.inner),
3905        };
3906
3907        let instrument_id = extract_instrument_ids(instrument_id)?;
3908        actor.ensure_registered_for_data()?;
3909
3910        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3911            match params {
3912                Some(dict) => from_pydict(py, &dict),
3913                None => Ok(None),
3914            }
3915        })?;
3916        let limit = limit.and_then(NonZeroUsize::new);
3917        let handler = nautilus_common::python::response::request_handler(
3918            py,
3919            actor.inner().core().actor_id().inner(),
3920            PyStrategyInner::python_instance,
3921            callback,
3922        )?;
3923        let request_id = DataActorCore::request_quotes(
3924            actor.inner().core(),
3925            instrument_id,
3926            start,
3927            end,
3928            limit,
3929            client_id,
3930            params_map,
3931            handler,
3932        )
3933        .map_err(to_pyvalue_err)?;
3934        Ok(request_id.to_string())
3935    }
3936
3937    #[pyo3(name = "request_trades")]
3938    #[pyo3(signature = (instrument_id, start=None, end=None, limit=None, client_id=None, params=None, callback=None))]
3939    #[expect(clippy::too_many_arguments)]
3940    fn py_request_trades(
3941        slf: &Bound<'_, Self>,
3942        py: Python<'_>,
3943        #[gen_stub(override_type(
3944            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3945        ))]
3946        instrument_id: &Bound<'_, PyAny>,
3947        start: Option<Timestamp>,
3948        end: Option<Timestamp>,
3949        limit: Option<usize>,
3950        client_id: Option<ClientId>,
3951        params: Option<Py<PyDict>>,
3952        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
3953        callback: Option<Py<PyAny>>,
3954    ) -> PyResult<String> {
3955        let actor = Self {
3956            inner: Rc::clone(&slf.try_borrow()?.inner),
3957        };
3958
3959        let instrument_id = extract_instrument_ids(instrument_id)?;
3960        actor.ensure_registered_for_data()?;
3961
3962        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
3963            match params {
3964                Some(dict) => from_pydict(py, &dict),
3965                None => Ok(None),
3966            }
3967        })?;
3968        let limit = limit.and_then(NonZeroUsize::new);
3969        let handler = nautilus_common::python::response::request_handler(
3970            py,
3971            actor.inner().core().actor_id().inner(),
3972            PyStrategyInner::python_instance,
3973            callback,
3974        )?;
3975        let request_id = DataActorCore::request_trades(
3976            actor.inner().core(),
3977            instrument_id,
3978            start,
3979            end,
3980            limit,
3981            client_id,
3982            params_map,
3983            handler,
3984        )
3985        .map_err(to_pyvalue_err)?;
3986        Ok(request_id.to_string())
3987    }
3988
3989    #[pyo3(name = "request_funding_rates")]
3990    #[pyo3(signature = (instrument_id, start=None, end=None, limit=None, client_id=None, params=None, callback=None))]
3991    #[expect(clippy::too_many_arguments)]
3992    fn py_request_funding_rates(
3993        slf: &Bound<'_, Self>,
3994        py: Python<'_>,
3995        #[gen_stub(override_type(
3996            type_repr = "model.InstrumentId | typing.Sequence[model.InstrumentId]"
3997        ))]
3998        instrument_id: &Bound<'_, PyAny>,
3999        start: Option<Timestamp>,
4000        end: Option<Timestamp>,
4001        limit: Option<usize>,
4002        client_id: Option<ClientId>,
4003        params: Option<Py<PyDict>>,
4004        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
4005        callback: Option<Py<PyAny>>,
4006    ) -> PyResult<String> {
4007        let actor = Self {
4008            inner: Rc::clone(&slf.try_borrow()?.inner),
4009        };
4010
4011        let instrument_id = extract_instrument_ids(instrument_id)?;
4012        actor.ensure_registered_for_data()?;
4013
4014        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
4015            match params {
4016                Some(dict) => from_pydict(py, &dict),
4017                None => Ok(None),
4018            }
4019        })?;
4020        let limit = limit.and_then(NonZeroUsize::new);
4021        let handler = nautilus_common::python::response::request_handler(
4022            py,
4023            actor.inner().core().actor_id().inner(),
4024            PyStrategyInner::python_instance,
4025            callback,
4026        )?;
4027        let request_id = DataActorCore::request_funding_rates(
4028            actor.inner().core(),
4029            instrument_id,
4030            start,
4031            end,
4032            limit,
4033            client_id,
4034            params_map,
4035            handler,
4036        )
4037        .map_err(to_pyvalue_err)?;
4038        Ok(request_id.to_string())
4039    }
4040
4041    #[pyo3(name = "request_bars")]
4042    #[pyo3(signature = (bar_type, start=None, end=None, limit=None, client_id=None, params=None, callback=None))]
4043    #[expect(clippy::too_many_arguments)]
4044    fn py_request_bars(
4045        slf: &Bound<'_, Self>,
4046        py: Python<'_>,
4047        #[gen_stub(override_type(type_repr = "model.BarType | typing.Sequence[model.BarType]"))]
4048        bar_type: &Bound<'_, PyAny>,
4049        start: Option<Timestamp>,
4050        end: Option<Timestamp>,
4051        limit: Option<usize>,
4052        client_id: Option<ClientId>,
4053        params: Option<Py<PyDict>>,
4054        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
4055        callback: Option<Py<PyAny>>,
4056    ) -> PyResult<String> {
4057        let actor = Self {
4058            inner: Rc::clone(&slf.try_borrow()?.inner),
4059        };
4060
4061        let bar_type = extract_bar_types(bar_type)?;
4062        actor.ensure_registered_for_data()?;
4063
4064        let params_map = Python::attach(|py| -> PyResult<Option<Params>> {
4065            match params {
4066                Some(dict) => from_pydict(py, &dict),
4067                None => Ok(None),
4068            }
4069        })?;
4070        let limit = limit.and_then(NonZeroUsize::new);
4071        let handler = nautilus_common::python::response::request_handler(
4072            py,
4073            actor.inner().core().actor_id().inner(),
4074            PyStrategyInner::python_instance,
4075            callback,
4076        )?;
4077        let request_id = DataActorCore::request_bars(
4078            actor.inner().core(),
4079            bar_type,
4080            start,
4081            end,
4082            limit,
4083            client_id,
4084            params_map,
4085            handler,
4086        )
4087        .map_err(to_pyvalue_err)?;
4088        Ok(request_id.to_string())
4089    }
4090
4091    #[pyo3(name = "request_join", signature = (request_ids, callback=None, request_id=None))]
4092    fn py_request_join(
4093        slf: &Bound<'_, Self>,
4094        py: Python<'_>,
4095        #[gen_stub(override_type(type_repr = "typing.Sequence[str | core.UUID4]", imports = ("typing", "nautilus_trader.core")))]
4096        request_ids: Vec<Bound<'_, PyAny>>,
4097        #[gen_stub(override_type(type_repr = "typing.Callable[[str], None] | None"))]
4098        callback: Option<Py<PyAny>>,
4099        #[gen_stub(override_type(type_repr = "str | core.UUID4 | None", imports = ("nautilus_trader.core",)))]
4100        request_id: Option<&Bound<'_, PyAny>>,
4101    ) -> PyResult<String> {
4102        let actor_id = {
4103            let actor = slf.try_borrow()?;
4104            actor.ensure_registered_for_data()?;
4105            actor.inner().core().actor_id().inner()
4106        };
4107
4108        let request_ids = request_ids
4109            .into_iter()
4110            .map(|id| nautilus_common::python::response::extract_request_id(&id))
4111            .collect::<PyResult<Vec<_>>>()?;
4112        let request_id = request_id
4113            .map(nautilus_common::python::response::extract_request_id)
4114            .transpose()?;
4115        nautilus_common::python::response::request_join::<PyStrategyInner>(
4116            py,
4117            actor_id,
4118            PyStrategyInner::python_instance,
4119            request_ids,
4120            request_id,
4121            callback,
4122        )
4123    }
4124
4125    #[pyo3(name = "is_pending_request")]
4126    fn py_is_pending_request(
4127        &self,
4128        #[gen_stub(override_type(type_repr = "str | core.UUID4", imports = ("nautilus_trader.core",)))]
4129        request_id: &Bound<'_, PyAny>,
4130    ) -> PyResult<bool> {
4131        let id = nautilus_common::python::response::extract_request_id(request_id)?;
4132        Ok(self.inner().core().is_pending_request(&id))
4133    }
4134
4135    #[pyo3(name = "has_pending_requests")]
4136    fn py_has_pending_requests(&self) -> bool {
4137        !self.inner().core().pending_requests().is_empty()
4138    }
4139
4140    #[pyo3(name = "pending_requests")]
4141    #[gen_stub(override_return_type(type_repr = "set[str]"))]
4142    fn py_pending_requests(&self, py: Python<'_>) -> PyResult<Py<PySet>> {
4143        let ids = self.inner().core().pending_requests();
4144        PySet::new(py, ids.iter().map(ToString::to_string)).map(Bound::unbind)
4145    }
4146
4147    /// Requests reconnect of one socket endpoint owned by `client_id`.
4148    #[pyo3(name = "reconnect_socket")]
4149    fn py_reconnect_socket(&self, client_id: ClientId, endpoint: &str) -> PyResult<()> {
4150        DataActor::reconnect_socket(self.inner(), client_id, endpoint).map_err(to_pyruntime_err)
4151    }
4152}
4153
4154#[pyo3_stub_gen::derive::gen_stub_pymethods]
4155#[pyo3::pymethods]
4156impl PyStrategy {
4157    #[pyo3(name = "publish_message", signature = (topic, message))]
4158    fn py_publish_message(
4159        slf: &Bound<'_, Self>,
4160        topic: &str,
4161        #[gen_stub(override_type(type_repr = "object"))] message: Py<PyAny>,
4162    ) -> PyResult<()> {
4163        let messages = get_python_message_bus(slf.as_any())?;
4164        messages.publish_message(topic, message)
4165    }
4166
4167    #[pyo3(name = "subscribe_topic")]
4168    #[pyo3(signature = (topic, handler, priority=0))]
4169    fn py_subscribe_topic(
4170        slf: &Bound<'_, Self>,
4171        topic: &str,
4172        #[gen_stub(override_type(type_repr = "collections.abc.Callable[[object], None]", imports = ("collections.abc",)))]
4173        handler: Py<PyAny>,
4174        priority: u32,
4175    ) -> PyResult<()> {
4176        let messages = get_python_message_bus(slf.as_any())?;
4177        messages.subscribe_topic(slf.py(), topic, handler, priority)
4178    }
4179
4180    #[pyo3(name = "unsubscribe_topic", signature = (topic, handler))]
4181    fn py_unsubscribe_topic(
4182        slf: &Bound<'_, Self>,
4183        topic: &str,
4184        #[gen_stub(override_type(type_repr = "collections.abc.Callable[[object], None]", imports = ("collections.abc",)))]
4185        handler: &Bound<'_, PyAny>,
4186    ) -> PyResult<()> {
4187        let messages = get_python_message_bus(slf.as_any())?;
4188        messages.unsubscribe_topic(topic, handler)
4189    }
4190}
4191
4192impl PyStrategy {
4193    fn ensure_registered_for_data(&self) -> PyResult<()> {
4194        if self.inner().core.actor.is_registered() {
4195            Ok(())
4196        } else {
4197            Err(to_pyruntime_err(
4198                "Strategy must be registered before publishing, managing synthetics, or requesting data",
4199            ))
4200        }
4201    }
4202
4203    fn ensure_registered(&self) -> PyResult<()> {
4204        if self.inner().core.actor.is_registered() {
4205            Ok(())
4206        } else {
4207            Err(to_pyruntime_err(
4208                "Strategy must be registered before managing subscriptions",
4209            ))
4210        }
4211    }
4212}
4213
4214/// Returns the class-derived component identity, `<ClassName>-<order ID tag>`.
4215///
4216/// The ID must remain a valid [`StrategyId`], so a strategy without a configured order ID tag
4217/// takes the unassigned tag until registration assigns the next one.
4218fn class_derived_actor_id(slf: &Bound<'_, PyStrategy>, class_name: &str) -> PyResult<ActorId> {
4219    let borrowed = slf.borrow();
4220    let order_id_tag = normalize_order_id_tag(borrowed.inner().core.order_id_tag())
4221        .unwrap_or(UNASSIGNED_ORDER_ID_TAG);
4222
4223    ActorId::new_checked(format!("{class_name}-{order_id_tag}")).map_err(to_pyvalue_err)
4224}
4225
4226/// Returns whether the config retained by the strategy supplies a strategy ID.
4227///
4228/// The config is read through Python rather than the extracted [`StrategyConfig`] so that a
4229/// custom subclass config which cannot be extracted still counts as configuring an ID. The
4230/// strategy borrow is released before the attribute lookup, which can run user code.
4231fn has_configured_strategy_id(slf: &Bound<'_, PyStrategy>) -> bool {
4232    let py = slf.py();
4233    let config = slf
4234        .borrow()
4235        .inner()
4236        .config
4237        .as_ref()
4238        .map(|config| config.clone_ref(py));
4239
4240    config.is_some_and(|config| {
4241        config
4242            .bind(py)
4243            .getattr("strategy_id")
4244            .is_ok_and(|strategy_id| !strategy_id.is_none())
4245    })
4246}
4247
4248fn py_order_list_to_orders(py: Python<'_>, order_list: &Py<PyAny>) -> PyResult<Vec<OrderAny>> {
4249    let order_objects = match order_list.getattr(py, "orders") {
4250        Ok(orders) => orders.extract::<Vec<Py<PyAny>>>(py)?,
4251        Err(e) if e.is_instance_of::<pyo3::exceptions::PyAttributeError>(py) => {
4252            order_list.extract::<Vec<Py<PyAny>>>(py)?
4253        }
4254        Err(e) => return Err(e),
4255    };
4256
4257    order_objects
4258        .into_iter()
4259        .map(|order| pyobject_to_order_any(py, order))
4260        .collect()
4261}
4262
4263#[cfg(test)]
4264mod tests {
4265    use std::{
4266        cell::RefCell,
4267        collections::{BTreeMap, HashMap},
4268        num::NonZeroUsize,
4269        rc::Rc,
4270        str::FromStr,
4271        sync::Arc,
4272    };
4273
4274    use indexmap::IndexMap;
4275    use nautilus_common::{
4276        actor::{DataActor, DataActorNative, registry::actor_exists},
4277        cache::Cache,
4278        clock::{Clock, VirtualClock},
4279        component::{Component, get_component},
4280        enums::ComponentState,
4281        live::runner::replace_system_command_sender,
4282        logging::{
4283            arm_shutdown_on_error, disarm_shutdown_on_error, init_logging,
4284            take_shutdown_on_error_trigger,
4285        },
4286        messages::{
4287            SystemCommand,
4288            data::{
4289                BarsResponse, DataCommand, QuotesResponse, SubscribeCommand, TradesResponse,
4290                UnsubscribeCommand,
4291            },
4292            execution::TradingCommand,
4293            system::{
4294                QueueCondition, QueueState, QueueStateChanged, SocketState, SocketStateChanged,
4295            },
4296        },
4297        msgbus::{
4298            self, MessagingSwitchboard,
4299            stubs::{TypedIntoMessageSavingHandler, get_typed_into_message_saving_handler},
4300        },
4301        python::{cache::PyCache, wrappers::get_python_wrapper},
4302        runner::{SyncDataCommandSender, SystemChannel, set_data_cmd_sender},
4303        signal::Signal,
4304        timer::TimeEvent,
4305    };
4306    use nautilus_core::{DurationNanos, UUID4, UnixNanos};
4307    use nautilus_model::{
4308        data::{
4309            Bar, BarType, CustomData, FundingRateUpdate, IndexPriceUpdate, InstrumentStatus,
4310            MarkPriceUpdate, OrderBookDelta, OrderBookDeltas, OrderBookDepth, QuoteTick, TradeTick,
4311            close::InstrumentClose,
4312            greeks::OptionGreekValues,
4313            option_chain::{OptionChainSlice, OptionGreeks},
4314            stubs::{stub_custom_data, stub_deltas, stub_depth10},
4315        },
4316        enums::{
4317            AggressorSide, BookType, GreeksConvention, InstrumentCloseType, MarketStatusAction,
4318            OmsType, OrderSide, OrderStatus, OrderType, PositionSide, TimeInForce,
4319        },
4320        events::{
4321            OrderAccepted, OrderCancelDenied, OrderCancelRejected, OrderCanceled, OrderDenied,
4322            OrderEmulated, OrderEventAny, OrderExpired, OrderInitialized, OrderModifyDenied,
4323            OrderModifyRejected, OrderPendingCancel, OrderPendingUpdate, OrderRejected,
4324            OrderReleased, OrderSubmitted, OrderTriggered, OrderUpdated, PositionChanged,
4325            PositionClosed, PositionEvent, PositionOpened,
4326            order::spec::{OrderFillVoidedSpec, OrderFilledSpec},
4327        },
4328        identifiers::{
4329            AccountId, ClientId, ClientOrderId, ComponentId, InstrumentId, OptionSeriesId,
4330            OrderListId, PositionId, StrategyId, TradeId, TraderId, Venue, VenueOrderId,
4331        },
4332        instruments::{CurrencyPair, InstrumentAny, stubs::audusd_sim},
4333        orderbook::OrderBook,
4334        orders::{Order, OrderTestBuilder, stubs::TestOrderEventStubs},
4335        position::Position,
4336        python::orders::order_any_to_pyobject,
4337        types::{Currency, Money, Price, Quantity},
4338    };
4339    use nautilus_portfolio::portfolio::Portfolio;
4340    use pyo3::{
4341        Bound, IntoPyObjectExt, Py, PyAny, PyResult, Python,
4342        ffi::c_str,
4343        types::{PyAnyMethods, PyBytes, PyDict, PyList, PyWeakrefMethods, PyWeakrefReference},
4344    };
4345    use serde_json::Value;
4346    use ustr::Ustr;
4347
4348    use super::PyStrategy;
4349    use crate::strategy::{Strategy, StrategyConfig};
4350
4351    const TRACKING_STRATEGY_CODE: &std::ffi::CStr = c_str!(
4352        r#"
4353class TrackingStrategy:
4354    TRACKED_METHODS = {
4355        "on_start",
4356        "on_stop",
4357        "on_resume",
4358        "on_reset",
4359        "on_dispose",
4360        "on_degrade",
4361        "on_fault",
4362        "on_save",
4363        "on_load",
4364        "on_time_event",
4365        "on_data",
4366        "on_signal",
4367        "on_queue_state",
4368        "on_socket_state",
4369        "on_instrument",
4370        "on_quote",
4371        "on_trade",
4372        "on_bar",
4373        "on_book_deltas",
4374        "on_book_depth",
4375        "on_book",
4376        "on_mark_price",
4377        "on_index_price",
4378        "on_funding_rate",
4379        "on_instrument_status",
4380        "on_instrument_close",
4381        "on_option_greeks",
4382        "on_option_chain",
4383        "on_historical_data",
4384        "on_historical_book_deltas",
4385        "on_historical_book_depth",
4386        "on_historical_quotes",
4387        "on_historical_trades",
4388        "on_historical_funding_rates",
4389        "on_historical_bars",
4390        "on_historical_mark_prices",
4391        "on_historical_index_prices",
4392        "on_market_exit",
4393        "post_market_exit",
4394        "on_order_initialized",
4395        "on_order_event",
4396        "on_order_denied",
4397        "on_order_emulated",
4398        "on_order_released",
4399        "on_order_submitted",
4400        "on_order_rejected",
4401        "on_order_accepted",
4402        "on_order_expired",
4403        "on_order_triggered",
4404        "on_order_pending_update",
4405        "on_order_pending_cancel",
4406        "on_order_modify_denied",
4407        "on_order_modify_rejected",
4408        "on_order_cancel_denied",
4409        "on_order_cancel_rejected",
4410        "on_order_updated",
4411        "on_order_canceled",
4412        "on_order_filled",
4413        "on_order_fill_voided",
4414        "on_position_opened",
4415        "on_position_event",
4416        "on_position_changed",
4417        "on_position_closed",
4418    }
4419
4420    def __init__(self):
4421        self.calls = []
4422        self.raise_on = None
4423
4424    def _record(self, method_name, *args):
4425        self.calls.append((method_name, args))
4426        if self.raise_on == method_name:
4427            self.fail_callback()
4428
4429    def fail_callback(self):
4430        try:
4431            raise ValueError("callback cause")
4432        except ValueError as e:
4433            raise RuntimeError("callback failure") from e
4434
4435    def was_called(self, method_name):
4436        return any(call[0] == method_name for call in self.calls)
4437
4438    def call_count(self, method_name):
4439        return sum(1 for call in self.calls if call[0] == method_name)
4440
4441    def last_call_args(self, method_name):
4442        for called_method, args in reversed(self.calls):
4443            if called_method == method_name:
4444                return args
4445        raise AssertionError(f"{method_name} was not called")
4446
4447    def call_names(self):
4448        return [call[0] for call in self.calls]
4449
4450    def last_loaded_state(self):
4451
4452        for method_name, args in reversed(self.calls):
4453            if method_name == "on_load":
4454                return args[0]
4455        return None
4456
4457    def on_save(self):
4458        self._record("on_save")
4459        return {"strategy": b"saved"}
4460
4461    def on_load(self, state):
4462        self._record("on_load", dict(state))
4463
4464    def __getattr__(self, name):
4465        if name in self.TRACKED_METHODS:
4466            return lambda *args: self._record(name, *args)
4467        raise AttributeError(name)
4468"#
4469    );
4470
4471    fn create_tracking_python_strategy(py: Python<'_>) -> PyResult<Py<PyAny>> {
4472        py.run(TRACKING_STRATEGY_CODE, None, None)?;
4473        let tracking_strategy_class = py.eval(c_str!("TrackingStrategy"), None, None)?;
4474        let instance = tracking_strategy_class.call0()?;
4475        Ok(instance.unbind())
4476    }
4477
4478    fn python_method_was_called(
4479        py_strategy: &Py<PyAny>,
4480        py: Python<'_>,
4481        method_name: &str,
4482    ) -> bool {
4483        py_strategy
4484            .call_method1(py, "was_called", (method_name,))
4485            .and_then(|result| result.extract::<bool>(py))
4486            .unwrap_or(false)
4487    }
4488
4489    fn python_method_call_count(py_strategy: &Py<PyAny>, py: Python<'_>, method_name: &str) -> i32 {
4490        py_strategy
4491            .call_method1(py, "call_count", (method_name,))
4492            .and_then(|result| result.extract::<i32>(py))
4493            .unwrap_or(0)
4494    }
4495
4496    fn python_method_call_names(py_strategy: &Py<PyAny>, py: Python<'_>) -> Vec<String> {
4497        py_strategy
4498            .call_method0(py, "call_names")
4499            .and_then(|result| result.extract::<Vec<String>>(py))
4500            .unwrap_or_default()
4501    }
4502
4503    fn python_last_loaded_state(
4504        py_strategy: &Py<PyAny>,
4505        py: Python<'_>,
4506    ) -> Option<HashMap<String, Vec<u8>>> {
4507        py_strategy
4508            .call_method0(py, "last_loaded_state")
4509            .and_then(|result| result.extract::<Option<HashMap<String, Vec<u8>>>>(py))
4510            .unwrap_or(None)
4511    }
4512
4513    const TRACKING_INDICATOR_CODE: &std::ffi::CStr = c_str!(
4514        r#"
4515class TrackingIndicator:
4516    def __init__(self, events=None):
4517        self.initialized = False
4518        self.calls = []
4519        self.events = events
4520
4521    def handle_quote_tick(self, quote):
4522        self.calls.append("quote")
4523        if self.events is not None:
4524            self.events.append("indicator:quote")
4525
4526    def handle_trade_tick(self, trade):
4527        self.calls.append("trade")
4528        if self.events is not None:
4529            self.events.append("indicator:trade")
4530
4531    def handle_bar(self, bar):
4532        self.calls.append("bar")
4533        if self.events is not None:
4534            self.events.append("indicator:bar")
4535
4536    def call_count(self, name):
4537        return self.calls.count(name)
4538
4539class IndicatorEventStrategy:
4540    def __init__(self, events):
4541        self.events = events
4542
4543    def on_start(self):
4544        pass
4545
4546    def on_quote(self, quote):
4547        self.events.append("strategy:quote")
4548
4549    def on_trade(self, trade):
4550        self.events.append("strategy:trade")
4551
4552    def on_bar(self, bar):
4553        self.events.append("strategy:bar")
4554"#
4555    );
4556
4557    fn create_tracking_python_indicator(py: Python<'_>) -> PyResult<Py<PyAny>> {
4558        py.run(TRACKING_INDICATOR_CODE, None, None)?;
4559        let indicator_class = py.eval(c_str!("TrackingIndicator"), None, None)?;
4560        Ok(indicator_class.call0()?.unbind())
4561    }
4562
4563    fn create_event_tracking_python_indicator(
4564        py: Python<'_>,
4565        events: &Bound<'_, PyList>,
4566    ) -> PyResult<Py<PyAny>> {
4567        py.run(TRACKING_INDICATOR_CODE, None, None)?;
4568        let indicator_class = py.eval(c_str!("TrackingIndicator"), None, None)?;
4569        Ok(indicator_class.call1((events,))?.unbind())
4570    }
4571
4572    fn create_indicator_event_strategy(
4573        py: Python<'_>,
4574        events: &Bound<'_, PyList>,
4575    ) -> PyResult<Py<PyAny>> {
4576        py.run(TRACKING_INDICATOR_CODE, None, None)?;
4577        let strategy_class = py.eval(c_str!("IndicatorEventStrategy"), None, None)?;
4578        Ok(strategy_class.call1((events,))?.unbind())
4579    }
4580
4581    fn python_indicator_call_count(
4582        indicator: &Py<PyAny>,
4583        py: Python<'_>,
4584        method_name: &str,
4585    ) -> i32 {
4586        indicator
4587            .call_method1(py, "call_count", (method_name,))
4588            .and_then(|result| result.extract::<i32>(py))
4589            .unwrap_or(0)
4590    }
4591
4592    fn sample_instrument() -> CurrencyPair {
4593        audusd_sim()
4594    }
4595
4596    fn sample_time_event() -> TimeEvent {
4597        TimeEvent::new(
4598            Ustr::from("test_timer"),
4599            UUID4::new(),
4600            UnixNanos::default(),
4601            UnixNanos::default(),
4602        )
4603    }
4604
4605    fn sample_data() -> CustomData {
4606        stub_custom_data(1, 42, None, None)
4607    }
4608
4609    fn sample_signal() -> Signal {
4610        Signal::new(
4611            Ustr::from("test_signal"),
4612            "1.0".to_string(),
4613            UnixNanos::default(),
4614            UnixNanos::default(),
4615        )
4616    }
4617
4618    fn sample_queue_state_changed() -> QueueStateChanged {
4619        QueueStateChanged::new(
4620            TraderId::from("TRADER-001"),
4621            SystemChannel::ExecCommands,
4622            QueueCondition::Backlogged,
4623            QueueState::Triggered,
4624            17,
4625            23,
4626            UUID4::from("00000000-0000-4000-8000-000000000001"),
4627            UnixNanos::from(1_700_000_000_000_000_001),
4628            UnixNanos::from(1_700_000_000_000_000_002),
4629        )
4630    }
4631
4632    fn sample_socket_state_changed() -> SocketStateChanged {
4633        SocketStateChanged::new(
4634            TraderId::from("TRADER-001"),
4635            ClientId::from("BINANCE"),
4636            Some(Venue::from("BINANCE")),
4637            Ustr::from("binance-futures-market-streams"),
4638            SocketState::Connected,
4639            UUID4::from("00000000-0000-4000-8000-000000000001"),
4640            UnixNanos::from(1_700_000_000_000_000_001),
4641            UnixNanos::from(1_700_000_000_000_000_002),
4642        )
4643    }
4644
4645    fn sample_quote() -> QuoteTick {
4646        let instrument = sample_instrument();
4647        QuoteTick::new(
4648            instrument.id,
4649            Price::from("1.00000"),
4650            Price::from("1.00001"),
4651            Quantity::from(100_000),
4652            Quantity::from(100_000),
4653            UnixNanos::default(),
4654            UnixNanos::default(),
4655        )
4656    }
4657
4658    fn sample_trade() -> TradeTick {
4659        let instrument = sample_instrument();
4660        TradeTick::new(
4661            instrument.id,
4662            Price::from("1.00000"),
4663            Quantity::from(100_000),
4664            AggressorSide::Buy,
4665            TradeId::new("123456"),
4666            UnixNanos::default(),
4667            UnixNanos::default(),
4668        )
4669    }
4670
4671    fn sample_bar() -> Bar {
4672        let instrument = sample_instrument();
4673        let bar_type =
4674            BarType::from_str(&format!("{}-1-MINUTE-LAST-INTERNAL", instrument.id)).unwrap();
4675        Bar::new(
4676            bar_type,
4677            Price::from("1.00000"),
4678            Price::from("1.00010"),
4679            Price::from("0.99990"),
4680            Price::from("1.00005"),
4681            Quantity::from(100_000),
4682            UnixNanos::default(),
4683            UnixNanos::default(),
4684        )
4685    }
4686
4687    fn sample_book() -> OrderBook {
4688        OrderBook::new(sample_instrument().id, BookType::L2_MBP)
4689    }
4690
4691    fn sample_book_deltas() -> OrderBookDeltas {
4692        let instrument = sample_instrument();
4693        let delta =
4694            OrderBookDelta::clear(instrument.id, 0, UnixNanos::default(), UnixNanos::default());
4695        OrderBookDeltas::new(instrument.id, vec![delta])
4696    }
4697
4698    fn sample_book_depth() -> OrderBookDepth {
4699        stub_depth10()
4700    }
4701
4702    fn sample_mark_price() -> MarkPriceUpdate {
4703        MarkPriceUpdate::new(
4704            sample_instrument().id,
4705            Price::from("1.00000"),
4706            UnixNanos::default(),
4707            UnixNanos::default(),
4708        )
4709    }
4710
4711    fn sample_index_price() -> IndexPriceUpdate {
4712        IndexPriceUpdate::new(
4713            sample_instrument().id,
4714            Price::from("1.00000"),
4715            UnixNanos::default(),
4716            UnixNanos::default(),
4717        )
4718    }
4719
4720    fn sample_funding_rate() -> FundingRateUpdate {
4721        FundingRateUpdate::new(
4722            sample_instrument().id,
4723            "0.0001".parse().unwrap(),
4724            None,
4725            None,
4726            UnixNanos::default(),
4727            UnixNanos::default(),
4728        )
4729    }
4730
4731    fn sample_instrument_status() -> InstrumentStatus {
4732        InstrumentStatus::new(
4733            sample_instrument().id,
4734            MarketStatusAction::Trading,
4735            UnixNanos::default(),
4736            UnixNanos::default(),
4737            None,
4738            None,
4739            None,
4740            None,
4741            None,
4742        )
4743    }
4744
4745    fn sample_instrument_close() -> InstrumentClose {
4746        InstrumentClose::new(
4747            sample_instrument().id,
4748            Price::from("1.00000"),
4749            InstrumentCloseType::EndOfSession,
4750            UnixNanos::default(),
4751            UnixNanos::default(),
4752        )
4753    }
4754
4755    fn sample_option_greeks() -> OptionGreeks {
4756        OptionGreeks {
4757            instrument_id: InstrumentId::from("AUD/USD.SIM"),
4758            convention: GreeksConvention::BlackScholes,
4759            greeks: OptionGreekValues {
4760                delta: 0.55,
4761                gamma: 0.03,
4762                vega: 0.12,
4763                theta: -0.05,
4764                rho: 0.01,
4765            },
4766            mark_iv: Some(0.25),
4767            bid_iv: None,
4768            ask_iv: None,
4769            underlying_price: None,
4770            open_interest: None,
4771            ts_event: UnixNanos::default(),
4772            ts_init: UnixNanos::default(),
4773        }
4774    }
4775
4776    fn sample_option_chain() -> OptionChainSlice {
4777        OptionChainSlice {
4778            series_id: OptionSeriesId::new_derived(
4779                Venue::from("SIM"),
4780                Ustr::from("AUD"),
4781                Ustr::from("USD"),
4782                UnixNanos::from(1_711_036_800_000_000_000),
4783            ),
4784            atm_strike: None,
4785            calls: BTreeMap::default(),
4786            puts: BTreeMap::default(),
4787            ts_event: UnixNanos::default(),
4788            ts_init: UnixNanos::default(),
4789        }
4790    }
4791
4792    fn sample_position_opened() -> PositionOpened {
4793        PositionOpened {
4794            trader_id: TraderId::from("TRADER-001"),
4795            strategy_id: StrategyId::from("TEST-001"),
4796            instrument_id: InstrumentId::from("BTCUSDT.BINANCE"),
4797            position_id: PositionId::from("P-001"),
4798            account_id: AccountId::from("ACC-001"),
4799            opening_order_id: ClientOrderId::from("O-001"),
4800            entry: OrderSide::Buy,
4801            side: PositionSide::Long,
4802            signed_qty: 1.into(),
4803            quantity: Quantity::from(1),
4804            last_qty: Quantity::from(1),
4805            last_px: Price::from("1.00000"),
4806            currency: Currency::from("USD"),
4807            avg_px_open: 1.into(),
4808            realized_pnl: None,
4809            event_id: UUID4::new(),
4810            ts_event: UnixNanos::default(),
4811            ts_init: UnixNanos::default(),
4812        }
4813    }
4814
4815    fn sample_position_changed() -> PositionChanged {
4816        PositionChanged {
4817            trader_id: TraderId::from("TRADER-001"),
4818            strategy_id: StrategyId::from("TEST-001"),
4819            instrument_id: InstrumentId::from("BTCUSDT.BINANCE"),
4820            position_id: PositionId::from("P-001"),
4821            account_id: AccountId::from("ACC-001"),
4822            opening_order_id: ClientOrderId::from("O-001"),
4823            entry: OrderSide::Buy,
4824            side: PositionSide::Long,
4825            signed_qty: 2.into(),
4826            quantity: Quantity::from(2),
4827            peak_quantity: Quantity::from(2),
4828            last_qty: Quantity::from(1),
4829            last_px: Price::from("1.10000"),
4830            currency: Currency::from("USD"),
4831            avg_px_open: "1.05".parse().unwrap(),
4832            avg_px_close: None,
4833            realized_return: 0.0,
4834            realized_pnl: None,
4835            unrealized_pnl: Money::new(0.0, Currency::USD()),
4836            event_id: UUID4::new(),
4837            ts_opened: UnixNanos::default(),
4838            ts_event: UnixNanos::default(),
4839            ts_init: UnixNanos::default(),
4840        }
4841    }
4842
4843    fn sample_position_closed() -> PositionClosed {
4844        PositionClosed {
4845            trader_id: TraderId::from("TRADER-001"),
4846            strategy_id: StrategyId::from("TEST-001"),
4847            instrument_id: InstrumentId::from("BTCUSDT.BINANCE"),
4848            position_id: PositionId::from("P-001"),
4849            account_id: AccountId::from("ACC-001"),
4850            opening_order_id: ClientOrderId::from("O-001"),
4851            closing_order_id: Some(ClientOrderId::from("O-002")),
4852            entry: OrderSide::Buy,
4853            side: PositionSide::Flat,
4854            signed_qty: 0.into(),
4855            quantity: Quantity::from(0),
4856            peak_quantity: Quantity::from(2),
4857            last_qty: Quantity::from(2),
4858            last_px: Price::from("1.20000"),
4859            currency: Currency::from("USD"),
4860            avg_px_open: "1.05".parse().unwrap(),
4861            avg_px_close: Some("1.20".parse().unwrap()),
4862            realized_return: 0.1,
4863            realized_pnl: Some(Money::new(0.1, Currency::USD())),
4864            unrealized_pnl: Money::new(0.0, Currency::USD()),
4865            duration: DurationNanos::new(1),
4866            event_id: UUID4::new(),
4867            ts_opened: UnixNanos::default(),
4868            ts_closed: Some(UnixNanos::default()),
4869            ts_event: UnixNanos::default(),
4870            ts_init: UnixNanos::default(),
4871        }
4872    }
4873
4874    fn sample_python_market_order(
4875        py: Python<'_>,
4876        strategy_id: StrategyId,
4877        client_order_id: ClientOrderId,
4878    ) -> PyResult<Py<PyAny>> {
4879        let order = OrderTestBuilder::new(OrderType::Market)
4880            .trader_id(TraderId::from("TRADER-001"))
4881            .strategy_id(strategy_id)
4882            .instrument_id(sample_instrument().id)
4883            .client_order_id(client_order_id)
4884            .quantity(Quantity::from(100_000))
4885            .build();
4886
4887        order_any_to_pyobject(py, order)
4888    }
4889
4890    fn sample_open_position(
4891        strategy_id: StrategyId,
4892        position_id: PositionId,
4893        client_order_id: ClientOrderId,
4894    ) -> Position {
4895        let instrument = sample_instrument();
4896        let fill = OrderFilledSpec::builder()
4897            .trader_id(TraderId::from("TRADER-001"))
4898            .strategy_id(strategy_id)
4899            .instrument_id(instrument.id)
4900            .client_order_id(client_order_id)
4901            .position_id(position_id)
4902            .order_side(OrderSide::Buy)
4903            .last_qty(Quantity::from(100_000))
4904            .last_px(Price::from("1.00000"))
4905            .currency(instrument.quote_currency)
4906            .build();
4907
4908        Position::new(&InstrumentAny::CurrencyPair(instrument), fill)
4909    }
4910
4911    fn create_registered_tracking_strategy_with_config(
4912        py: Python<'_>,
4913        config: Option<StrategyConfig>,
4914    ) -> (Py<PyAny>, PyStrategy) {
4915        let py_strategy = create_tracking_python_strategy(py).unwrap();
4916        let mut rust_strategy = PyStrategy::new(config);
4917        rust_strategy
4918            .set_python_instance(py_strategy.bind(py))
4919            .unwrap();
4920
4921        let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
4922        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4923        let portfolio = Rc::new(RefCell::new(Portfolio::new(
4924            clock.clone(),
4925            cache.clone(),
4926            None,
4927        )));
4928
4929        rust_strategy
4930            .register(TraderId::from("TRADER-001"), clock, cache, portfolio)
4931            .unwrap();
4932
4933        (py_strategy, rust_strategy)
4934    }
4935
4936    fn create_registered_tracking_strategy(py: Python<'_>) -> (Py<PyAny>, PyStrategy) {
4937        create_registered_tracking_strategy_with_config(py, None)
4938    }
4939
4940    #[rstest::rstest]
4941    fn test_python_strategy_identifier_lists_require_registration_before_validation(
4942        #[values(
4943            "subscribe_quotes",
4944            "unsubscribe_quotes",
4945            "subscribe_trades",
4946            "unsubscribe_trades"
4947        )]
4948        method: &str,
4949        #[values("empty", "invalid", "mixed_venues")] input: &str,
4950    ) {
4951        Python::initialize();
4952        Python::attach(|py| {
4953            let strategy = PyStrategy::new(None);
4954            let strategy = Py::new(py, strategy).unwrap();
4955            let argument = match input {
4956                "empty" => PyList::empty(py).into_any(),
4957                "invalid" => PyList::new(py, [42]).unwrap().into_any(),
4958                "mixed_venues" => PyList::new(
4959                    py,
4960                    [
4961                        InstrumentId::from("BTC/USD.SIM"),
4962                        InstrumentId::from("ETH/USD.OTHER"),
4963                    ],
4964                )
4965                .unwrap()
4966                .into_any(),
4967                _ => unreachable!(),
4968            };
4969
4970            let error = strategy
4971                .bind(py)
4972                .call_method1(method, (&argument,))
4973                .unwrap_err();
4974
4975            assert!(error.is_instance_of::<pyo3::exceptions::PyRuntimeError>(py));
4976            assert_eq!(
4977                error.value(py).to_string(),
4978                "Strategy must be registered before managing subscriptions"
4979            );
4980        });
4981    }
4982
4983    #[rstest::rstest]
4984    fn test_python_strategy_identifier_lists_reject_mixed_venues_before_effects(
4985        #[values(
4986            "subscribe_quotes",
4987            "unsubscribe_quotes",
4988            "subscribe_trades",
4989            "unsubscribe_trades"
4990        )]
4991        method: &str,
4992    ) {
4993        Python::initialize();
4994        Python::attach(|py| {
4995            let (_instance, strategy) = create_registered_tracking_strategy(py);
4996            let strategy = Py::new(py, strategy).unwrap();
4997            set_data_cmd_sender(Arc::new(SyncDataCommandSender));
4998            let (handler, saver) = get_typed_into_message_saving_handler::<DataCommand>(None);
4999            msgbus::register_data_command_endpoint(
5000                MessagingSwitchboard::data_engine_queue_execute(),
5001                handler,
5002            );
5003            let first = InstrumentId::from("BTC/USD.SIM");
5004            let second = InstrumentId::from("ETH/USD.OTHER");
5005            let ids = PyList::new(py, [first, second]).unwrap();
5006            let quotes = method.ends_with("quotes");
5007            let subscribe = method.starts_with("subscribe_");
5008            if !subscribe {
5009                let kwargs = PyDict::new(py);
5010                kwargs
5011                    .set_item("client_id", ClientId::from("ORIGINAL"))
5012                    .unwrap();
5013                strategy
5014                    .bind(py)
5015                    .call_method(
5016                        if quotes {
5017                            "subscribe_quotes"
5018                        } else {
5019                            "subscribe_trades"
5020                        },
5021                        (&ids,),
5022                        Some(&kwargs),
5023                    )
5024                    .unwrap();
5025            }
5026
5027            let error = strategy.bind(py).call_method1(method, (&ids,)).unwrap_err();
5028
5029            assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
5030            assert_eq!(
5031                error.value(py).to_string(),
5032                "multiple instrument venues require an explicit client ID"
5033            );
5034            assert_eq!(saver.get_messages().len(), usize::from(!subscribe));
5035
5036            for id in [first, second] {
5037                assert_eq!(
5038                    msgbus::exact_subscriber_count_quotes(msgbus::switchboard::get_quotes_topic(
5039                        id
5040                    )),
5041                    usize::from(!subscribe && quotes),
5042                );
5043                assert_eq!(
5044                    msgbus::exact_subscriber_count_trades(msgbus::switchboard::get_trades_topic(
5045                        id
5046                    )),
5047                    usize::from(!subscribe && !quotes),
5048                );
5049            }
5050        });
5051    }
5052
5053    #[rstest::rstest]
5054    fn test_python_subscription_lists_reject_invalid_routes_before_effects(
5055        #[values(
5056            "subscribe_quotes",
5057            "subscribe_instrument",
5058            "subscribe_book_deltas",
5059            "subscribe_book_depth",
5060            "subscribe_book_at_interval",
5061            "subscribe_option_greeks",
5062            "subscribe_instrument_status",
5063            "subscribe_instrument_close"
5064        )]
5065        method: &str,
5066        #[values(false, true)] external: bool,
5067    ) {
5068        Python::initialize();
5069        Python::attach(|py| {
5070            let client_id = ClientId::from("ROUTED");
5071            let (_instance, strategy) = create_registered_tracking_strategy(py);
5072            if external {
5073                DataActorNative::cache_rc(strategy.inner())
5074                    .borrow_mut()
5075                    .add_external_data_client(client_id);
5076            }
5077
5078            let actor = Py::new(py, strategy).unwrap();
5079            set_data_cmd_sender(Arc::new(SyncDataCommandSender));
5080            let (handler, saver) = get_typed_into_message_saving_handler::<DataCommand>(None);
5081            msgbus::register_data_command_endpoint(
5082                MessagingSwitchboard::data_engine_queue_execute(),
5083                handler,
5084            );
5085            let ids = PyList::new(
5086                py,
5087                [
5088                    InstrumentId::from("AUD/USD.SIM"),
5089                    InstrumentId::from("SYNTH.SYNTH"),
5090                ],
5091            )
5092            .unwrap();
5093            let kwargs = PyDict::new(py);
5094            kwargs.set_item("client_id", client_id).unwrap();
5095            if method.starts_with("subscribe_book") {
5096                kwargs.set_item("book_type", BookType::L2_MBP).unwrap();
5097            }
5098
5099            if method == "subscribe_book_at_interval" {
5100                kwargs.set_item("interval_ms", 13).unwrap();
5101            }
5102
5103            let result = actor.bind(py).call_method(method, (&ids,), Some(&kwargs));
5104            if external {
5105                result.unwrap();
5106            } else {
5107                let error = result.unwrap_err();
5108                assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
5109
5110                let expected = if method == "subscribe_quotes" {
5111                    "quote identifier lists cannot mix client, synthetic, and spread routes"
5112                } else {
5113                    "Cannot subscribe synthetic instruments for this data type"
5114                };
5115
5116                assert_eq!(error.value(py).to_string(), expected);
5117                assert!(saver.get_messages().is_empty());
5118            }
5119
5120            if method.starts_with("subscribe_book") {
5121                kwargs.del_item("book_type").unwrap();
5122            }
5123
5124            let unsubscribe = method.replacen("subscribe", "unsubscribe", 1);
5125            actor
5126                .bind(py)
5127                .call_method(unsubscribe.as_str(), (&ids,), Some(&kwargs))
5128                .unwrap();
5129            assert_eq!(saver.get_messages().len(), if external { 2 } else { 0 });
5130        });
5131    }
5132
5133    #[rstest::rstest]
5134    #[case::quotes("quotes")]
5135    #[case::trades("trades")]
5136    fn test_python_strategy_identifier_lists(
5137        #[case] family: &str,
5138        #[values(false, true)] mixed_venues: bool,
5139    ) {
5140        pyo3::Python::initialize();
5141        Python::attach(|py| {
5142            let (_instance, strategy) = create_registered_tracking_strategy(py);
5143            let strategy = Py::new(py, strategy).unwrap();
5144            set_data_cmd_sender(Arc::new(SyncDataCommandSender));
5145            let (handler, saver) = get_typed_into_message_saving_handler::<DataCommand>(None);
5146            msgbus::register_data_command_endpoint(
5147                MessagingSwitchboard::data_engine_queue_execute(),
5148                handler,
5149            );
5150            let first = InstrumentId::from("BTC/USD.SIM");
5151
5152            let second = if mixed_venues {
5153                InstrumentId::from("ETH/USD.OTHER")
5154            } else {
5155                InstrumentId::from("ETH/USD.SIM")
5156            };
5157
5158            let client_id = mixed_venues.then(|| ClientId::from("EXPLICIT"));
5159            let ids = PyList::new(py, [second, first, second]).unwrap();
5160            let kwargs = PyDict::new(py);
5161            kwargs.set_item("instrument_id", &ids).unwrap();
5162            kwargs.set_item("client_id", client_id).unwrap();
5163
5164            for action in ["subscribe", "unsubscribe"] {
5165                strategy
5166                    .bind(py)
5167                    .call_method(format!("{action}_{family}").as_str(), (), Some(&kwargs))
5168                    .unwrap();
5169            }
5170
5171            let commands = saver.get_messages();
5172
5173            let actual: Vec<_> = commands
5174                .iter()
5175                .map(|command| match command {
5176                    DataCommand::Subscribe(SubscribeCommand::Quotes(cmd)) => (
5177                        "quotes",
5178                        true,
5179                        cmd.instrument_ids.clone(),
5180                        cmd.client_id,
5181                        cmd.venue,
5182                        cmd.params.clone(),
5183                    ),
5184                    DataCommand::Subscribe(SubscribeCommand::Trades(cmd)) => (
5185                        "trades",
5186                        true,
5187                        cmd.instrument_ids.clone(),
5188                        cmd.client_id,
5189                        cmd.venue,
5190                        cmd.params.clone(),
5191                    ),
5192                    DataCommand::Unsubscribe(UnsubscribeCommand::Quotes(cmd)) => (
5193                        "quotes",
5194                        false,
5195                        cmd.instrument_ids.clone(),
5196                        cmd.client_id,
5197                        cmd.venue,
5198                        cmd.params.clone(),
5199                    ),
5200                    DataCommand::Unsubscribe(UnsubscribeCommand::Trades(cmd)) => (
5201                        "trades",
5202                        false,
5203                        cmd.instrument_ids.clone(),
5204                        cmd.client_id,
5205                        cmd.venue,
5206                        cmd.params.clone(),
5207                    ),
5208                    _ => panic!("unexpected subscription command {command:?}"),
5209                })
5210                .collect();
5211
5212            let expected = if mixed_venues {
5213                vec![
5214                    (family, true, vec![second, first], client_id, None, None),
5215                    (family, false, vec![second, first], client_id, None, None),
5216                ]
5217            } else {
5218                vec![
5219                    (
5220                        family,
5221                        true,
5222                        vec![second, first],
5223                        None,
5224                        Some(first.venue),
5225                        None,
5226                    ),
5227                    (
5228                        family,
5229                        false,
5230                        vec![second, first],
5231                        None,
5232                        Some(first.venue),
5233                        None,
5234                    ),
5235                ]
5236            };
5237
5238            assert_eq!(actual, expected);
5239        });
5240    }
5241
5242    #[rstest::rstest]
5243    fn test_register_in_global_registries_retains_python_wrapper() {
5244        pyo3::Python::initialize();
5245
5246        Python::attach(|py| {
5247            let (py_strategy, rust_strategy) = create_registered_tracking_strategy_with_config(
5248                py,
5249                Some(StrategyConfig {
5250                    strategy_id: Some(StrategyId::from("Retained-001")),
5251                    ..Default::default()
5252                }),
5253            );
5254
5255            rust_strategy.register_in_global_registries().unwrap();
5256
5257            let retained = get_python_wrapper(ComponentId::from("Retained-001"))
5258                .expect("registering must retain the strategy's Python wrapper");
5259
5260            assert!(retained.bind(py).is(py_strategy.bind(py)));
5261            assert!(get_component(&Ustr::from("Retained-001")).is_some());
5262            assert!(actor_exists(&Ustr::from("Retained-001")));
5263        });
5264    }
5265
5266    #[rstest::rstest]
5267    fn test_registered_python_strategy_routes_time_events_by_state() {
5268        pyo3::Python::initialize();
5269
5270        Python::attach(|py| {
5271            let (py_strategy, rust_strategy) = create_registered_tracking_strategy_with_config(
5272                py,
5273                Some(StrategyConfig {
5274                    strategy_id: Some(StrategyId::from("StoppedTimer-001")),
5275                    manage_gtd_expiry: true,
5276                    ..Default::default()
5277                }),
5278            );
5279            rust_strategy.register_in_global_registries().unwrap();
5280            Component::start(rust_strategy.inner_mut()).unwrap();
5281
5282            let running_client_order_id = ClientOrderId::from("O-RUNNING-001");
5283            let running_timer_name = format!("GTD-EXPIRY:{running_client_order_id}");
5284            let clock = DataActorNative::clock_rc(rust_strategy.inner());
5285            clock
5286                .borrow_mut()
5287                .set_time_alert_ns(&running_timer_name, UnixNanos::from(1), None, None)
5288                .unwrap();
5289            rust_strategy
5290                .inner_mut()
5291                .core
5292                .gtd_timers
5293                .insert(running_client_order_id, Ustr::from(&running_timer_name));
5294            let running_dispatched = dispatch_time_events(&clock, UnixNanos::from(1));
5295
5296            assert_eq!(running_dispatched, 1);
5297            assert!(
5298                !rust_strategy
5299                    .inner_mut()
5300                    .has_gtd_expiry_timer(&running_client_order_id)
5301            );
5302            assert_eq!(
5303                python_method_call_count(&py_strategy, py, "on_time_event"),
5304                1
5305            );
5306
5307            let client_order_id = ClientOrderId::from("O-STOPPED-001");
5308            let timer_name = format!("GTD-EXPIRY:{client_order_id}");
5309            clock
5310                .borrow_mut()
5311                .set_time_alert_ns(&timer_name, UnixNanos::from(2), None, None)
5312                .unwrap();
5313            rust_strategy
5314                .inner_mut()
5315                .core
5316                .gtd_timers
5317                .insert(client_order_id, Ustr::from(&timer_name));
5318            Component::stop(rust_strategy.inner_mut()).unwrap();
5319
5320            let stopped_dispatched = dispatch_time_events(&clock, UnixNanos::from(2));
5321
5322            assert_eq!(stopped_dispatched, 1);
5323            assert_eq!(
5324                Component::state(rust_strategy.inner()),
5325                ComponentState::Stopped
5326            );
5327            assert!(
5328                rust_strategy
5329                    .inner_mut()
5330                    .has_gtd_expiry_timer(&client_order_id)
5331            );
5332            assert_eq!(
5333                python_method_call_count(&py_strategy, py, "on_time_event"),
5334                1
5335            );
5336        });
5337    }
5338
5339    fn dispatch_time_events(clock: &Rc<RefCell<dyn Clock>>, to_time_ns: UnixNanos) -> usize {
5340        let handlers = {
5341            let mut clock_ref = clock.borrow_mut();
5342            let test_clock = clock_ref
5343                .as_any_mut()
5344                .downcast_mut::<VirtualClock>()
5345                .expect("strategy clock must be VirtualClock");
5346            let events = test_clock.advance_time(to_time_ns, true);
5347            test_clock.match_handlers(events)
5348        };
5349        let dispatched = handlers.len();
5350
5351        for handler in handlers {
5352            handler.run();
5353        }
5354
5355        dispatched
5356    }
5357
5358    #[rstest::rstest]
5359    fn test_register_in_global_registries_rejects_missing_python_wrapper() {
5360        pyo3::Python::initialize();
5361
5362        Python::attach(|_py| {
5363            let mut rust_strategy = PyStrategy::new(Some(StrategyConfig {
5364                strategy_id: Some(StrategyId::from("Unwrapped-001")),
5365                ..Default::default()
5366            }));
5367
5368            let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
5369            let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5370            let portfolio = Rc::new(RefCell::new(Portfolio::new(
5371                clock.clone(),
5372                cache.clone(),
5373                None,
5374            )));
5375            rust_strategy
5376                .register(TraderId::from("TRADER-001"), clock, cache, portfolio)
5377                .unwrap();
5378
5379            let error = rust_strategy
5380                .register_in_global_registries()
5381                .expect_err("registering without a Python wrapper must fail");
5382
5383            assert!(error.to_string().contains("without a Python wrapper"));
5384            assert!(get_component(&Ustr::from("Unwrapped-001")).is_none());
5385            assert!(!actor_exists(&Ustr::from("Unwrapped-001")));
5386            assert!(get_python_wrapper(ComponentId::from("Unwrapped-001")).is_none());
5387        });
5388    }
5389
5390    #[rstest::rstest]
5391    fn test_external_order_instrument_ids_returns_configured_instruments() {
5392        let claims = vec![
5393            InstrumentId::from("AUDUSD.SIM"),
5394            InstrumentId::from("BTCUSDT.BINANCE"),
5395        ];
5396        let strategy = PyStrategy::new(Some(StrategyConfig {
5397            external_order_instrument_ids: Some(claims.clone()),
5398            ..Default::default()
5399        }));
5400
5401        assert_eq!(strategy.external_order_instrument_ids(), Some(claims));
5402    }
5403
5404    #[rstest::rstest]
5405    fn test_new_checked_rejects_order_id_tag_with_separator() {
5406        let config = StrategyConfig {
5407            order_id_tag: Some("A-B".to_string()),
5408            ..Default::default()
5409        };
5410
5411        let error = PyStrategy::new_checked(Some(config)).unwrap_err();
5412
5413        assert_eq!(
5414            error.to_string(),
5415            "`order_id_tag` cannot contain the '-' strategy ID separator, was 'A-B'"
5416        );
5417    }
5418
5419    #[rstest::rstest]
5420    fn test_py_new_raises_value_error_for_order_id_tag_with_separator() {
5421        pyo3::Python::initialize();
5422        Python::attach(|py| {
5423            // Built in Rust so it carries a tag `StrategyConfig.__new__` would have rejected,
5424            // which is the only way to drive an invalid config through the constructor
5425            let config = StrategyConfig {
5426                order_id_tag: Some("A-B".to_string()),
5427                ..Default::default()
5428            };
5429            let config_obj = Py::new(py, config).unwrap().into_any();
5430
5431            let error = PyStrategy::py_new(Some(config_obj)).unwrap_err();
5432
5433            assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
5434            assert_eq!(
5435                error.value(py).to_string(),
5436                "`order_id_tag` cannot contain the '-' strategy ID separator, was 'A-B'"
5437            );
5438        });
5439    }
5440
5441    #[rstest::rstest]
5442    fn test_py_new_accepts_a_config_without_a_separator() {
5443        pyo3::Python::initialize();
5444        Python::attach(|py| {
5445            let config = StrategyConfig {
5446                order_id_tag: Some("001".to_string()),
5447                ..Default::default()
5448            };
5449            let config_obj = Py::new(py, config).unwrap().into_any();
5450
5451            let strategy = PyStrategy::py_new(Some(config_obj)).unwrap();
5452
5453            assert_eq!(strategy.order_id_tag(), Some("001".to_string()));
5454        });
5455    }
5456
5457    #[rstest::rstest]
5458    fn test_python_aggregate_event_handlers_exist() {
5459        pyo3::Python::initialize();
5460        Python::attach(|py| {
5461            let strategy = Py::new(py, PyStrategy::new(None)).unwrap();
5462            let strategy = strategy.bind(py);
5463
5464            assert!(strategy.hasattr("on_order_event").unwrap());
5465            assert!(strategy.hasattr("on_position_event").unwrap());
5466        });
5467    }
5468
5469    #[rstest::rstest]
5470    #[case(None)]
5471    #[case(Some(25))]
5472    fn test_python_book_depth_subscription_methods_send_commands(#[case] depth: Option<usize>) {
5473        pyo3::Python::initialize();
5474        Python::attach(|py| {
5475            let (_, mut rust_strategy) = create_registered_tracking_strategy(py);
5476            let (handler, saver) = get_typed_into_message_saving_handler::<DataCommand>(None);
5477            msgbus::register_data_command_endpoint(
5478                MessagingSwitchboard::data_engine_queue_execute(),
5479                handler,
5480            );
5481
5482            let instrument_id = sample_instrument().id;
5483            let client_id = Some(ClientId::new("DEPTH-CLIENT"));
5484            rust_strategy
5485                .py_subscribe_book_depth(
5486                    &pyo3::Py::new(py, instrument_id)
5487                        .unwrap()
5488                        .into_bound(py)
5489                        .into_any(),
5490                    BookType::L2_MBP,
5491                    depth,
5492                    client_id,
5493                    true,
5494                    None,
5495                )
5496                .unwrap();
5497            rust_strategy
5498                .py_unsubscribe_book_depth(
5499                    &pyo3::Py::new(py, instrument_id)
5500                        .unwrap()
5501                        .into_bound(py)
5502                        .into_any(),
5503                    client_id,
5504                    None,
5505                )
5506                .unwrap();
5507
5508            let commands = saver.get_messages();
5509            let [
5510                DataCommand::Subscribe(SubscribeCommand::BookDepth(subscribe)),
5511                DataCommand::Unsubscribe(UnsubscribeCommand::BookDepth(unsubscribe)),
5512            ] = commands.as_slice()
5513            else {
5514                panic!("expected BookDepth subscribe and unsubscribe commands, was {commands:?}");
5515            };
5516
5517            assert_eq!(subscribe.single_instrument_id().unwrap(), instrument_id);
5518            assert_eq!(subscribe.book_type, BookType::L2_MBP);
5519            assert_eq!(subscribe.depth.map(NonZeroUsize::get), depth);
5520            assert_eq!(subscribe.client_id, client_id);
5521            assert!(subscribe.managed);
5522            assert_eq!(unsubscribe.single_instrument_id().unwrap(), instrument_id);
5523            assert_eq!(unsubscribe.client_id, client_id);
5524        });
5525    }
5526
5527    #[rstest::rstest]
5528    fn test_strategy_retains_python_config_object() {
5529        pyo3::Python::initialize();
5530        Python::attach(|py| {
5531            let config = py
5532                .eval(
5533                    c_str!("type('_Cfg', (), {'strategy_id': 'S-RETAIN-001'})()"),
5534                    None,
5535                    None,
5536                )
5537                .unwrap();
5538
5539            let strategy = py
5540                .get_type::<PyStrategy>()
5541                .as_any()
5542                .call1((config.clone(),))
5543                .unwrap();
5544
5545            let retained = strategy.getattr("config").unwrap();
5546
5547            assert!(retained.is(&config));
5548        });
5549    }
5550
5551    #[rstest::rstest]
5552    fn test_indicator_registration_exposes_readiness_and_registered_view() {
5553        pyo3::Python::initialize();
5554        Python::attach(|py| {
5555            let mut rust_strategy = PyStrategy::new(None);
5556            let indicator = create_tracking_python_indicator(py).unwrap();
5557            let instrument_id = sample_instrument().id;
5558            let bar_type = sample_bar().bar_type;
5559
5560            assert_eq!(
5561                rust_strategy
5562                    .py_registered_indicators(py)
5563                    .unwrap()
5564                    .bind(py)
5565                    .len()
5566                    .unwrap(),
5567                0
5568            );
5569            assert!(!rust_strategy.py_indicators_initialized(py).unwrap());
5570
5571            rust_strategy.py_register_indicator_for_quote_ticks(
5572                py,
5573                instrument_id,
5574                indicator.clone_ref(py),
5575            );
5576            rust_strategy.py_register_indicator_for_trade_ticks(
5577                py,
5578                instrument_id,
5579                indicator.clone_ref(py),
5580            );
5581            rust_strategy.py_register_indicator_for_bars(py, bar_type, indicator.clone_ref(py));
5582
5583            let registered = rust_strategy.py_registered_indicators(py).unwrap();
5584            let registered = registered.bind(py);
5585
5586            assert_eq!(registered.len().unwrap(), 1);
5587            assert_eq!(
5588                registered.get_item(0).unwrap().as_ptr(),
5589                indicator.bind(py).as_ptr()
5590            );
5591            assert!(!rust_strategy.py_indicators_initialized(py).unwrap());
5592
5593            indicator.bind(py).setattr("initialized", true).unwrap();
5594
5595            assert!(rust_strategy.py_indicators_initialized(py).unwrap());
5596        });
5597    }
5598
5599    #[rstest::rstest]
5600    fn test_registered_indicators_receive_quote_trade_and_bar_before_strategy_callbacks() {
5601        pyo3::Python::initialize();
5602        Python::attach(|py| {
5603            let events = PyList::empty(py);
5604            let py_strategy = create_indicator_event_strategy(py, &events).unwrap();
5605            let indicator = create_event_tracking_python_indicator(py, &events).unwrap();
5606
5607            let mut rust_strategy = PyStrategy::new(None);
5608            rust_strategy
5609                .set_python_instance(py_strategy.bind(py))
5610                .unwrap();
5611
5612            let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
5613            let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5614            let portfolio = Rc::new(RefCell::new(Portfolio::new(
5615                clock.clone(),
5616                cache.clone(),
5617                None,
5618            )));
5619
5620            rust_strategy
5621                .register(TraderId::from("TRADER-001"), clock, cache, portfolio)
5622                .unwrap();
5623            Component::start(rust_strategy.inner_mut()).unwrap();
5624
5625            let quote = sample_quote();
5626            let trade = sample_trade();
5627            let bar = sample_bar();
5628            let external_bar_type = BarType::from_str(&format!(
5629                "{}-1-MINUTE-LAST-EXTERNAL",
5630                bar.bar_type.instrument_id()
5631            ))
5632            .unwrap();
5633
5634            rust_strategy.py_register_indicator_for_quote_ticks(
5635                py,
5636                quote.instrument_id,
5637                indicator.clone_ref(py),
5638            );
5639            rust_strategy.py_register_indicator_for_trade_ticks(
5640                py,
5641                trade.instrument_id,
5642                indicator.clone_ref(py),
5643            );
5644            rust_strategy.py_register_indicator_for_bars(
5645                py,
5646                external_bar_type,
5647                indicator.clone_ref(py),
5648            );
5649
5650            DataActor::handle_quote(rust_strategy.inner_mut(), &quote);
5651            DataActor::handle_trade(rust_strategy.inner_mut(), &trade);
5652            DataActor::handle_bar(rust_strategy.inner_mut(), &bar);
5653
5654            let events = events.extract::<Vec<String>>().unwrap();
5655
5656            assert_eq!(python_indicator_call_count(&indicator, py, "quote"), 1);
5657            assert_eq!(python_indicator_call_count(&indicator, py, "trade"), 1);
5658            assert_eq!(python_indicator_call_count(&indicator, py, "bar"), 1);
5659            assert_eq!(
5660                events,
5661                vec![
5662                    "indicator:quote",
5663                    "strategy:quote",
5664                    "indicator:trade",
5665                    "strategy:trade",
5666                    "indicator:bar",
5667                    "strategy:bar",
5668                ]
5669            );
5670        });
5671    }
5672
5673    #[rstest::rstest]
5674    fn test_registered_indicators_receive_historical_quote_trade_and_bar_batches() {
5675        pyo3::Python::initialize();
5676        Python::attach(|py| {
5677            let mut rust_strategy = PyStrategy::new(None);
5678            let indicator = create_tracking_python_indicator(py).unwrap();
5679            let quote = sample_quote();
5680            let trade = sample_trade();
5681            let bar = sample_bar();
5682            let quotes = vec![quote];
5683            let trades = vec![trade];
5684            let bars = vec![bar];
5685
5686            rust_strategy.py_register_indicator_for_quote_ticks(
5687                py,
5688                quote.instrument_id,
5689                indicator.clone_ref(py),
5690            );
5691            rust_strategy.py_register_indicator_for_trade_ticks(
5692                py,
5693                trade.instrument_id,
5694                indicator.clone_ref(py),
5695            );
5696            rust_strategy.py_register_indicator_for_bars(py, bar.bar_type, indicator.clone_ref(py));
5697
5698            let client_id = ClientId::new("TEST");
5699            let quotes_response = QuotesResponse::new(
5700                UUID4::new(),
5701                client_id,
5702                quote.instrument_id,
5703                quotes,
5704                None,
5705                None,
5706                UnixNanos::default(),
5707                None,
5708            );
5709            let trades_response = TradesResponse::new(
5710                UUID4::new(),
5711                client_id,
5712                trade.instrument_id,
5713                trades,
5714                None,
5715                None,
5716                UnixNanos::default(),
5717                None,
5718            );
5719            let bars_response = BarsResponse::new(
5720                UUID4::new(),
5721                client_id,
5722                bar.bar_type,
5723                bars,
5724                None,
5725                None,
5726                UnixNanos::default(),
5727                None,
5728            );
5729
5730            DataActor::handle_quotes_response(rust_strategy.inner_mut(), &quotes_response);
5731            DataActor::handle_trades_response(rust_strategy.inner_mut(), &trades_response);
5732            DataActor::handle_bars_response(rust_strategy.inner_mut(), &bars_response);
5733
5734            assert_eq!(python_indicator_call_count(&indicator, py, "quote"), 1);
5735            assert_eq!(python_indicator_call_count(&indicator, py, "trade"), 1);
5736            assert_eq!(python_indicator_call_count(&indicator, py, "bar"), 1);
5737        });
5738    }
5739
5740    fn assert_python_dispatch<F>(py: Python<'_>, method_name: &str, invoke: F) -> Py<PyAny>
5741    where
5742        F: FnOnce(&mut PyStrategy) -> anyhow::Result<()>,
5743    {
5744        let (py_strategy, mut rust_strategy) = create_registered_tracking_strategy(py);
5745        let result = invoke(&mut rust_strategy);
5746
5747        assert!(result.is_ok());
5748        assert!(python_method_was_called(&py_strategy, py, method_name));
5749        assert_eq!(python_method_call_count(&py_strategy, py, method_name), 1);
5750
5751        py_strategy
5752    }
5753
5754    fn assert_python_callback<F>(
5755        py: Python<'_>,
5756        method_name: &str,
5757        raises: bool,
5758        shutdown: bool,
5759        invoke: F,
5760    ) -> Py<PyAny>
5761    where
5762        F: Fn(&mut PyStrategy) -> anyhow::Result<()>,
5763    {
5764        let _guard = init_logging(
5765            TraderId::from("TRADER-001"),
5766            UUID4::new(),
5767            Default::default(),
5768            Default::default(),
5769        )
5770        .unwrap();
5771        let (py_strategy, mut rust_strategy) = create_registered_tracking_strategy(py);
5772        if raises {
5773            py_strategy.setattr(py, "raise_on", method_name).unwrap();
5774        }
5775
5776        arm_shutdown_on_error(shutdown);
5777        let result = invoke(&mut rust_strategy);
5778        let trigger = take_shutdown_on_error_trigger();
5779        disarm_shutdown_on_error();
5780
5781        assert!(result.is_ok());
5782        assert_eq!(python_method_call_count(&py_strategy, py, method_name), 1);
5783
5784        if raises && shutdown {
5785            let trigger = trigger.expect("Python callback failure must request shutdown");
5786            assert_eq!(
5787                trigger.component.as_str(),
5788                rust_strategy.inner().core.actor.actor_id.as_str()
5789            );
5790            assert!(
5791                trigger
5792                    .message
5793                    .contains(&format!("Python {method_name} failed:"))
5794            );
5795            assert!(trigger.message.contains("in fail_callback"));
5796            assert!(trigger.message.contains("ValueError: callback cause"));
5797            assert!(trigger.message.contains("RuntimeError: callback failure"));
5798        } else {
5799            assert_eq!(trigger, None);
5800        }
5801
5802        py_strategy
5803    }
5804
5805    #[rstest::rstest]
5806    #[case(false)]
5807    #[case(true)]
5808    fn test_python_timer_callback_exception_requests_shutdown(#[case] shutdown: bool) {
5809        Python::initialize();
5810        let _guard = init_logging(
5811            TraderId::from("TRADER-001"),
5812            UUID4::new(),
5813            Default::default(),
5814            Default::default(),
5815        )
5816        .unwrap();
5817        Python::attach(|py| {
5818            let (tracker, strategy) = create_registered_tracking_strategy(py);
5819            strategy.register_in_global_registries().unwrap();
5820            Component::start(strategy.inner_mut()).unwrap();
5821            tracker.setattr(py, "raise_on", "on_time_event").unwrap();
5822            let clock = DataActorNative::clock_rc(strategy.inner());
5823            clock
5824                .borrow_mut()
5825                .set_time_alert_ns("CALLBACK", UnixNanos::from(10), None, None)
5826                .unwrap();
5827            arm_shutdown_on_error(shutdown);
5828            let dispatched = dispatch_time_events(&clock, UnixNanos::from(10));
5829            let trigger = take_shutdown_on_error_trigger();
5830            disarm_shutdown_on_error();
5831
5832            assert_eq!(dispatched, 1);
5833            assert_eq!(python_method_call_count(&tracker, py, "on_time_event"), 1);
5834            assert_eq!(Component::state(strategy.inner()), ComponentState::Running);
5835
5836            if shutdown {
5837                let trigger = trigger.expect("strategy timer exception must request shutdown");
5838                assert!(trigger.message.contains("Python on_time_event failed:"));
5839                assert!(trigger.message.contains("in fail_callback"));
5840                assert!(trigger.message.contains("RuntimeError: callback failure"));
5841            } else {
5842                assert_eq!(trigger, None);
5843            }
5844        });
5845    }
5846
5847    #[rstest::rstest]
5848    fn test_python_data_callback_exception_preserves_traceback() {
5849        Python::initialize();
5850        Python::attach(|py| {
5851            let (tracker, strategy) = create_registered_tracking_strategy(py);
5852            tracker.setattr(py, "raise_on", "on_bar").unwrap();
5853            let error = DataActor::on_bar(strategy.inner_mut(), &sample_bar()).unwrap_err();
5854            let message = error.to_string();
5855
5856            assert_eq!(python_method_call_count(&tracker, py, "on_bar"), 1);
5857            assert!(message.contains("Python on_bar failed:"));
5858            assert!(message.contains("in fail_callback"));
5859            assert!(message.contains("ValueError: callback cause"));
5860            assert!(message.contains("RuntimeError: callback failure"));
5861        });
5862    }
5863
5864    #[rstest::rstest]
5865    #[case("on_market_exit")]
5866    #[case("post_market_exit")]
5867    fn test_python_dispatch_market_exit_callback_errors(
5868        #[case] method_name: &str,
5869        #[values(false, true)] raises: bool,
5870        #[values(false, true)] shutdown: bool,
5871    ) {
5872        Python::initialize();
5873        Python::attach(|py| {
5874            assert_python_callback(py, method_name, raises, shutdown, |strategy| {
5875                match method_name {
5876                    "on_market_exit" => Strategy::on_market_exit(strategy.inner_mut()),
5877                    "post_market_exit" => Strategy::post_market_exit(strategy.inner_mut()),
5878                    _ => unreachable!(),
5879                }
5880
5881                Ok(())
5882            });
5883        });
5884    }
5885
5886    #[rstest::rstest]
5887    #[case("on_start")]
5888    #[case("on_stop")]
5889    #[case("on_resume")]
5890    #[case("on_reset")]
5891    #[case("on_dispose")]
5892    #[case("on_degrade")]
5893    #[case("on_fault")]
5894    fn test_python_dispatch_lifecycle_matrix(#[case] method_name: &str) {
5895        pyo3::Python::initialize();
5896        Python::attach(|py| {
5897            assert_python_dispatch(py, method_name, |rust_strategy| match method_name {
5898                "on_start" => DataActor::on_start(rust_strategy.inner_mut()),
5899                "on_stop" => DataActor::on_stop(rust_strategy.inner_mut()),
5900                "on_resume" => DataActor::on_resume(rust_strategy.inner_mut()),
5901                "on_reset" => DataActor::on_reset(rust_strategy.inner_mut()),
5902                "on_dispose" => DataActor::on_dispose(rust_strategy.inner_mut()),
5903                "on_degrade" => DataActor::on_degrade(rust_strategy.inner_mut()),
5904                "on_fault" => DataActor::on_fault(rust_strategy.inner_mut()),
5905                _ => unreachable!("unhandled lifecycle case: {method_name}"),
5906            });
5907        });
5908    }
5909
5910    #[rstest::rstest]
5911    #[case("on_save")]
5912    #[case("on_load")]
5913    fn test_python_dispatch_persistence_matrix(#[case] method_name: &str) {
5914        pyo3::Python::initialize();
5915        Python::attach(|py| {
5916            assert_python_dispatch(py, method_name, |rust_strategy| match method_name {
5917                "on_save" => {
5918                    let state = DataActor::on_save(rust_strategy.inner()).unwrap();
5919                    assert_eq!(
5920                        state.get("strategy").map(Vec::as_slice),
5921                        Some(b"saved".as_slice())
5922                    );
5923                    Ok(())
5924                }
5925                "on_load" => {
5926                    let mut state = IndexMap::new();
5927                    state.insert("strategy".to_string(), b"loaded".to_vec());
5928                    DataActor::on_load(rust_strategy.inner_mut(), state)
5929                }
5930                _ => unreachable!("unhandled persistence case: {method_name}"),
5931            });
5932        });
5933    }
5934
5935    #[rstest::rstest]
5936    fn test_python_persistence_methods_convert_state() {
5937        pyo3::Python::initialize();
5938        Python::attach(|py| {
5939            let (py_strategy, mut rust_strategy) = create_registered_tracking_strategy(py);
5940
5941            let saved = rust_strategy.py_save(py).unwrap();
5942            let saved_state = saved
5943                .bind(py)
5944                .extract::<HashMap<String, Vec<u8>>>()
5945                .unwrap();
5946            assert_eq!(
5947                saved_state.get("strategy").map(Vec::as_slice),
5948                Some(&b"saved"[..])
5949            );
5950
5951            let load_state = PyDict::new(py);
5952            load_state
5953                .set_item("strategy", PyBytes::new(py, b"loaded-from-python"))
5954                .unwrap();
5955
5956            rust_strategy.py_load(&load_state).unwrap();
5957
5958            let loaded_state = python_last_loaded_state(&py_strategy, py).unwrap();
5959            assert_eq!(
5960                loaded_state.get("strategy").map(Vec::as_slice),
5961                Some(&b"loaded-from-python"[..])
5962            );
5963        });
5964    }
5965
5966    #[rstest::rstest]
5967    fn test_python_publish_data_and_signal_reach_msgbus() {
5968        use nautilus_common::msgbus::{
5969            MStr, MessageBus, Pattern, get_message_bus, switchboard::get_custom_topic,
5970            typed_handler::ShareableMessageHandler,
5971        };
5972        use nautilus_core::python::IntoPyObjectNautilusExt;
5973
5974        *get_message_bus().borrow_mut() = MessageBus::default();
5975
5976        pyo3::Python::initialize();
5977        Python::attach(|py| {
5978            let (_, rust_strategy) = create_registered_tracking_strategy(py);
5979            let data = sample_data();
5980
5981            let received_data: Rc<RefCell<Vec<CustomData>>> = Rc::new(RefCell::new(Vec::new()));
5982            let received_data_clone = received_data.clone();
5983            let data_handler = ShareableMessageHandler::from_typed(move |data: &CustomData| {
5984                received_data_clone.borrow_mut().push(data.clone());
5985            });
5986            msgbus::subscribe_any(get_custom_topic(&data.data_type).into(), data_handler, None);
5987
5988            let received_signals: Rc<RefCell<Vec<Signal>>> = Rc::new(RefCell::new(Vec::new()));
5989            let received_signals_clone = received_signals.clone();
5990            let signal_handler = ShareableMessageHandler::from_typed(move |data: &CustomData| {
5991                if let Some(signal) = data.data.as_any().downcast_ref::<Signal>() {
5992                    received_signals_clone.borrow_mut().push(signal.clone());
5993                }
5994            });
5995            let signal_pattern: MStr<Pattern> = "data.Signal*".to_string().into();
5996            msgbus::subscribe_any(signal_pattern, signal_handler, None);
5997
5998            rust_strategy
5999                .py_publish_data(&data.data_type, &data)
6000                .unwrap();
6001
6002            let value: Py<PyAny> = 2.0_f64.into_py_any_unwrap(py);
6003            rust_strategy
6004                .py_publish_signal(py, "risk", value, 1_700_000_000_000_000_000)
6005                .unwrap();
6006
6007            let received_data = received_data.borrow();
6008            assert_eq!(received_data.len(), 1);
6009            assert_eq!(received_data[0].data_type, data.data_type);
6010
6011            let received_signals = received_signals.borrow();
6012            assert_eq!(received_signals.len(), 1);
6013            assert_eq!(received_signals[0].name, "risk");
6014            assert_eq!(received_signals[0].value, "2.0");
6015            assert_eq!(
6016                received_signals[0].ts_event,
6017                UnixNanos::from(1_700_000_000_000_000_000_u64),
6018            );
6019        });
6020    }
6021
6022    #[rstest::rstest]
6023    fn test_python_add_and_update_synthetic_update_cache() {
6024        use std::str::FromStr;
6025
6026        use nautilus_model::{
6027            identifiers::{InstrumentId, Symbol},
6028            instruments::SyntheticInstrument,
6029        };
6030
6031        pyo3::Python::initialize();
6032        Python::attach(|py| {
6033            let (_, rust_strategy) = create_registered_tracking_strategy(py);
6034
6035            let comp1 = InstrumentId::from_str("BTC-USD.VENUE").unwrap();
6036            let comp2 = InstrumentId::from_str("ETH-USD.VENUE").unwrap();
6037            let symbol = Symbol::from("SYN");
6038            let original_formula = format!("({comp1} + {comp2}) / 2.0");
6039            let synthetic = SyntheticInstrument::builder()
6040                .symbol(symbol)
6041                .price_precision(2)
6042                .components(vec![comp1, comp2])
6043                .formula(&original_formula)
6044                .ts_event(UnixNanos::default())
6045                .ts_init(UnixNanos::default())
6046                .build()
6047                .unwrap();
6048            let synthetic_id = synthetic.id;
6049
6050            rust_strategy.py_add_synthetic(synthetic).unwrap();
6051
6052            let updated_formula = format!("{comp1} + {comp2}");
6053            let updated = SyntheticInstrument::builder()
6054                .symbol(symbol)
6055                .price_precision(2)
6056                .components(vec![comp1, comp2])
6057                .formula(&updated_formula)
6058                .ts_event(UnixNanos::default())
6059                .ts_init(UnixNanos::default())
6060                .build()
6061                .unwrap();
6062            rust_strategy.py_update_synthetic(updated).unwrap();
6063
6064            let cache = DataActor::cache(rust_strategy.inner());
6065            let stored = cache.synthetic(&synthetic_id).unwrap();
6066            assert_eq!(stored.formula, updated_formula);
6067        });
6068    }
6069
6070    #[rstest::rstest]
6071    fn test_python_subscribe_and_unsubscribe_signal_update_msgbus() {
6072        use nautilus_common::msgbus::{MessageBus, get_message_bus, switchboard::get_signal_topic};
6073
6074        *get_message_bus().borrow_mut() = MessageBus::default();
6075
6076        pyo3::Python::initialize();
6077        Python::attach(|py| {
6078            let (_, mut rust_strategy) = create_registered_tracking_strategy(py);
6079
6080            rust_strategy.py_subscribe_signal("risk", Some(50)).unwrap();
6081
6082            let topic = get_signal_topic("risk");
6083            let subscriptions = get_message_bus().borrow_mut().matching_subscriptions(topic);
6084            assert_eq!(subscriptions.len(), 1);
6085            assert_eq!(subscriptions[0].priority, 50);
6086
6087            rust_strategy.py_unsubscribe_signal("risk").unwrap();
6088
6089            let subscriptions = get_message_bus().borrow_mut().matching_subscriptions(topic);
6090            assert!(subscriptions.is_empty());
6091        });
6092    }
6093
6094    #[rstest::rstest]
6095    #[case(None)]
6096    #[case(Some(SystemChannel::ExecCommands))]
6097    fn test_python_subscribe_and_unsubscribe_queue_state_update_msgbus(
6098        #[case] channel: Option<SystemChannel>,
6099    ) {
6100        use nautilus_common::msgbus::{MessageBus, MessagingSwitchboard, get_message_bus};
6101
6102        *get_message_bus().borrow_mut() = MessageBus::default();
6103
6104        pyo3::Python::initialize();
6105        Python::attach(|py| {
6106            let (_, mut rust_strategy) = create_registered_tracking_strategy(py);
6107
6108            rust_strategy
6109                .py_subscribe_queue_state(channel, Some(50))
6110                .unwrap();
6111
6112            let topic =
6113                MessagingSwitchboard::queue_state_changed_topic(SystemChannel::ExecCommands);
6114            let subscriptions = get_message_bus().borrow_mut().matching_subscriptions(topic);
6115            assert_eq!(subscriptions.len(), 1);
6116            assert_eq!(subscriptions[0].priority, 50);
6117            let unrelated =
6118                MessagingSwitchboard::queue_state_changed_topic(SystemChannel::DataEvents);
6119            assert_eq!(
6120                get_message_bus()
6121                    .borrow_mut()
6122                    .matching_subscriptions(unrelated)
6123                    .len(),
6124                usize::from(channel.is_none())
6125            );
6126
6127            rust_strategy.py_unsubscribe_queue_state(channel).unwrap();
6128
6129            let subscriptions = get_message_bus().borrow_mut().matching_subscriptions(topic);
6130            assert!(subscriptions.is_empty());
6131        });
6132    }
6133
6134    #[rstest::rstest]
6135    #[case(None, None)]
6136    #[case(Some(ClientId::from("BINANCE")), None)]
6137    #[case(None, Some("binance-futures-market-streams"))]
6138    #[case(
6139        Some(ClientId::from("BINANCE")),
6140        Some("binance-futures-market-streams")
6141    )]
6142    fn test_python_subscribe_and_unsubscribe_socket_state_update_msgbus(
6143        #[case] client_id: Option<ClientId>,
6144        #[case] endpoint: Option<&str>,
6145    ) {
6146        use nautilus_common::msgbus::{MessageBus, MessagingSwitchboard, get_message_bus};
6147
6148        *get_message_bus().borrow_mut() = MessageBus::default();
6149
6150        pyo3::Python::initialize();
6151        Python::attach(|py| {
6152            let (_, mut rust_strategy) = create_registered_tracking_strategy(py);
6153
6154            rust_strategy
6155                .py_subscribe_socket_state(client_id, endpoint, Some(50))
6156                .unwrap();
6157
6158            let topic = MessagingSwitchboard::socket_state_changed_topic(
6159                ClientId::from("BINANCE"),
6160                "binance-futures-market-streams",
6161            );
6162            let subscriptions = get_message_bus().borrow_mut().matching_subscriptions(topic);
6163            assert_eq!(subscriptions.len(), 1);
6164            assert_eq!(subscriptions[0].priority, 50);
6165            let unrelated =
6166                MessagingSwitchboard::socket_state_changed_topic(ClientId::from("BYBIT"), "orders");
6167            assert_eq!(
6168                get_message_bus()
6169                    .borrow_mut()
6170                    .matching_subscriptions(unrelated)
6171                    .len(),
6172                usize::from(client_id.is_none() && endpoint.is_none())
6173            );
6174
6175            rust_strategy
6176                .py_unsubscribe_socket_state(client_id, endpoint)
6177                .unwrap();
6178
6179            let subscriptions = get_message_bus().borrow_mut().matching_subscriptions(topic);
6180            assert!(subscriptions.is_empty());
6181        });
6182    }
6183
6184    #[rstest::rstest]
6185    fn test_python_reconnect_socket_enqueues_typed_command() {
6186        pyo3::Python::initialize();
6187        Python::attach(|py| {
6188            let (system_tx, mut system_rx) = tokio::sync::mpsc::unbounded_channel();
6189            replace_system_command_sender(system_tx);
6190            let (_, strategy) = create_registered_tracking_strategy(py);
6191
6192            strategy
6193                .py_reconnect_socket(ClientId::from("POLYMARKET"), "polymarket-market-streams")
6194                .expect("valid reconnect command");
6195            let command = system_rx
6196                .try_recv()
6197                .expect("reconnect command should be queued");
6198            let SystemCommand::ReconnectSocket(command) = command;
6199
6200            assert_eq!(command.trader_id, TraderId::from("TRADER-001"));
6201            assert_eq!(command.client_id, ClientId::from("POLYMARKET"));
6202            assert_eq!(command.endpoint, "polymarket-market-streams");
6203            assert_eq!(command.ts_init, UnixNanos::default());
6204        });
6205    }
6206
6207    #[rstest::rstest]
6208    fn test_python_stop_stops_immediately_when_manage_stop_disabled() {
6209        pyo3::Python::initialize();
6210        Python::attach(|py| {
6211            let config = StrategyConfig {
6212                strategy_id: Some(StrategyId::from("TEST-001")),
6213                order_id_tag: Some("001".to_string()),
6214                manage_stop: false,
6215                ..Default::default()
6216            };
6217            let (py_strategy, mut rust_strategy) =
6218                create_registered_tracking_strategy_with_config(py, Some(config));
6219
6220            rust_strategy.py_start().unwrap();
6221            rust_strategy.py_stop().unwrap();
6222
6223            assert!(rust_strategy.py_is_stopped());
6224            assert!(!rust_strategy.inner().core.pending_stop);
6225            assert!(!rust_strategy.inner().core.is_exiting);
6226            assert_eq!(python_method_call_count(&py_strategy, py, "on_stop"), 1);
6227        });
6228    }
6229
6230    #[rstest::rstest]
6231    fn test_python_stop_defers_when_manage_stop_enabled() {
6232        pyo3::Python::initialize();
6233        Python::attach(|py| {
6234            let config = StrategyConfig {
6235                strategy_id: Some(StrategyId::from("TEST-001")),
6236                order_id_tag: Some("001".to_string()),
6237                manage_stop: true,
6238                ..Default::default()
6239            };
6240            let (py_strategy, mut rust_strategy) =
6241                create_registered_tracking_strategy_with_config(py, Some(config));
6242
6243            rust_strategy.py_start().unwrap();
6244            rust_strategy.py_stop().unwrap();
6245
6246            assert!(rust_strategy.py_is_running());
6247            assert!(rust_strategy.inner().core.pending_stop);
6248            assert!(rust_strategy.inner().core.is_exiting);
6249            assert_eq!(python_method_call_count(&py_strategy, py, "on_stop"), 0);
6250        });
6251    }
6252
6253    #[rstest::rstest]
6254    fn test_python_market_exit_methods_update_state_and_dispatch_hooks() {
6255        pyo3::Python::initialize();
6256        Python::attach(|py| {
6257            let (py_strategy, mut rust_strategy) = create_registered_tracking_strategy(py);
6258
6259            rust_strategy.py_start().unwrap();
6260
6261            assert!(!rust_strategy.py_is_exiting());
6262
6263            rust_strategy.py_market_exit().unwrap();
6264
6265            assert!(rust_strategy.py_is_exiting());
6266            assert_eq!(
6267                python_method_call_count(&py_strategy, py, "on_market_exit"),
6268                1
6269            );
6270
6271            rust_strategy.inner_mut().finalize_market_exit();
6272
6273            assert!(!rust_strategy.py_is_exiting());
6274            assert_eq!(
6275                python_method_call_count(&py_strategy, py, "post_market_exit"),
6276                1
6277            );
6278        });
6279    }
6280
6281    #[rstest::rstest]
6282    #[case::order_list_object(true)]
6283    #[case::raw_order_sequence(false)]
6284    fn test_python_submit_order_list_accepts_order_list_inputs(#[case] wrap_order_list: bool) {
6285        pyo3::Python::initialize();
6286        Python::attach(|py| {
6287            let (_, mut rust_strategy) = create_registered_tracking_strategy(py);
6288            let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
6289                get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
6290            msgbus::register_trading_command_endpoint(
6291                MessagingSwitchboard::risk_engine_queue_execute(),
6292                risk_handler,
6293            );
6294
6295            let strategy_id = rust_strategy.strategy_id();
6296            let client_order_id1 = ClientOrderId::from("O-PYO3-LIST-001");
6297            let client_order_id2 = ClientOrderId::from("O-PYO3-LIST-002");
6298            let orders = vec![
6299                sample_python_market_order(py, strategy_id, client_order_id1).unwrap(),
6300                sample_python_market_order(py, strategy_id, client_order_id2).unwrap(),
6301            ];
6302            let params = PyDict::new(py);
6303
6304            params.set_item("routing_hint", "prefer_batch").unwrap();
6305            let order_list = if wrap_order_list {
6306                let order_list_type = py
6307                    .eval(c_str!("type('OrderListShim', (), {})"), None, None)
6308                    .unwrap();
6309                let order_list = order_list_type.call0().unwrap();
6310
6311                order_list.setattr("orders", orders).unwrap();
6312                order_list.unbind()
6313            } else {
6314                PyList::new(py, orders).unwrap().into_any().unbind()
6315            };
6316
6317            rust_strategy
6318                .py_submit_order_list(py, order_list, None, None, Some(params.unbind()))
6319                .unwrap();
6320
6321            let cache = DataActor::cache(rust_strategy.inner());
6322            let cached_order1 = cache.order(&client_order_id1).unwrap();
6323            let cached_order2 = cache.order(&client_order_id2).unwrap();
6324            let order_list_id = cached_order1.order_list_id().unwrap();
6325            let order_list = cache.order_list(&order_list_id).unwrap();
6326
6327            assert_eq!(cached_order2.order_list_id(), Some(order_list_id));
6328            assert_eq!(
6329                order_list.client_order_ids.as_slice(),
6330                &[client_order_id1, client_order_id2]
6331            );
6332
6333            let py_cache =
6334                Py::new(py, PyCache::from_rc(rust_strategy.inner().core.cache_rc())).unwrap();
6335            let py_order_list = py_cache
6336                .bind(py)
6337                .call_method1("order_list", (order_list_id,))
6338                .unwrap();
6339
6340            assert_eq!(
6341                py_order_list
6342                    .getattr("id")
6343                    .unwrap()
6344                    .extract::<OrderListId>()
6345                    .unwrap(),
6346                order_list_id,
6347            );
6348            assert_eq!(
6349                py_order_list
6350                    .call_method0("client_order_ids")
6351                    .unwrap()
6352                    .extract::<Vec<ClientOrderId>>()
6353                    .unwrap(),
6354                vec![client_order_id1, client_order_id2],
6355            );
6356
6357            let risk_messages = risk_messages.get_messages();
6358            assert_eq!(risk_messages.len(), 1);
6359            let Some(TradingCommand::SubmitOrderList(command)) = risk_messages.first() else {
6360                panic!("expected SubmitOrderList command");
6361            };
6362            assert_eq!(
6363                command
6364                    .params
6365                    .as_ref()
6366                    .and_then(|params| params.get("routing_hint")),
6367                Some(&Value::String("prefer_batch".to_string()))
6368            );
6369        });
6370    }
6371
6372    #[rstest::rstest]
6373    fn test_python_close_position_forwards_params_to_submit_order() {
6374        pyo3::Python::initialize();
6375        Python::attach(|py| {
6376            let (_, mut rust_strategy) = create_registered_tracking_strategy(py);
6377            let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
6378                get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
6379            msgbus::register_trading_command_endpoint(
6380                MessagingSwitchboard::risk_engine_queue_execute(),
6381                risk_handler,
6382            );
6383
6384            let position_id = PositionId::from("P-PYO3-CLOSE-001");
6385            let position = sample_open_position(
6386                rust_strategy.strategy_id(),
6387                position_id,
6388                ClientOrderId::from("O-PYO3-CLOSE-001"),
6389            );
6390            rust_strategy
6391                .inner()
6392                .core
6393                .cache_rc()
6394                .borrow_mut()
6395                .add_instrument(InstrumentAny::CurrencyPair(sample_instrument()))
6396                .unwrap();
6397            let params = PyDict::new(py);
6398
6399            params.set_item("routing_hint", "close_single").unwrap();
6400            rust_strategy
6401                .py_close_position(
6402                    &position,
6403                    None,
6404                    None,
6405                    None,
6406                    None,
6407                    None,
6408                    Some(params.unbind()),
6409                )
6410                .unwrap();
6411
6412            let risk_messages = risk_messages.get_messages();
6413            assert_eq!(risk_messages.len(), 1);
6414            let Some(TradingCommand::SubmitOrder(command)) = risk_messages.first() else {
6415                panic!("expected SubmitOrder command");
6416            };
6417            assert_eq!(command.position_id, Some(position_id));
6418            assert_eq!(
6419                command
6420                    .params
6421                    .as_ref()
6422                    .and_then(|params| params.get("routing_hint")),
6423                Some(&Value::String("close_single".to_string()))
6424            );
6425        });
6426    }
6427
6428    #[rstest::rstest]
6429    fn test_python_close_all_positions_forwards_params_to_submit_order() {
6430        pyo3::Python::initialize();
6431        Python::attach(|py| {
6432            let (_, mut rust_strategy) = create_registered_tracking_strategy(py);
6433            let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
6434                get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
6435            msgbus::register_trading_command_endpoint(
6436                MessagingSwitchboard::risk_engine_queue_execute(),
6437                risk_handler,
6438            );
6439
6440            let instrument = sample_instrument();
6441            let position_id1 = PositionId::from("P-PYO3-CLOSE-ALL-001");
6442            let position_id2 = PositionId::from("P-PYO3-CLOSE-ALL-002");
6443            let position1 = sample_open_position(
6444                rust_strategy.strategy_id(),
6445                position_id1,
6446                ClientOrderId::from("O-PYO3-CLOSE-ALL-001"),
6447            );
6448            let position2 = sample_open_position(
6449                rust_strategy.strategy_id(),
6450                position_id2,
6451                ClientOrderId::from("O-PYO3-CLOSE-ALL-002"),
6452            );
6453            let cache = rust_strategy.inner().core.cache_rc();
6454
6455            {
6456                let mut cache = cache.borrow_mut();
6457                cache
6458                    .add_instrument(InstrumentAny::CurrencyPair(instrument.clone()))
6459                    .unwrap();
6460                cache.add_position(&position1, OmsType::Hedging).unwrap();
6461                cache.add_position(&position2, OmsType::Hedging).unwrap();
6462            }
6463
6464            let params = PyDict::new(py);
6465
6466            params.set_item("routing_hint", "close_all").unwrap();
6467            rust_strategy
6468                .py_close_all_positions(
6469                    instrument.id,
6470                    None,
6471                    None,
6472                    None,
6473                    None,
6474                    None,
6475                    None,
6476                    Some(params.unbind()),
6477                )
6478                .unwrap();
6479
6480            let risk_messages = risk_messages.get_messages();
6481            assert_eq!(risk_messages.len(), 2);
6482            let commands: Vec<_> = risk_messages
6483                .iter()
6484                .map(|message| {
6485                    let TradingCommand::SubmitOrder(command) = message else {
6486                        panic!("expected SubmitOrder command");
6487                    };
6488                    command
6489                })
6490                .collect();
6491
6492            assert!(
6493                commands
6494                    .iter()
6495                    .any(|command| command.position_id == Some(position_id1))
6496            );
6497            assert!(
6498                commands
6499                    .iter()
6500                    .any(|command| command.position_id == Some(position_id2))
6501            );
6502            assert!(commands.iter().all(|command| {
6503                command
6504                    .params
6505                    .as_ref()
6506                    .and_then(|params| params.get("routing_hint"))
6507                    == Some(&Value::String("close_all".to_string()))
6508            }));
6509        });
6510    }
6511
6512    #[rstest::rstest]
6513    fn test_python_cancel_gtd_expiry_accepts_order() {
6514        pyo3::Python::initialize();
6515        Python::attach(|py| {
6516            let (_, mut rust_strategy) = create_registered_tracking_strategy(py);
6517            let strategy_id = rust_strategy.strategy_id();
6518            let client_order_id = ClientOrderId::from("O-PYO3-GTD-001");
6519            let timer_name = format!("GTD-EXPIRY:{client_order_id}");
6520            let order = OrderTestBuilder::new(OrderType::Limit)
6521                .trader_id(TraderId::from("TRADER-001"))
6522                .strategy_id(strategy_id)
6523                .instrument_id(sample_instrument().id)
6524                .client_order_id(client_order_id)
6525                .quantity(Quantity::from(100_000))
6526                .price(Price::from("1.00000"))
6527                .time_in_force(TimeInForce::Gtd)
6528                .expire_time(UnixNanos::from(1))
6529                .build();
6530            let py_order = order_any_to_pyobject(py, order).unwrap();
6531
6532            {
6533                let mut clock = rust_strategy.inner_mut().core.clock_mut();
6534                clock
6535                    .set_time_alert_ns(&timer_name, UnixNanos::from(1), None, None)
6536                    .unwrap();
6537            }
6538            rust_strategy
6539                .inner_mut()
6540                .core
6541                .gtd_timers
6542                .insert(client_order_id, Ustr::from(&timer_name));
6543
6544            rust_strategy
6545                .py_cancel_gtd_expiry(py, py_order)
6546                .expect("cancel_gtd_expiry should accept Python order");
6547
6548            let clock_timer_exists = rust_strategy
6549                .inner_mut()
6550                .core
6551                .clock_mut()
6552                .timer_names()
6553                .contains(&timer_name.as_str());
6554
6555            assert!(
6556                !rust_strategy
6557                    .inner_mut()
6558                    .has_gtd_expiry_timer(&client_order_id)
6559            );
6560            assert!(!clock_timer_exists);
6561        });
6562    }
6563
6564    #[rstest::rstest]
6565    #[case("on_time_event")]
6566    #[case("on_data")]
6567    #[case("on_signal")]
6568    #[case("on_queue_state")]
6569    #[case("on_socket_state")]
6570    #[case("on_instrument")]
6571    #[case("on_quote")]
6572    #[case("on_trade")]
6573    #[case("on_bar")]
6574    #[case("on_book_deltas")]
6575    #[case("on_book_depth")]
6576    #[case("on_book")]
6577    #[case("on_mark_price")]
6578    #[case("on_index_price")]
6579    #[case("on_funding_rate")]
6580    #[case("on_instrument_status")]
6581    #[case("on_instrument_close")]
6582    #[case("on_option_greeks")]
6583    #[case("on_option_chain")]
6584    #[case("on_historical_data")]
6585    #[case("on_historical_book_deltas")]
6586    #[case("on_historical_book_depth")]
6587    #[case("on_historical_quotes")]
6588    #[case("on_historical_trades")]
6589    #[case("on_historical_funding_rates")]
6590    #[case("on_historical_bars")]
6591    #[case("on_historical_mark_prices")]
6592    #[case("on_historical_index_prices")]
6593    fn test_python_dispatch_data_callback_matrix(#[case] method_name: &str) {
6594        pyo3::Python::initialize();
6595        Python::attach(|py| {
6596            assert_python_dispatch(py, method_name, |rust_strategy| match method_name {
6597                "on_time_event" => {
6598                    let event = sample_time_event();
6599                    DataActor::on_time_event(rust_strategy.inner_mut(), &event)
6600                }
6601                "on_data" => {
6602                    let data = sample_data();
6603                    rust_strategy.inner_mut().on_data(&data)
6604                }
6605                "on_signal" => {
6606                    let signal = sample_signal();
6607                    rust_strategy.inner_mut().on_signal(&signal)
6608                }
6609                "on_queue_state" => {
6610                    let event = sample_queue_state_changed();
6611                    rust_strategy.inner_mut().on_queue_state(&event)
6612                }
6613                "on_socket_state" => {
6614                    let event = sample_socket_state_changed();
6615                    rust_strategy.inner_mut().on_socket_state(&event)
6616                }
6617                "on_instrument" => {
6618                    let instrument = InstrumentAny::CurrencyPair(sample_instrument());
6619                    rust_strategy.inner_mut().on_instrument(&instrument)
6620                }
6621                "on_quote" => {
6622                    let quote = sample_quote();
6623                    rust_strategy.inner_mut().on_quote(&quote)
6624                }
6625                "on_trade" => {
6626                    let trade = sample_trade();
6627                    rust_strategy.inner_mut().on_trade(&trade)
6628                }
6629                "on_bar" => {
6630                    let bar = sample_bar();
6631                    rust_strategy.inner_mut().on_bar(&bar)
6632                }
6633                "on_book_deltas" => {
6634                    let deltas = sample_book_deltas();
6635                    rust_strategy.inner_mut().on_book_deltas(&deltas)
6636                }
6637                "on_book_depth" => {
6638                    let depth = sample_book_depth();
6639                    rust_strategy.inner_mut().on_book_depth(&depth)
6640                }
6641                "on_book" => {
6642                    let book = sample_book();
6643                    rust_strategy.inner_mut().on_book(&book)
6644                }
6645                "on_mark_price" => {
6646                    let mark_price = sample_mark_price();
6647                    rust_strategy.inner_mut().on_mark_price(&mark_price)
6648                }
6649                "on_index_price" => {
6650                    let index_price = sample_index_price();
6651                    rust_strategy.inner_mut().on_index_price(&index_price)
6652                }
6653                "on_funding_rate" => {
6654                    let funding_rate = sample_funding_rate();
6655                    rust_strategy.inner_mut().on_funding_rate(&funding_rate)
6656                }
6657                "on_instrument_status" => {
6658                    let status = sample_instrument_status();
6659                    rust_strategy.inner_mut().on_instrument_status(&status)
6660                }
6661                "on_instrument_close" => {
6662                    let close = sample_instrument_close();
6663                    rust_strategy.inner_mut().on_instrument_close(&close)
6664                }
6665                "on_option_greeks" => {
6666                    let greeks = sample_option_greeks();
6667                    DataActor::on_option_greeks(rust_strategy.inner_mut(), &greeks)
6668                }
6669                "on_option_chain" => {
6670                    let slice = sample_option_chain();
6671                    DataActor::on_option_chain(rust_strategy.inner_mut(), &slice)
6672                }
6673                "on_historical_data" => {
6674                    let data = sample_data();
6675                    rust_strategy.inner_mut().on_historical_data(&data)
6676                }
6677                "on_historical_book_deltas" => {
6678                    let deltas = sample_book_deltas().deltas;
6679                    rust_strategy.inner_mut().on_historical_book_deltas(&deltas)
6680                }
6681                "on_historical_book_depth" => {
6682                    let depths = vec![sample_book_depth()];
6683                    rust_strategy.inner_mut().on_historical_book_depth(&depths)
6684                }
6685                "on_historical_quotes" => {
6686                    let quotes = vec![sample_quote()];
6687                    rust_strategy.inner_mut().on_historical_quotes(&quotes)
6688                }
6689                "on_historical_trades" => {
6690                    let trades = vec![sample_trade()];
6691                    rust_strategy.inner_mut().on_historical_trades(&trades)
6692                }
6693                "on_historical_funding_rates" => {
6694                    let funding_rates = vec![sample_funding_rate()];
6695                    rust_strategy
6696                        .inner_mut()
6697                        .on_historical_funding_rates(&funding_rates)
6698                }
6699                "on_historical_bars" => {
6700                    let bars = vec![sample_bar()];
6701                    rust_strategy.inner_mut().on_historical_bars(&bars)
6702                }
6703                "on_historical_mark_prices" => {
6704                    let mark_prices = vec![sample_mark_price()];
6705                    rust_strategy
6706                        .inner_mut()
6707                        .on_historical_mark_prices(&mark_prices)
6708                }
6709                "on_historical_index_prices" => {
6710                    let index_prices = vec![sample_index_price()];
6711                    rust_strategy
6712                        .inner_mut()
6713                        .on_historical_index_prices(&index_prices)
6714                }
6715                _ => unreachable!("unhandled data callback case: {method_name}"),
6716            });
6717        });
6718    }
6719
6720    #[rstest::rstest]
6721    fn test_python_dispatch_historical_custom_data_preserves_payload_shape() {
6722        pyo3::Python::initialize();
6723
6724        Python::attach(|py| {
6725            let scalar = stub_custom_data(3, 126, None, None);
6726            let py_strategy = assert_python_dispatch(py, "on_historical_data", |rust_strategy| {
6727                rust_strategy.inner_mut().on_historical_data(&scalar)
6728            });
6729            let actual_scalar = py_strategy
6730                .call_method1(py, "last_call_args", ("on_historical_data",))
6731                .unwrap()
6732                .bind(py)
6733                .get_item(0)
6734                .unwrap()
6735                .extract::<CustomData>()
6736                .unwrap();
6737
6738            assert_eq!(actual_scalar, scalar);
6739
6740            let expected = vec![
6741                stub_custom_data(1, 42, None, None),
6742                stub_custom_data(2, 84, None, None),
6743            ];
6744            let py_strategy = assert_python_dispatch(py, "on_historical_data", |rust_strategy| {
6745                rust_strategy.inner_mut().on_historical_data(&expected)
6746            });
6747            let actual = py_strategy
6748                .call_method1(py, "last_call_args", ("on_historical_data",))
6749                .unwrap()
6750                .bind(py)
6751                .get_item(0)
6752                .unwrap()
6753                .extract::<Vec<CustomData>>()
6754                .unwrap();
6755
6756            assert_eq!(actual, expected);
6757        });
6758    }
6759
6760    #[rstest::rstest]
6761    fn test_python_dispatch_historical_book_deltas_preserves_batch() {
6762        pyo3::Python::initialize();
6763
6764        Python::attach(|py| {
6765            let expected = stub_deltas().deltas;
6766            let py_strategy =
6767                assert_python_dispatch(py, "on_historical_book_deltas", |rust_strategy| {
6768                    rust_strategy
6769                        .inner_mut()
6770                        .on_historical_book_deltas(&expected)
6771                });
6772            let actual = py_strategy
6773                .call_method1(py, "last_call_args", ("on_historical_book_deltas",))
6774                .unwrap()
6775                .bind(py)
6776                .get_item(0)
6777                .unwrap()
6778                .extract::<Vec<OrderBookDelta>>()
6779                .unwrap();
6780
6781            assert_eq!(actual, expected);
6782        });
6783    }
6784
6785    #[rstest::rstest]
6786    fn test_python_dispatch_historical_book_depth_preserves_batch() {
6787        pyo3::Python::initialize();
6788
6789        Python::attach(|py| {
6790            let first = stub_depth10();
6791            let mut second = first.clone();
6792            second.sequence = 17;
6793            second.ts_event = UnixNanos::from(18);
6794            second.ts_init = UnixNanos::from(19);
6795            let expected = vec![first, second];
6796            let py_strategy =
6797                assert_python_dispatch(py, "on_historical_book_depth", |rust_strategy| {
6798                    rust_strategy
6799                        .inner_mut()
6800                        .on_historical_book_depth(&expected)
6801                });
6802            let actual = py_strategy
6803                .call_method1(py, "last_call_args", ("on_historical_book_depth",))
6804                .unwrap()
6805                .bind(py)
6806                .get_item(0)
6807                .unwrap()
6808                .extract::<Vec<OrderBookDepth>>()
6809                .unwrap();
6810
6811            assert_eq!(actual, expected);
6812        });
6813    }
6814
6815    #[rstest::rstest]
6816    #[case("on_order_initialized")]
6817    #[case("on_order_event")]
6818    #[case("on_order_denied")]
6819    #[case("on_order_emulated")]
6820    #[case("on_order_released")]
6821    #[case("on_order_submitted")]
6822    #[case("on_order_rejected")]
6823    #[case("on_order_accepted")]
6824    #[case("on_order_expired")]
6825    #[case("on_order_triggered")]
6826    #[case("on_order_pending_update")]
6827    #[case("on_order_pending_cancel")]
6828    #[case("on_order_modify_denied")]
6829    #[case("on_order_modify_rejected")]
6830    #[case("on_order_cancel_denied")]
6831    #[case("on_order_cancel_rejected")]
6832    #[case("on_order_updated")]
6833    #[case("on_order_canceled")]
6834    #[case("on_order_filled")]
6835    #[case("on_order_fill_voided")]
6836    fn test_python_dispatch_order_callback_matrix(
6837        #[case] method_name: &str,
6838        #[values(false, true)] raises: bool,
6839        #[values(false, true)] shutdown: bool,
6840    ) {
6841        pyo3::Python::initialize();
6842        Python::attach(|py| {
6843            assert_python_callback(py, method_name, raises, shutdown, |rust_strategy| {
6844                match method_name {
6845                    "on_order_initialized" => {
6846                        Strategy::on_order_initialized(
6847                            rust_strategy.inner_mut(),
6848                            OrderInitialized::default(),
6849                        );
6850                        Ok(())
6851                    }
6852                    "on_order_event" => {
6853                        Strategy::on_order_event(
6854                            rust_strategy.inner_mut(),
6855                            OrderEventAny::Accepted(OrderAccepted::default()),
6856                        );
6857                        Ok(())
6858                    }
6859                    "on_order_denied" => {
6860                        Strategy::on_order_denied(
6861                            rust_strategy.inner_mut(),
6862                            OrderDenied::default(),
6863                        );
6864                        Ok(())
6865                    }
6866                    "on_order_emulated" => {
6867                        Strategy::on_order_emulated(
6868                            rust_strategy.inner_mut(),
6869                            OrderEmulated::default(),
6870                        );
6871                        Ok(())
6872                    }
6873                    "on_order_released" => {
6874                        Strategy::on_order_released(
6875                            rust_strategy.inner_mut(),
6876                            OrderReleased::default(),
6877                        );
6878                        Ok(())
6879                    }
6880                    "on_order_submitted" => {
6881                        Strategy::on_order_submitted(
6882                            rust_strategy.inner_mut(),
6883                            OrderSubmitted::default(),
6884                        );
6885                        Ok(())
6886                    }
6887                    "on_order_rejected" => {
6888                        Strategy::on_order_rejected(
6889                            rust_strategy.inner_mut(),
6890                            OrderRejected::default(),
6891                        );
6892                        Ok(())
6893                    }
6894                    "on_order_accepted" => {
6895                        Strategy::on_order_accepted(
6896                            rust_strategy.inner_mut(),
6897                            OrderAccepted::default(),
6898                        );
6899                        Ok(())
6900                    }
6901                    "on_order_expired" => {
6902                        Strategy::on_order_expired(
6903                            rust_strategy.inner_mut(),
6904                            OrderExpired::default(),
6905                        );
6906                        Ok(())
6907                    }
6908                    "on_order_triggered" => {
6909                        Strategy::on_order_triggered(
6910                            rust_strategy.inner_mut(),
6911                            OrderTriggered::default(),
6912                        );
6913                        Ok(())
6914                    }
6915                    "on_order_pending_update" => {
6916                        Strategy::on_order_pending_update(
6917                            rust_strategy.inner_mut(),
6918                            OrderPendingUpdate::default(),
6919                        );
6920                        Ok(())
6921                    }
6922                    "on_order_pending_cancel" => {
6923                        Strategy::on_order_pending_cancel(
6924                            rust_strategy.inner_mut(),
6925                            OrderPendingCancel::default(),
6926                        );
6927                        Ok(())
6928                    }
6929                    "on_order_modify_denied" => {
6930                        Strategy::on_order_modify_denied(
6931                            rust_strategy.inner_mut(),
6932                            OrderModifyDenied::default(),
6933                        );
6934                        Ok(())
6935                    }
6936                    "on_order_modify_rejected" => {
6937                        Strategy::on_order_modify_rejected(
6938                            rust_strategy.inner_mut(),
6939                            OrderModifyRejected::default(),
6940                        );
6941                        Ok(())
6942                    }
6943                    "on_order_cancel_denied" => {
6944                        Strategy::on_order_cancel_denied(
6945                            rust_strategy.inner_mut(),
6946                            OrderCancelDenied::default(),
6947                        );
6948                        Ok(())
6949                    }
6950                    "on_order_cancel_rejected" => {
6951                        Strategy::on_order_cancel_rejected(
6952                            rust_strategy.inner_mut(),
6953                            OrderCancelRejected::default(),
6954                        );
6955                        Ok(())
6956                    }
6957                    "on_order_updated" => {
6958                        Strategy::on_order_updated(
6959                            rust_strategy.inner_mut(),
6960                            OrderUpdated::default(),
6961                        );
6962                        Ok(())
6963                    }
6964                    "on_order_canceled" => {
6965                        let event = OrderCanceled::default();
6966                        Strategy::on_order_canceled(rust_strategy.inner_mut(), &event);
6967                        Ok(())
6968                    }
6969                    "on_order_filled" => {
6970                        let event = OrderFilledSpec::builder().build();
6971                        Strategy::on_order_filled(rust_strategy.inner_mut(), &event);
6972                        Ok(())
6973                    }
6974                    "on_order_fill_voided" => {
6975                        let event = OrderFillVoidedSpec::builder().build();
6976                        Strategy::on_order_fill_voided(rust_strategy.inner_mut(), &event);
6977                        Ok(())
6978                    }
6979                    _ => unreachable!("unhandled order callback case: {method_name}"),
6980                }
6981            });
6982        });
6983    }
6984
6985    #[rstest::rstest]
6986    #[case("on_order_filled")]
6987    #[case("on_order_event")]
6988    fn test_python_order_event_callback_exception_continues_dispatch(
6989        #[case] method_name: &str,
6990        #[values(false, true)] shutdown: bool,
6991    ) {
6992        Python::initialize();
6993        Python::attach(|py| {
6994            let tracker = assert_python_callback(py, method_name, true, shutdown, |strategy| {
6995                Component::start(strategy.inner_mut()).unwrap();
6996                Strategy::handle_order_event(
6997                    strategy.inner_mut(),
6998                    OrderEventAny::Filled(OrderFilledSpec::builder().build()),
6999                );
7000                assert_eq!(Component::state(strategy.inner()), ComponentState::Running);
7001                Ok(())
7002            });
7003
7004            assert_eq!(
7005                python_method_call_names(&tracker, py),
7006                ["on_start", "on_order_filled", "on_order_event"],
7007            );
7008        });
7009    }
7010
7011    #[rstest::rstest]
7012    fn test_python_handle_order_event_dispatches_specific_and_aggregate_callbacks() {
7013        pyo3::Python::initialize();
7014        Python::attach(|py| {
7015            let (py_strategy, mut rust_strategy) = create_registered_tracking_strategy(py);
7016
7017            rust_strategy.py_start().unwrap();
7018            Strategy::handle_order_event(
7019                rust_strategy.inner_mut(),
7020                OrderEventAny::Accepted(OrderAccepted::default()),
7021            );
7022
7023            assert_eq!(
7024                python_method_call_count(&py_strategy, py, "on_order_accepted"),
7025                1
7026            );
7027            assert_eq!(
7028                python_method_call_count(&py_strategy, py, "on_order_event"),
7029                1
7030            );
7031            let call_names = python_method_call_names(&py_strategy, py);
7032            assert_eq!(
7033                &call_names[call_names.len() - 2..],
7034                ["on_order_accepted", "on_order_event"],
7035            );
7036        });
7037    }
7038
7039    #[rstest::rstest]
7040    #[case("on_position_event")]
7041    #[case("on_position_opened")]
7042    #[case("on_position_changed")]
7043    #[case("on_position_closed")]
7044    fn test_python_dispatch_position_callback_matrix(
7045        #[case] method_name: &str,
7046        #[values(false, true)] raises: bool,
7047        #[values(false, true)] shutdown: bool,
7048    ) {
7049        pyo3::Python::initialize();
7050        Python::attach(|py| {
7051            assert_python_callback(py, method_name, raises, shutdown, |rust_strategy| {
7052                match method_name {
7053                    "on_position_event" => {
7054                        Strategy::on_position_event(
7055                            rust_strategy.inner_mut(),
7056                            PositionEvent::PositionOpened(sample_position_opened()),
7057                        );
7058                        Ok(())
7059                    }
7060                    "on_position_opened" => {
7061                        Strategy::on_position_opened(
7062                            rust_strategy.inner_mut(),
7063                            sample_position_opened(),
7064                        );
7065                        Ok(())
7066                    }
7067                    "on_position_changed" => {
7068                        Strategy::on_position_changed(
7069                            rust_strategy.inner_mut(),
7070                            sample_position_changed(),
7071                        );
7072                        Ok(())
7073                    }
7074                    "on_position_closed" => {
7075                        Strategy::on_position_closed(
7076                            rust_strategy.inner_mut(),
7077                            sample_position_closed(),
7078                        );
7079                        Ok(())
7080                    }
7081                    _ => unreachable!("unhandled position callback case: {method_name}"),
7082                }
7083            });
7084        });
7085    }
7086
7087    #[rstest::rstest]
7088    fn test_python_handle_position_event_dispatches_specific_and_aggregate_callbacks() {
7089        pyo3::Python::initialize();
7090        Python::attach(|py| {
7091            let (py_strategy, mut rust_strategy) = create_registered_tracking_strategy(py);
7092
7093            rust_strategy.py_start().unwrap();
7094            Strategy::handle_position_event(
7095                rust_strategy.inner_mut(),
7096                PositionEvent::PositionOpened(sample_position_opened()),
7097            );
7098
7099            assert_eq!(
7100                python_method_call_count(&py_strategy, py, "on_position_opened"),
7101                1
7102            );
7103            assert_eq!(
7104                python_method_call_count(&py_strategy, py, "on_position_event"),
7105                1
7106            );
7107            let call_names = python_method_call_names(&py_strategy, py);
7108            assert_eq!(
7109                &call_names[call_names.len() - 2..],
7110                ["on_position_opened", "on_position_event"],
7111            );
7112        });
7113    }
7114
7115    #[rstest::rstest]
7116    fn test_python_self_is_weak() {
7117        Python::initialize();
7118
7119        Python::attach(|py| {
7120            let instance = py
7121                .get_type::<PyStrategy>()
7122                .call0()
7123                .expect("Strategy should construct");
7124            let weakref =
7125                PyWeakrefReference::new(&instance).expect("Strategy should be weak-referenceable");
7126            assert!(weakref.upgrade().is_some());
7127
7128            drop(instance);
7129
7130            // A strong `py_self` would form an untraceable Rust-Python cycle and keep this alive
7131            assert!(
7132                weakref.upgrade().is_none(),
7133                "an unregistered Strategy must be collected once its last Python owner is dropped",
7134            );
7135        });
7136    }
7137
7138    #[rstest::rstest]
7139    #[case("on_start")]
7140    #[case("on_stop")]
7141    #[case("on_resume")]
7142    #[case("on_reset")]
7143    #[case("on_dispose")]
7144    #[case("on_degrade")]
7145    #[case("on_fault")]
7146    #[case("on_save")]
7147    #[case("on_load")]
7148    #[case("on_time_event")]
7149    #[case("on_data")]
7150    #[case("on_signal")]
7151    #[case("on_queue_state")]
7152    #[case("on_socket_state")]
7153    #[case("on_instrument")]
7154    #[case("on_quote")]
7155    #[case("on_trade")]
7156    #[case("on_bar")]
7157    #[case("on_book_deltas")]
7158    #[case("on_book_depth")]
7159    #[case("on_book")]
7160    #[case("on_mark_price")]
7161    #[case("on_index_price")]
7162    #[case("on_funding_rate")]
7163    #[case("on_instrument_status")]
7164    #[case("on_instrument_close")]
7165    #[case("on_option_greeks")]
7166    #[case("on_option_chain")]
7167    #[case("on_market_exit")]
7168    #[case("post_market_exit")]
7169    #[case("on_order_initialized")]
7170    #[case("on_order_event")]
7171    #[case("on_order_denied")]
7172    #[case("on_order_emulated")]
7173    #[case("on_order_released")]
7174    #[case("on_order_submitted")]
7175    #[case("on_order_rejected")]
7176    #[case("on_order_accepted")]
7177    #[case("on_order_expired")]
7178    #[case("on_order_triggered")]
7179    #[case("on_order_pending_update")]
7180    #[case("on_order_pending_cancel")]
7181    #[case("on_order_modify_denied")]
7182    #[case("on_order_modify_rejected")]
7183    #[case("on_order_cancel_denied")]
7184    #[case("on_order_cancel_rejected")]
7185    #[case("on_order_updated")]
7186    #[case("on_order_canceled")]
7187    #[case("on_order_filled")]
7188    #[case("on_order_fill_voided")]
7189    #[case("on_position_opened")]
7190    #[case("on_position_event")]
7191    #[case("on_position_changed")]
7192    #[case("on_position_closed")]
7193    #[case("on_historical_data")]
7194    #[case("on_historical_book_deltas")]
7195    #[case("on_historical_book_depth")]
7196    #[case("on_historical_quotes")]
7197    #[case("on_historical_trades")]
7198    #[case("on_historical_funding_rates")]
7199    #[case("on_historical_bars")]
7200    #[case("on_historical_mark_prices")]
7201    #[case("on_historical_index_prices")]
7202    fn test_default_callback_during_exclusive_borrow(#[case] method: &str) {
7203        Python::initialize();
7204        Python::attach(|py| {
7205            let argument = match method {
7206                "on_start" | "on_stop" | "on_resume" | "on_reset" | "on_dispose" | "on_degrade"
7207                | "on_fault" | "on_save" | "on_market_exit" | "post_market_exit" => None,
7208                "on_load" => Some(PyDict::new(py).into_any().unbind()),
7209                "on_time_event" => Some(sample_time_event().into_py_any(py).unwrap()),
7210                "on_data" | "on_instrument" | "on_order_event" | "on_position_event"
7211                | "on_historical_data" => Some(py.None()),
7212                "on_signal" => Some(sample_signal().into_py_any(py).unwrap()),
7213                "on_queue_state" => Some(sample_queue_state_changed().into_py_any(py).unwrap()),
7214                "on_socket_state" => Some(sample_socket_state_changed().into_py_any(py).unwrap()),
7215                "on_quote" => Some(sample_quote().into_py_any(py).unwrap()),
7216                "on_trade" => Some(sample_trade().into_py_any(py).unwrap()),
7217                "on_bar" => Some(sample_bar().into_py_any(py).unwrap()),
7218                "on_book_deltas" => Some(sample_book_deltas().into_py_any(py).unwrap()),
7219                "on_book_depth" => Some(sample_book_depth().into_py_any(py).unwrap()),
7220                "on_book" => Some(sample_book().into_py_any(py).unwrap()),
7221                "on_mark_price" => Some(sample_mark_price().into_py_any(py).unwrap()),
7222                "on_index_price" => Some(sample_index_price().into_py_any(py).unwrap()),
7223                "on_funding_rate" => Some(sample_funding_rate().into_py_any(py).unwrap()),
7224                "on_instrument_status" => Some(sample_instrument_status().into_py_any(py).unwrap()),
7225                "on_instrument_close" => Some(sample_instrument_close().into_py_any(py).unwrap()),
7226                "on_option_greeks" => Some(sample_option_greeks().into_py_any(py).unwrap()),
7227                "on_option_chain" => Some(sample_option_chain().into_py_any(py).unwrap()),
7228                "on_order_initialized" => {
7229                    Some(OrderInitialized::default().into_py_any(py).unwrap())
7230                }
7231                "on_order_denied" => Some(OrderDenied::default().into_py_any(py).unwrap()),
7232                "on_order_emulated" => Some(OrderEmulated::default().into_py_any(py).unwrap()),
7233                "on_order_released" => Some(OrderReleased::default().into_py_any(py).unwrap()),
7234                "on_order_submitted" => Some(OrderSubmitted::default().into_py_any(py).unwrap()),
7235                "on_order_rejected" => Some(OrderRejected::default().into_py_any(py).unwrap()),
7236                "on_order_accepted" => Some(OrderAccepted::default().into_py_any(py).unwrap()),
7237                "on_order_expired" => Some(OrderExpired::default().into_py_any(py).unwrap()),
7238                "on_order_triggered" => Some(OrderTriggered::default().into_py_any(py).unwrap()),
7239                "on_order_pending_update" => {
7240                    Some(OrderPendingUpdate::default().into_py_any(py).unwrap())
7241                }
7242                "on_order_pending_cancel" => {
7243                    Some(OrderPendingCancel::default().into_py_any(py).unwrap())
7244                }
7245                "on_order_modify_denied" => {
7246                    Some(OrderModifyDenied::default().into_py_any(py).unwrap())
7247                }
7248                "on_order_modify_rejected" => {
7249                    Some(OrderModifyRejected::default().into_py_any(py).unwrap())
7250                }
7251                "on_order_cancel_denied" => {
7252                    Some(OrderCancelDenied::default().into_py_any(py).unwrap())
7253                }
7254                "on_order_cancel_rejected" => {
7255                    Some(OrderCancelRejected::default().into_py_any(py).unwrap())
7256                }
7257                "on_order_updated" => Some(OrderUpdated::default().into_py_any(py).unwrap()),
7258                "on_order_canceled" => Some(OrderCanceled::default().into_py_any(py).unwrap()),
7259                "on_order_filled" => {
7260                    Some(OrderFilledSpec::builder().build().into_py_any(py).unwrap())
7261                }
7262                "on_order_fill_voided" => Some(
7263                    OrderFillVoidedSpec::builder()
7264                        .build()
7265                        .into_py_any(py)
7266                        .unwrap(),
7267                ),
7268                "on_position_opened" => Some(sample_position_opened().into_py_any(py).unwrap()),
7269                "on_position_changed" => Some(sample_position_changed().into_py_any(py).unwrap()),
7270                "on_position_closed" => Some(sample_position_closed().into_py_any(py).unwrap()),
7271                "on_historical_book_deltas"
7272                | "on_historical_book_depth"
7273                | "on_historical_quotes"
7274                | "on_historical_trades"
7275                | "on_historical_funding_rates"
7276                | "on_historical_bars"
7277                | "on_historical_mark_prices"
7278                | "on_historical_index_prices" => Some(PyList::empty(py).into_any().unbind()),
7279                _ => unreachable!(),
7280            };
7281
7282            let instance = py.get_type::<PyStrategy>().call0().unwrap();
7283            let _borrow = instance
7284                .extract::<pyo3::PyRefMut<'_, PyStrategy>>()
7285                .unwrap();
7286
7287            let result = match argument {
7288                Some(argument) => instance.call_method1(method, (argument,)),
7289                None => instance.call_method0(method),
7290            }
7291            .unwrap();
7292
7293            if method == "on_save" {
7294                assert_eq!(result.len().unwrap(), 0);
7295            } else {
7296                assert!(result.is_none());
7297            }
7298        });
7299    }
7300
7301    #[rstest::rstest]
7302    #[case::cached(true)]
7303    #[case::not_cached(false)]
7304    fn test_query_order_refreshes_python_snapshot(#[case] cached: bool) {
7305        Python::initialize();
7306        Python::attach(|py| {
7307            let (_, strategy) = create_registered_tracking_strategy(py);
7308            let cache = strategy.inner().core.cache_rc();
7309            let (handler, messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
7310                get_typed_into_message_saving_handler(None);
7311            msgbus::register_trading_command_endpoint(
7312                MessagingSwitchboard::exec_engine_queue_execute(),
7313                handler,
7314            );
7315            let order = OrderTestBuilder::new(OrderType::Limit)
7316                .trader_id(TraderId::from("TRADER-001"))
7317                .strategy_id(strategy.strategy_id())
7318                .instrument_id(InstrumentId::from("AUD/USD.SIM"))
7319                .client_order_id(ClientOrderId::from("O-QUERY-REFRESH-001"))
7320                .quantity(Quantity::from(123))
7321                .price(Price::from("1.23456"))
7322                .build();
7323            let argument = order_any_to_pyobject(py, order.clone()).unwrap();
7324            let account_id = AccountId::from("SIM-009");
7325            let venue_order_id = VenueOrderId::from("V-QUERY-REFRESH-009");
7326
7327            let before = if cached {
7328                let mut cache = cache.borrow_mut();
7329                cache.add_order(order.clone(), None, None, true).unwrap();
7330                let submitted = TestOrderEventStubs::submitted(&order, account_id);
7331                cache.update_order(&submitted).unwrap();
7332                let accepted = TestOrderEventStubs::accepted(&order, account_id, venue_order_id);
7333                Some(cache.update_order(&accepted).unwrap())
7334            } else {
7335                None
7336            };
7337
7338            let client_id = ClientId::from("QUERY-CLIENT");
7339            let instance = Py::new(py, strategy).unwrap();
7340            instance
7341                .call_method1(py, "query_order", (argument, client_id))
7342                .unwrap();
7343            let commands = messages.get_messages();
7344
7345            assert_eq!(commands.len(), 1);
7346
7347            let TradingCommand::QueryOrder(command) = &commands[0] else {
7348                panic!("Unexpected command: {:?}", commands[0]);
7349            };
7350
7351            assert_eq!(command.trader_id, order.trader_id());
7352            assert_eq!(command.client_id, Some(client_id));
7353            assert_eq!(command.strategy_id, order.strategy_id());
7354            assert_eq!(command.instrument_id, order.instrument_id());
7355            assert_eq!(command.client_order_id, order.client_order_id());
7356            assert_eq!(command.venue_order_id, cached.then_some(venue_order_id));
7357            assert_eq!(command.ts_init, UnixNanos::default());
7358            assert_eq!(command.params, None);
7359            assert_eq!(command.correlation_id, None);
7360            let after = cache.borrow().order_owned(&order.client_order_id());
7361            assert_eq!(
7362                serde_json::to_value(&after).unwrap(),
7363                serde_json::to_value(&before).unwrap()
7364            );
7365        });
7366    }
7367
7368    #[rstest::rstest]
7369    #[case(false)]
7370    #[case(true)]
7371    fn test_modify_order_no_changes_returns_error_without_logging(#[case] same_values: bool) {
7372        Python::initialize();
7373        let _guard = init_logging(
7374            TraderId::from("TRADER-001"),
7375            UUID4::new(),
7376            Default::default(),
7377            Default::default(),
7378        )
7379        .unwrap();
7380        Python::attach(|py| {
7381            let (_, strategy) = create_registered_tracking_strategy(py);
7382            let strategy_id = strategy.strategy_id();
7383            let cache = strategy.inner().core.cache_rc();
7384            let instance = Py::new(py, strategy).unwrap();
7385            let client_order_id = ClientOrderId::from("O-NO-CHANGE-001");
7386            let order = OrderTestBuilder::new(OrderType::Limit)
7387                .instrument_id(InstrumentId::from("AUD/USD.SIM"))
7388                .strategy_id(strategy_id)
7389                .client_order_id(client_order_id)
7390                .price(Price::from("1.23456"))
7391                .quantity(Quantity::from(123))
7392                .submit(true)
7393                .build();
7394            cache
7395                .borrow_mut()
7396                .add_order(order.clone(), None, None, true)
7397                .unwrap();
7398            let argument = client_order_id.into_py_any(py).unwrap();
7399            let quantity = same_values.then_some(order.quantity());
7400            let price = same_values.then_some(order.price().unwrap());
7401            arm_shutdown_on_error(true);
7402            let result = instance.call_method1(py, "modify_order", (argument, quantity, price));
7403            let trigger = take_shutdown_on_error_trigger();
7404            disarm_shutdown_on_error();
7405
7406            let e = result.unwrap_err();
7407            assert!(e.is_instance_of::<pyo3::exceptions::PyRuntimeError>(py));
7408            assert_eq!(
7409                e.to_string(),
7410                "RuntimeError: Cannot create command ModifyOrder: quantity, price, and trigger were either None or the same as existing values"
7411            );
7412            assert_eq!(trigger, None);
7413            assert_eq!(cache.borrow().order(&client_order_id).unwrap(), &order);
7414        });
7415    }
7416
7417    #[rstest::rstest]
7418    #[case(false)]
7419    #[case(true)]
7420    fn test_submit_order_list_validation_returns_error_without_logging(
7421        #[case] duplicate_ids: bool,
7422    ) {
7423        Python::initialize();
7424        let _guard = init_logging(
7425            TraderId::from("TRADER-001"),
7426            UUID4::new(),
7427            Default::default(),
7428            Default::default(),
7429        )
7430        .unwrap();
7431        Python::attach(|py| {
7432            let (_, strategy) = create_registered_tracking_strategy(py);
7433            let client_order_id = ClientOrderId::from("O-LIST-DUPLICATE-001");
7434            let cache = strategy.inner().core.cache_rc();
7435            let order =
7436                sample_python_market_order(py, strategy.strategy_id(), client_order_id).unwrap();
7437
7438            let orders = if duplicate_ids {
7439                vec![order.clone_ref(py), order]
7440            } else {
7441                Vec::new()
7442            };
7443
7444            let instance = Py::new(py, strategy).unwrap();
7445            arm_shutdown_on_error(true);
7446            let result =
7447                instance.call_method1(py, "submit_order_list", (PyList::new(py, orders).unwrap(),));
7448            let trigger = take_shutdown_on_error_trigger();
7449            disarm_shutdown_on_error();
7450
7451            let e = result.unwrap_err();
7452            assert!(e.is_instance_of::<pyo3::exceptions::PyRuntimeError>(py));
7453            assert!(e.to_string().contains(if duplicate_ids {
7454                "duplicate"
7455            } else {
7456                "no orders to submit"
7457            }));
7458            assert_eq!(trigger, None);
7459            assert!(!cache.borrow().order_exists(&client_order_id));
7460        });
7461    }
7462
7463    #[rstest::rstest]
7464    #[case("submit_order", "default")]
7465    #[case("modify_order", "default")]
7466    #[case("submit_order", "super")]
7467    #[case("modify_order", "super")]
7468    #[case("submit_order", "getter")]
7469    #[case("modify_order", "getter")]
7470    fn test_order_command_callback_borrowing(#[case] method: &str, #[case] callback: &str) {
7471        Python::initialize();
7472        let _guard = init_logging(
7473            TraderId::from("TRADER-001"),
7474            UUID4::new(),
7475            Default::default(),
7476            Default::default(),
7477        )
7478        .unwrap();
7479        Python::attach(|py| {
7480            let globals = PyDict::new(py);
7481            globals
7482                .set_item("Strategy", py.get_type::<PyStrategy>())
7483                .unwrap();
7484            py.run(
7485                c_str!(
7486                    r#"
7487class CommandStrategy(Strategy):
7488    def __init__(self):
7489        super().__init__()
7490        self.calls = []
7491        self.callback = "default"
7492
7493    def on_start(self):
7494        pass
7495
7496    def on_order_event(self, event):
7497
7498        if self.callback == "getter":
7499            self.calls.append("enter")
7500            self.cache
7501        else:
7502            super().on_order_event(event)
7503        self.calls.append("exit")
7504"#
7505                ),
7506                Some(&globals),
7507                None,
7508            )
7509            .unwrap();
7510            let instance = py
7511                .eval(c_str!("CommandStrategy()"), Some(&globals), None)
7512                .unwrap();
7513            instance.setattr("callback", callback).unwrap();
7514            if callback == "default" {
7515                instance.get_type().delattr("on_order_event").unwrap();
7516            }
7517
7518            let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
7519            let cache = Rc::new(RefCell::new(Cache::default()));
7520
7521            let portfolio = Rc::new(RefCell::new(Portfolio::new(
7522                clock.clone(),
7523                cache.clone(),
7524                None,
7525            )));
7526            let strategy_id;
7527            {
7528                let mut strategy = instance
7529                    .extract::<pyo3::PyRefMut<'_, PyStrategy>>()
7530                    .unwrap();
7531                strategy
7532                    .register(
7533                        TraderId::from("TRADER-001"),
7534                        clock,
7535                        cache.clone(),
7536                        portfolio,
7537                    )
7538                    .unwrap();
7539                strategy.register_in_global_registries().unwrap();
7540                Component::start(strategy.inner_mut()).unwrap();
7541                strategy_id = strategy.strategy_id();
7542            }
7543
7544            let actor_id = strategy_id.inner();
7545
7546            let handler = msgbus::TypedHandler::from(move |event: &OrderEventAny| {
7547                let mut strategy = nautilus_common::actor::registry::try_get_actor_unchecked::<
7548                    super::PyStrategyInner,
7549                >(&actor_id)
7550                .unwrap();
7551                Strategy::handle_order_event(&mut *strategy, event.clone());
7552            });
7553
7554            let topic = format!("events.order.{strategy_id}");
7555            msgbus::subscribe_order_events(topic.clone().into(), handler.clone(), None);
7556            let (risk_handler, messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
7557                get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
7558            msgbus::register_trading_command_endpoint(
7559                MessagingSwitchboard::risk_engine_queue_execute(),
7560                risk_handler,
7561            );
7562            let client_order_id = ClientOrderId::from("O-CALLBACK-001");
7563            let order = OrderTestBuilder::new(OrderType::Limit)
7564                .trader_id(TraderId::from("TRADER-001"))
7565                .strategy_id(strategy_id)
7566                .instrument_id(sample_instrument().id)
7567                .client_order_id(client_order_id)
7568                .price(Price::from("1.23456"))
7569                .quantity(Quantity::from(123))
7570                .submit(method == "modify_order")
7571                .build();
7572
7573            if method == "modify_order" {
7574                cache
7575                    .borrow_mut()
7576                    .add_order(order.clone(), None, None, true)
7577                    .unwrap();
7578            }
7579
7580            arm_shutdown_on_error(true);
7581
7582            let result = if method == "submit_order" {
7583                instance.call_method1(method, (order_any_to_pyobject(py, order).unwrap(),))
7584            } else {
7585                instance.call_method1(method, (client_order_id, Quantity::from(234)))
7586            };
7587
7588            let trigger = take_shutdown_on_error_trigger();
7589            disarm_shutdown_on_error();
7590            msgbus::unsubscribe_order_events(topic.into(), &handler);
7591
7592            assert!(result.unwrap().is_none());
7593            assert_eq!(messages.get_messages().len(), 1);
7594            assert_eq!(
7595                cache.borrow().order(&client_order_id).unwrap().status(),
7596                if method == "submit_order" {
7597                    OrderStatus::Initialized
7598                } else {
7599                    OrderStatus::PendingUpdate
7600                }
7601            );
7602            let calls = instance
7603                .getattr("calls")
7604                .unwrap()
7605                .extract::<Vec<String>>()
7606                .unwrap();
7607
7608            match callback {
7609                "default" => {
7610                    assert_eq!(calls, Vec::<String>::new());
7611                    assert_eq!(trigger, None);
7612                }
7613                "super" => {
7614                    assert_eq!(calls, ["exit"]);
7615                    assert_eq!(trigger, None);
7616                }
7617                "getter" => {
7618                    assert_eq!(calls, ["enter"]);
7619                    let trigger = trigger.unwrap();
7620                    assert_eq!(trigger.component, actor_id);
7621                    assert!(
7622                        trigger
7623                            .message
7624                            .starts_with("Python on_order_event failed:\n")
7625                    );
7626                    assert!(
7627                        trigger
7628                            .message
7629                            .contains("RuntimeError: Already mutably borrowed")
7630                    );
7631                }
7632                _ => unreachable!(),
7633            }
7634        });
7635    }
7636}