Skip to main content

nautilus_backtest/python/
engine.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 [`BacktestEngine`].
17
18use std::collections::HashMap;
19
20use ahash::AHashMap;
21use nautilus_common::{
22    actor::data_actor::ImportableActorConfig,
23    enums::ComponentState,
24    python::{
25        actor::{PyDataActor, prepare_python_actor},
26        cache::PyCache,
27        config_error_to_pyvalue_err,
28    },
29};
30use nautilus_core::{
31    UUID4, UnixNanos,
32    python::{to_pyruntime_err, to_pytype_err, to_pyvalue_err},
33};
34use nautilus_execution::{
35    matching_engine::config::OrderPriorityResetPolicy,
36    python::{
37        fee::pyobject_to_fee_model_handle, fill::pyobject_to_fill_model_handle,
38        latency::pyobject_to_latency_model_any,
39    },
40};
41#[cfg(feature = "defi")]
42use nautilus_model::defi::DefiData;
43use nautilus_model::{
44    data::{
45        Bar, CustomData, Data, FundingRateUpdate, IndexPriceUpdate, InstrumentClose,
46        InstrumentStatus, MarkPriceUpdate, OptionGreeks, OrderBookDelta, OrderBookDeltas,
47        OrderBookDepth, QuoteTick, TradeTick,
48    },
49    enums::{AccountType, BookType, OmsType, OtoTriggerMode},
50    identifiers::{AccountId, ActorId, ClientId, ExecAlgorithmId, InstrumentId, TraderId, Venue},
51    python::{
52        account::margin_model::pyobject_to_margin_model_any,
53        instruments::pyobject_to_instrument_any,
54    },
55    types::{Currency, Money},
56};
57use nautilus_portfolio::python::PyPortfolio;
58#[cfg(feature = "examples")]
59use nautilus_trading::examples::strategies::{
60    CompositeMarketMaker, CompositeMarketMakerConfig, DeltaNeutralVol, DeltaNeutralVolConfig,
61    EmaCross, EmaCrossConfig, GridMarketMaker, GridMarketMakerConfig, HurstVpinDirectional,
62    HurstVpinDirectionalConfig, OrderBookImbalance, OrderBookImbalanceConfig,
63};
64use nautilus_trading::{
65    ImportableExecutionAlgorithmConfig, ImportableStrategyConfig,
66    algorithm::{TwapAlgorithm, TwapAlgorithmConfig},
67    python::algorithm::PyExecutionAlgorithm,
68};
69use pyo3::prelude::*;
70use rust_decimal::Decimal;
71
72use super::{modules::pyobject_to_simulation_module_handle, node::create_importable_component};
73use crate::{
74    config::{BacktestEngineConfig, BacktestVenueConfig, BehavioralModels},
75    engine::BacktestEngine,
76    result::BacktestResult,
77};
78
79/// PyO3 wrapper around [`BacktestEngine`].
80///
81/// Exposes the backtest engine to Python as `BacktestEngine`.
82/// Uses `unsendable` because the inner engine holds `Rc<RefCell<...>>`.
83#[pyo3::pyclass(
84    module = "nautilus_trader.backtest",
85    name = "BacktestEngine",
86    unsendable
87)]
88#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.backtest")]
89#[derive(Debug)]
90pub struct PyBacktestEngine(BacktestEngine);
91
92// DeFi methods live in their own fully gated `#[pymethods]` block (multiple-pymethods is enabled)
93// so the `gen_stub`/pyo3 expansion never references `DefiData` in non-DeFi builds.
94#[cfg(feature = "defi")]
95#[pyo3_stub_gen::derive::gen_stub_pymethods]
96#[pymethods]
97impl PyBacktestEngine {
98    /// Adds DeFi data to the engine.
99    #[pyo3(name = "add_defi_data", signature = (data, client_id=None, sort=true))]
100    fn py_add_defi_data(
101        &mut self,
102        data: Vec<DefiData>,
103        client_id: Option<ClientId>,
104        sort: bool,
105    ) -> PyResult<()> {
106        self.0
107            .add_defi_data(data, client_id, sort)
108            .map_err(to_pyruntime_err)
109    }
110}
111
112#[pyo3_stub_gen::derive::gen_stub_pymethods]
113#[pymethods]
114impl PyBacktestEngine {
115    #[new]
116    fn py_new(config: BacktestEngineConfig) -> PyResult<Self> {
117        let engine = BacktestEngine::new(config).map_err(to_pyruntime_err)?;
118        Ok(Self(engine))
119    }
120
121    /// Adds a simulated exchange with the given parameters to the engine.
122    ///
123    /// # Liquidation parameters
124    ///
125    /// - `liquidation_enabled` (bool, default `False`): if margin liquidation should be
126    ///   triggered when the account's equity falls to or below the maintenance
127    ///   margin threshold scaled by `liquidation_trigger_ratio`.
128    /// - `liquidation_trigger_ratio` (float, optional, default `1.0`): the ratio of
129    ///   maintenance margin used as the liquidation threshold. A value of `1.0`
130    ///   liquidates when equity <= maintenance margin; higher values trigger earlier.
131    /// - `liquidation_cancel_open_orders` (bool, default `True`): if open resting
132    ///   orders for the venue should be cancelled before synthetic close-out fills
133    ///   are emitted for open positions.
134    #[pyo3(
135        name = "add_venue",
136        signature = (
137            venue,
138            oms_type,
139            account_type,
140            starting_balances,
141            base_currency = None,
142            default_leverage = None,
143            leverages = None,
144            fill_model = None,
145            fee_model = None,
146            margin_model = None,
147            latency_model = None,
148            modules = None,
149            book_type = BookType::L1_MBP,
150            routing = false,
151            reject_stop_orders = true,
152            support_gtd_orders = true,
153            support_contingent_orders = true,
154            use_position_ids = true,
155            use_random_ids = false,
156            use_reduce_only = true,
157            use_message_queue = true,
158            use_market_order_acks = false,
159            bar_execution = true,
160            bar_adaptive_high_low_ordering = false,
161            trade_execution = true,
162            liquidity_consumption = false,
163            queue_position = false,
164            allow_cash_borrowing = false,
165            frozen_account = false,
166            oto_trigger_mode = OtoTriggerMode::Partial,
167            price_protection_points = None,
168            liquidation_enabled = false,
169            liquidation_trigger_ratio = None,
170            liquidation_cancel_open_orders = true,
171            order_priority_reset_policy = OrderPriorityResetPolicy::PriceChange,
172        )
173    )]
174    #[expect(
175        clippy::fn_params_excessive_bools,
176        clippy::too_many_arguments,
177        reason = "method mirrors the existing Python keyword API"
178    )]
179    fn py_add_venue(
180        &mut self,
181        venue: Venue,
182        oms_type: OmsType,
183        account_type: AccountType,
184        starting_balances: Vec<Money>,
185        base_currency: Option<Currency>,
186        default_leverage: Option<Decimal>,
187        leverages: Option<HashMap<InstrumentId, Decimal>>,
188        fill_model: Option<Py<PyAny>>,
189        fee_model: Option<Py<PyAny>>,
190        margin_model: Option<Py<PyAny>>,
191        latency_model: Option<Py<PyAny>>,
192        modules: Option<Vec<Py<PyAny>>>,
193        book_type: BookType,
194        routing: bool,
195        reject_stop_orders: bool,
196        support_gtd_orders: bool,
197        support_contingent_orders: bool,
198        use_position_ids: bool,
199        use_random_ids: bool,
200        use_reduce_only: bool,
201        use_message_queue: bool,
202        use_market_order_acks: bool,
203        bar_execution: bool,
204        bar_adaptive_high_low_ordering: bool,
205        trade_execution: bool,
206        liquidity_consumption: bool,
207        queue_position: bool,
208        allow_cash_borrowing: bool,
209        frozen_account: bool,
210        oto_trigger_mode: OtoTriggerMode,
211        price_protection_points: Option<u32>,
212        liquidation_enabled: bool,
213        liquidation_trigger_ratio: Option<f64>,
214        liquidation_cancel_open_orders: bool,
215        order_priority_reset_policy: OrderPriorityResetPolicy,
216    ) -> PyResult<()> {
217        let leverages: AHashMap<InstrumentId, Decimal> =
218            leverages.map_or_default(|m| m.into_iter().collect());
219        let fill_model = fill_model
220            .map(|obj| Python::attach(|py| pyobject_to_fill_model_handle(obj.bind(py))))
221            .transpose()?
222            .unwrap_or_default();
223
224        let fee_model = fee_model
225            .map(|obj| Python::attach(|py| pyobject_to_fee_model_handle(obj.bind(py))))
226            .transpose()?
227            .ok_or_else(|| {
228                to_pyvalue_err(
229                    "Backtest venue requires an explicit fee_model, including an explicit zero-fee model",
230                )
231            })?;
232
233        let margin_model = margin_model
234            .map(|obj| Python::attach(|py| pyobject_to_margin_model_any(obj.bind(py))))
235            .transpose()?
236            .map(Into::into);
237
238        let latency_model = latency_model
239            .map(|obj| Python::attach(|py| pyobject_to_latency_model_any(obj.bind(py))))
240            .transpose()?
241            .map(Into::into);
242
243        let modules = modules
244            .map(|objs| {
245                objs.into_iter()
246                    .map(|obj| {
247                        Python::attach(|py| pyobject_to_simulation_module_handle(py, obj.bind(py)))
248                    })
249                    .collect::<PyResult<Vec<_>>>()
250            })
251            .transpose()?
252            .unwrap_or_default();
253
254        let models = BehavioralModels {
255            fill: fill_model,
256            fee: fee_model,
257            margin: margin_model,
258            latency: latency_model,
259        };
260
261        let sim_config = BacktestVenueConfig::builder()
262            .name(venue.as_str())
263            .oms_type(oms_type)
264            .account_type(account_type)
265            .book_type(book_type)
266            .maybe_base_currency(base_currency)
267            .maybe_default_leverage(default_leverage)
268            .leverages(leverages)
269            .routing(routing)
270            .reject_stop_orders(reject_stop_orders)
271            .support_gtd_orders(support_gtd_orders)
272            .support_contingent_orders(support_contingent_orders)
273            .use_position_ids(use_position_ids)
274            .use_random_ids(use_random_ids)
275            .use_reduce_only(use_reduce_only)
276            .use_market_order_acks(use_market_order_acks)
277            .bar_execution(bar_execution)
278            .bar_adaptive_high_low_ordering(bar_adaptive_high_low_ordering)
279            .trade_execution(trade_execution)
280            .liquidity_consumption(liquidity_consumption)
281            .allow_cash_borrowing(allow_cash_borrowing)
282            .frozen_account(frozen_account)
283            .queue_position(queue_position)
284            .order_priority_reset_policy(order_priority_reset_policy)
285            .oto_trigger_mode(oto_trigger_mode)
286            .price_protection_points(price_protection_points.unwrap_or_default())
287            .liquidation_enabled(liquidation_enabled)
288            .liquidation_trigger_ratio(liquidation_trigger_ratio.unwrap_or(1.0))
289            .liquidation_cancel_open_orders(liquidation_cancel_open_orders)
290            .build_simulated(starting_balances, models, modules, use_message_queue)
291            .map_err(config_error_to_pyvalue_err)?;
292
293        self.0.add_venue(sim_config).map_err(to_pyruntime_err)?;
294
295        Ok(())
296    }
297
298    /// Changes the fill model for a venue.
299    #[pyo3(name = "change_fill_model")]
300    #[expect(clippy::needless_pass_by_value)]
301    fn py_change_fill_model(
302        &mut self,
303        py: Python,
304        venue: Venue,
305        fill_model: Py<PyAny>,
306    ) -> PyResult<()> {
307        let fill_model = pyobject_to_fill_model_handle(fill_model.bind(py))?;
308        self.0.change_fill_model(venue, fill_model);
309        Ok(())
310    }
311
312    /// Adds data to the engine.
313    #[pyo3(
314        name = "add_data",
315        signature = (data, client_id=None, validate=true, sort=true)
316    )]
317    fn py_add_data(
318        &mut self,
319        py: Python,
320        data: Vec<Py<PyAny>>,
321        client_id: Option<ClientId>,
322        validate: bool,
323        sort: bool,
324    ) -> PyResult<()> {
325        let rust_data: Vec<Data> = data
326            .into_iter()
327            .map(|obj| pyobject_to_data(py, obj.bind(py)))
328            .collect::<PyResult<_>>()?;
329        self.0
330            .add_data(rust_data, client_id, validate, sort)
331            .map_err(to_pyruntime_err)
332    }
333
334    /// Adds an instrument to the engine.
335    #[pyo3(name = "add_instrument")]
336    fn py_add_instrument(&mut self, py: Python, instrument: Py<PyAny>) -> PyResult<()> {
337        let instrument_any = pyobject_to_instrument_any(py, instrument)?;
338        self.0
339            .add_instrument(&instrument_any)
340            .map_err(to_pyruntime_err)
341    }
342
343    /// Adds an actor from a constructed Python instance.
344    ///
345    /// The actor ID and logging flags are sourced from the instance's config.
346    #[pyo3(name = "add_actor")]
347    fn py_add_actor(&mut self, actor: &Bound<'_, PyAny>) -> PyResult<()> {
348        log::debug!("`add_actor` with a constructed instance");
349        Self::add_python_actor(&mut self.0, &actor.clone().unbind())
350    }
351
352    /// Adds an actor from an importable config.
353    #[pyo3(name = "add_actor_from_config")]
354    #[expect(clippy::needless_pass_by_value)]
355    fn py_add_actor_from_config(
356        &mut self,
357        _py: Python,
358        config: ImportableActorConfig,
359    ) -> PyResult<()> {
360        log::debug!("`add_actor_from_config` with: {config:?}");
361        let actor = create_importable_component(
362            &config.actor_path,
363            "actor_path",
364            &config.config_path,
365            &config.config,
366            "actor",
367        )?;
368
369        Self::add_python_actor(&mut self.0, &actor)
370    }
371
372    /// Adds a strategy from a constructed Python instance.
373    ///
374    /// The strategy ID, order ID tag, and logging flags are sourced from the instance's
375    /// config.
376    #[pyo3(name = "add_strategy")]
377    fn py_add_strategy(&mut self, strategy: &Bound<'_, PyAny>) -> PyResult<()> {
378        log::debug!("`add_strategy` with a constructed instance");
379        Self::add_python_strategy(&mut self.0, &strategy.clone().unbind())
380    }
381
382    /// Adds a strategy from an importable config.
383    #[pyo3(name = "add_strategy_from_config")]
384    #[expect(clippy::needless_pass_by_value)]
385    fn py_add_strategy_from_config(
386        &mut self,
387        _py: Python,
388        config: ImportableStrategyConfig,
389    ) -> PyResult<()> {
390        log::debug!("`add_strategy_from_config` with: {config:?}");
391        let strategy = create_importable_component(
392            &config.strategy_path,
393            "strategy_path",
394            &config.config_path,
395            &config.config,
396            "strategy",
397        )?;
398
399        Self::add_python_strategy(&mut self.0, &strategy)
400    }
401
402    /// Adds an execution algorithm from a constructed Python instance.
403    ///
404    /// The execution algorithm ID and logging flags are sourced from the instance's
405    /// config.
406    #[pyo3(name = "add_exec_algorithm")]
407    fn py_add_exec_algorithm(&mut self, exec_algorithm: &Bound<'_, PyAny>) -> PyResult<()> {
408        log::debug!("`add_exec_algorithm` with a constructed instance");
409        Self::add_python_exec_algorithm(&mut self.0, &exec_algorithm.clone().unbind())
410    }
411
412    /// Adds an execution algorithm from an importable config.
413    #[pyo3(name = "add_exec_algorithm_from_config")]
414    #[expect(clippy::needless_pass_by_value)]
415    fn py_add_exec_algorithm_from_config(
416        &mut self,
417        _py: Python,
418        config: ImportableExecutionAlgorithmConfig,
419    ) -> PyResult<()> {
420        Self::ensure_can_add_exec_algorithm(&self.0)?;
421
422        log::debug!("`add_exec_algorithm_from_config` with: {config:?}");
423        let exec_algorithm = create_importable_component(
424            &config.exec_algorithm_path,
425            "exec_algorithm_path",
426            &config.config_path,
427            &config.config,
428            "exec algorithm",
429        )?;
430
431        Self::add_python_exec_algorithm(&mut self.0, &exec_algorithm)
432    }
433
434    /// Adds a built-in example actor from its type name and config.
435    ///
436    /// This method exists only to single-source bundled example actor code across
437    /// Rust and Python tests/examples. It is not a first-class extension path for
438    /// adding native actors.
439    #[cfg(feature = "examples")]
440    #[pyo3(name = "add_builtin_actor")]
441    fn py_add_builtin_actor(&mut self, type_name: &str, config: &Bound<'_, PyAny>) -> PyResult<()> {
442        let register = builtin_actor_register(type_name).ok_or_else(|| {
443            to_pytype_err(format!("Unsupported built-in actor type: {type_name}"))
444        })?;
445        register(&mut self.0, config)
446    }
447
448    /// Adds a built-in example strategy from its type name and config.
449    ///
450    /// This method exists only to single-source bundled example strategy code across
451    /// Rust and Python tests/examples. It is not a first-class extension path for
452    /// adding native strategies.
453    #[cfg(feature = "examples")]
454    #[pyo3(name = "add_builtin_strategy")]
455    fn py_add_builtin_strategy(
456        &mut self,
457        type_name: &str,
458        config: &Bound<'_, PyAny>,
459    ) -> PyResult<()> {
460        let register = builtin_strategy_register(type_name).ok_or_else(|| {
461            to_pytype_err(format!("Unsupported built-in strategy type: {type_name}"))
462        })?;
463        register(&mut self.0, config)
464    }
465
466    /// Adds a compiled-in native Rust execution algorithm from its type name and config.
467    ///
468    /// The type name determines which built-in execution algorithm is constructed.
469    /// All execution happens in Rust; Python is the configuration layer.
470    #[pyo3(name = "add_native_exec_algorithm")]
471    fn py_add_native_exec_algorithm(
472        &mut self,
473        type_name: &str,
474        config: &Bound<'_, PyAny>,
475    ) -> PyResult<()> {
476        let register = native_exec_algorithm_register(type_name).ok_or_else(|| {
477            to_pytype_err(format!(
478                "Unsupported native exec algorithm type: {type_name}"
479            ))
480        })?;
481        register(&mut self.0, config)
482    }
483
484    /// Runs the backtest engine.
485    #[pyo3(
486        name = "run",
487        signature = (start=None, end=None, run_config_id=None, streaming=false)
488    )]
489    fn py_run(
490        &mut self,
491        start: Option<u64>,
492        end: Option<u64>,
493        run_config_id: Option<String>,
494        streaming: bool,
495    ) -> PyResult<()> {
496        self.0
497            .run(
498                start.map(UnixNanos::from),
499                end.map(UnixNanos::from),
500                run_config_id,
501                streaming,
502            )
503            .map_err(to_pyruntime_err)
504    }
505
506    /// Ends the backtest run, finalizing results.
507    #[pyo3(name = "end")]
508    fn py_end(&mut self) -> PyResult<()> {
509        self.0.end().map_err(to_pyruntime_err)
510    }
511
512    /// Resets the engine state for a new run.
513    #[pyo3(name = "reset")]
514    fn py_reset(&mut self) -> PyResult<()> {
515        self.0.reset().map_err(to_pyruntime_err)
516    }
517
518    /// Disposes of the engine, releasing all resources.
519    #[pyo3(name = "dispose")]
520    fn py_dispose(&mut self) {
521        self.0.dispose();
522    }
523
524    /// Returns the backtest result from the last run.
525    #[pyo3(name = "get_result")]
526    fn py_get_result(&self) -> BacktestResult {
527        self.0.get_result()
528    }
529
530    /// Clears all data from the engine.
531    #[pyo3(name = "clear_data")]
532    fn py_clear_data(&mut self) {
533        self.0.clear_data();
534    }
535
536    /// Clears all actors from the engine.
537    #[pyo3(name = "clear_actors")]
538    fn py_clear_actors(&mut self) -> PyResult<()> {
539        self.0.clear_actors().map_err(to_pyruntime_err)
540    }
541
542    /// Clears all strategies from the engine.
543    #[pyo3(name = "clear_strategies")]
544    fn py_clear_strategies(&mut self) -> PyResult<()> {
545        self.0.clear_strategies().map_err(to_pyruntime_err)
546    }
547
548    /// Clears all execution algorithms from the engine.
549    #[pyo3(name = "clear_exec_algorithms")]
550    fn py_clear_exec_algorithms(&mut self) -> PyResult<()> {
551        self.0.clear_exec_algorithms().map_err(to_pyruntime_err)
552    }
553
554    /// Adds multiple actors from importable configs. Stops at the first error.
555    #[pyo3(name = "add_actors_from_configs")]
556    fn py_add_actors_from_configs(
557        &mut self,
558        py: Python,
559        configs: Vec<ImportableActorConfig>,
560    ) -> PyResult<()> {
561        for config in configs {
562            self.py_add_actor_from_config(py, config)?;
563        }
564        Ok(())
565    }
566
567    /// Adds multiple strategies from importable configs. Stops at the first error.
568    #[pyo3(name = "add_strategies_from_configs")]
569    fn py_add_strategies_from_configs(
570        &mut self,
571        py: Python,
572        configs: Vec<ImportableStrategyConfig>,
573    ) -> PyResult<()> {
574        for config in configs {
575            self.py_add_strategy_from_config(py, config)?;
576        }
577        Ok(())
578    }
579
580    /// Adds multiple execution algorithms from importable configs. Stops at the first error.
581    #[pyo3(name = "add_exec_algorithms_from_configs")]
582    fn py_add_exec_algorithms_from_configs(
583        &mut self,
584        py: Python,
585        configs: Vec<ImportableExecutionAlgorithmConfig>,
586    ) -> PyResult<()> {
587        for config in configs {
588            self.py_add_exec_algorithm_from_config(py, config)?;
589        }
590        Ok(())
591    }
592
593    /// Adds multiple actors from constructed Python instances. Stops at the first error.
594    #[pyo3(name = "add_actors")]
595    fn py_add_actors(&mut self, actors: Vec<Py<PyAny>>) -> PyResult<()> {
596        for actor in actors {
597            Self::add_python_actor(&mut self.0, &actor)?;
598        }
599        Ok(())
600    }
601
602    /// Adds multiple strategies from constructed Python instances. Stops at the first error.
603    #[pyo3(name = "add_strategies")]
604    fn py_add_strategies(&mut self, strategies: Vec<Py<PyAny>>) -> PyResult<()> {
605        for strategy in strategies {
606            Self::add_python_strategy(&mut self.0, &strategy)?;
607        }
608        Ok(())
609    }
610
611    /// Adds multiple execution algorithms from constructed Python instances. Stops at the first error.
612    #[pyo3(name = "add_exec_algorithms")]
613    fn py_add_exec_algorithms(&mut self, exec_algorithms: Vec<Py<PyAny>>) -> PyResult<()> {
614        for exec_algorithm in exec_algorithms {
615            Self::add_python_exec_algorithm(&mut self.0, &exec_algorithm)?;
616        }
617        Ok(())
618    }
619
620    /// Sorts the engine's internal data stream by timestamp.
621    #[pyo3(name = "sort_data")]
622    fn py_sort_data(&mut self) {
623        self.0.sort_data();
624    }
625
626    /// Returns the trader ID for this engine.
627    #[getter]
628    #[pyo3(name = "trader_id")]
629    fn py_trader_id(&self) -> TraderId {
630        self.0.trader_id()
631    }
632
633    /// Returns the machine ID for this engine.
634    #[getter]
635    #[pyo3(name = "machine_id")]
636    fn py_machine_id(&self) -> String {
637        self.0.machine_id().to_string()
638    }
639
640    /// Returns the unique instance ID for this engine.
641    #[getter]
642    #[pyo3(name = "instance_id")]
643    fn py_instance_id(&self) -> UUID4 {
644        self.0.instance_id()
645    }
646
647    /// Returns the current iteration count.
648    #[getter]
649    #[pyo3(name = "iteration")]
650    fn py_iteration(&self) -> usize {
651        self.0.iteration()
652    }
653
654    /// Returns the last run config ID, if any.
655    #[getter]
656    #[pyo3(name = "run_config_id")]
657    fn py_run_config_id(&self) -> Option<String> {
658        self.0.run_config_id().map(str::to_string)
659    }
660
661    /// Returns the last run ID, if any.
662    #[getter]
663    #[pyo3(name = "run_id")]
664    fn py_run_id(&self) -> Option<UUID4> {
665        self.0.run_id()
666    }
667
668    /// Returns when the last run started, in nanoseconds since the UNIX epoch.
669    #[getter]
670    #[pyo3(name = "run_started")]
671    fn py_run_started(&self) -> Option<u64> {
672        self.0.run_started().map(|n| n.as_u64())
673    }
674
675    /// Returns when the last run finished, in nanoseconds since the UNIX epoch.
676    #[getter]
677    #[pyo3(name = "run_finished")]
678    fn py_run_finished(&self) -> Option<u64> {
679        self.0.run_finished().map(|n| n.as_u64())
680    }
681
682    /// Returns the last backtest range start, in nanoseconds since the UNIX epoch.
683    #[getter]
684    #[pyo3(name = "backtest_start")]
685    fn py_backtest_start(&self) -> Option<u64> {
686        self.0.backtest_start().map(|n| n.as_u64())
687    }
688
689    /// Returns the last backtest range end, in nanoseconds since the UNIX epoch.
690    #[getter]
691    #[pyo3(name = "backtest_end")]
692    fn py_backtest_end(&self) -> Option<u64> {
693        self.0.backtest_end().map(|n| n.as_u64())
694    }
695
696    /// Returns the list of registered venue identifiers.
697    #[pyo3(name = "list_venues")]
698    fn py_list_venues(&self) -> Vec<Venue> {
699        self.0.list_venues()
700    }
701
702    /// Returns the cache shared with the kernel and registered components.
703    #[getter]
704    #[pyo3(name = "cache")]
705    fn py_cache(&self) -> PyCache {
706        engine_cache(&self.0)
707    }
708
709    /// Returns the portfolio shared with the kernel and registered components.
710    #[getter]
711    #[pyo3(name = "portfolio")]
712    fn py_portfolio(&self) -> PyPortfolio {
713        engine_portfolio(&self.0)
714    }
715
716    /// Generates an orders report as a pandas `DataFrame`.
717    ///
718    /// # Errors
719    ///
720    /// Returns an error if the Python `ReportProvider` import or call fails.
721    #[pyo3(name = "generate_orders_report")]
722    fn py_generate_orders_report<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
723        generate_orders_report(&self.0, py)
724    }
725
726    /// Generates an order fills report as a pandas `DataFrame`.
727    ///
728    /// # Errors
729    ///
730    /// Returns an error if the Python `ReportProvider` import or call fails.
731    #[pyo3(name = "generate_order_fills_report")]
732    fn py_generate_order_fills_report<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
733        generate_order_fills_report(&self.0, py)
734    }
735
736    /// Generates a fills report as a pandas `DataFrame`.
737    ///
738    /// # Errors
739    ///
740    /// Returns an error if the Python `ReportProvider` import or call fails.
741    #[pyo3(name = "generate_fills_report")]
742    fn py_generate_fills_report<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
743        generate_fills_report(&self.0, py)
744    }
745
746    /// Generates a positions report as a pandas `DataFrame`.
747    ///
748    /// # Errors
749    ///
750    /// Returns an error if the Python `ReportProvider` import or call fails.
751    #[pyo3(name = "generate_positions_report")]
752    fn py_generate_positions_report<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
753        generate_positions_report(&self.0, py)
754    }
755
756    /// Generates an account report as a pandas `DataFrame`.
757    ///
758    /// At least one of `venue` or `account_id` must be provided.
759    ///
760    /// # Errors
761    ///
762    /// Returns an error if neither `venue` nor `account_id` is provided, or if the Python
763    /// `ReportProvider` import or call fails.
764    #[pyo3(name = "generate_account_report", signature = (venue=None, account_id=None))]
765    fn py_generate_account_report<'py>(
766        &self,
767        py: Python<'py>,
768        venue: Option<Venue>,
769        account_id: Option<AccountId>,
770    ) -> PyResult<Bound<'py, PyAny>> {
771        generate_account_report(&self.0, py, venue, account_id)
772    }
773
774    fn __repr__(&self) -> String {
775        format!("{:?}", self.0)
776    }
777}
778
779pub(super) fn engine_cache(engine: &BacktestEngine) -> PyCache {
780    PyCache::from_rc(engine.kernel().cache.clone())
781}
782
783pub(super) fn engine_portfolio(engine: &BacktestEngine) -> PyPortfolio {
784    PyPortfolio::from_rc(engine.kernel().portfolio.clone())
785}
786
787pub(super) fn generate_orders_report<'py>(
788    engine: &BacktestEngine,
789    py: Python<'py>,
790) -> PyResult<Bound<'py, PyAny>> {
791    let orders = cache_bound(engine, py)?.call_method0("orders")?;
792    report_provider(py)?.call_method1("generate_orders_report", (orders,))
793}
794
795pub(super) fn generate_order_fills_report<'py>(
796    engine: &BacktestEngine,
797    py: Python<'py>,
798) -> PyResult<Bound<'py, PyAny>> {
799    let orders = cache_bound(engine, py)?.call_method0("orders")?;
800    report_provider(py)?.call_method1("generate_order_fills_report", (orders,))
801}
802
803pub(super) fn generate_fills_report<'py>(
804    engine: &BacktestEngine,
805    py: Python<'py>,
806) -> PyResult<Bound<'py, PyAny>> {
807    let orders = cache_bound(engine, py)?.call_method0("orders")?;
808    report_provider(py)?.call_method1("generate_fills_report", (orders,))
809}
810
811pub(super) fn generate_positions_report<'py>(
812    engine: &BacktestEngine,
813    py: Python<'py>,
814) -> PyResult<Bound<'py, PyAny>> {
815    let cache = cache_bound(engine, py)?;
816    let positions = cache.call_method0("positions")?;
817    let snapshots = cache.call_method0("position_snapshots")?;
818    report_provider(py)?.call_method1("generate_positions_report", (positions, snapshots))
819}
820
821pub(super) fn generate_account_report<'py>(
822    engine: &BacktestEngine,
823    py: Python<'py>,
824    venue: Option<Venue>,
825    account_id: Option<AccountId>,
826) -> PyResult<Bound<'py, PyAny>> {
827    let cache = cache_bound(engine, py)?;
828    let account = match (account_id, venue) {
829        (Some(aid), _) => cache.call_method1("account", (aid,))?,
830        (None, Some(v)) => cache.call_method1("account_for_venue", (v,))?,
831        (None, None) => {
832            return Err(to_pyvalue_err(
833                "At least one of 'venue' or 'account_id' must be provided",
834            ));
835        }
836    };
837
838    if account.is_none() {
839        return py.import("pandas")?.call_method0("DataFrame");
840    }
841    report_provider(py)?.call_method1("generate_account_report", (account,))
842}
843
844fn cache_bound<'py>(engine: &BacktestEngine, py: Python<'py>) -> PyResult<Bound<'py, PyCache>> {
845    Ok(Py::new(py, engine_cache(engine))?.into_bound(py))
846}
847
848fn report_provider(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
849    py.import("nautilus_trader.analysis.reporter")?
850        .getattr("ReportProvider")
851}
852
853impl PyBacktestEngine {
854    /// Provides access to the inner [`BacktestEngine`].
855    #[must_use]
856    pub fn inner(&self) -> &BacktestEngine {
857        &self.0
858    }
859
860    /// Provides mutable access to the inner [`BacktestEngine`].
861    pub fn inner_mut(&mut self) -> &mut BacktestEngine {
862        &mut self.0
863    }
864
865    /// Configures and registers a constructed Python strategy instance.
866    ///
867    /// Shared by `add_strategy` (caller-constructed instance) and
868    /// `add_strategy_from_config` (imported and constructed here). The strategy ID,
869    /// order ID tag, and logging flags are sourced from the instance's retained
870    /// `.config`, so both entry points use a single config object.
871    #[allow(
872        unsafe_code,
873        reason = "Required for Python strategy component registration"
874    )]
875    pub(crate) fn add_python_strategy(
876        engine: &mut BacktestEngine,
877        strategy: &Py<PyAny>,
878    ) -> PyResult<()> {
879        let strategy_id = engine
880            .kernel_mut()
881            .trader
882            .borrow_mut()
883            .add_python_strategy_instance(strategy)
884            .map_err(to_pyruntime_err)?;
885
886        let oms_type = Python::attach(|py| -> PyResult<Option<OmsType>> {
887            Ok(strategy
888                .bind(py)
889                .getattr("config")
890                .ok()
891                .filter(|config| !config.is_none())
892                .and_then(|cfg| cfg.getattr("oms_type").ok())
893                .filter(|value| !value.is_none())
894                .and_then(|value| value.extract::<OmsType>().ok()))
895        })?;
896
897        if let Some(oms_type) = oms_type {
898            engine
899                .kernel()
900                .exec_engine
901                .borrow_mut()
902                .register_oms_type(strategy_id, oms_type);
903        }
904
905        Ok(())
906    }
907
908    /// Configures and registers a constructed Python actor instance.
909    ///
910    /// Shared by `add_actor` (caller-constructed instance) and `add_actor_from_config`
911    /// (imported and constructed here). The actor ID and logging flags are sourced from
912    /// the instance's retained `.config`, so both entry points use a single config object.
913    pub(crate) fn add_python_actor(engine: &mut BacktestEngine, actor: &Py<PyAny>) -> PyResult<()> {
914        let actor_id = Python::attach(|py| -> anyhow::Result<ActorId> {
915            let bound = actor.bind(py);
916
917            let config_instance = bound
918                .getattr("config")
919                .ok()
920                .filter(|config| !config.is_none());
921
922            prepare_python_actor(bound, config_instance.as_ref())
923        })
924        .map_err(to_pyruntime_err)?;
925
926        if engine
927            .kernel()
928            .trader
929            .borrow()
930            .actor_ids()
931            .contains(&actor_id)
932        {
933            return Err(to_pyruntime_err(format!(
934                "Actor '{actor_id}' is already registered"
935            )));
936        }
937
938        engine
939            .kernel_mut()
940            .trader
941            .borrow_mut()
942            .add_python_actor_instance(actor, actor_id)
943            .map_err(to_pyruntime_err)?;
944
945        log::info!("Registered Python actor {actor_id}");
946        Ok(())
947    }
948
949    /// Configures and registers a constructed Python execution algorithm instance.
950    ///
951    /// Shared by `add_exec_algorithm` (caller-constructed instance) and
952    /// `add_exec_algorithm_from_config` (imported and constructed here). The execution
953    /// algorithm ID and logging flags are sourced from the instance's retained `.config`.
954    pub(crate) fn add_python_exec_algorithm(
955        engine: &mut BacktestEngine,
956        exec_algorithm: &Py<PyAny>,
957    ) -> PyResult<()> {
958        Self::ensure_can_add_exec_algorithm(engine)?;
959
960        if Self::try_add_py_execution_algorithm(engine, exec_algorithm)? {
961            return Ok(());
962        }
963
964        let actor_id = Python::attach(|py| -> anyhow::Result<ActorId> {
965            let bound = exec_algorithm.bind(py);
966
967            let config_instance = bound
968                .getattr("config")
969                .ok()
970                .filter(|config| !config.is_none());
971
972            let mut py_data_actor_ref = bound
973                .extract::<PyRefMut<PyDataActor>>()
974                .map_err(Into::<PyErr>::into)
975                .map_err(|e| anyhow::anyhow!("Failed to extract PyDataActor: {e}"))?;
976
977            if let Some(config) = config_instance.as_ref() {
978                Self::configure_python_exec_algorithm(&mut py_data_actor_ref, config)?;
979            }
980
981            py_data_actor_ref.set_python_instance(bound)?;
982            let actor_id = py_data_actor_ref.actor_id();
983
984            Ok(actor_id)
985        })
986        .map_err(to_pyruntime_err)?;
987
988        let exec_algorithm_id = engine
989            .kernel_mut()
990            .trader
991            .borrow_mut()
992            .add_python_exec_algorithm_instance(exec_algorithm, actor_id)
993            .map_err(to_pyruntime_err)?;
994
995        log::info!("Registered Python exec algorithm {exec_algorithm_id}");
996        Ok(())
997    }
998
999    fn configure_python_exec_algorithm(
1000        actor: &mut PyDataActor,
1001        config: &Bound<'_, PyAny>,
1002    ) -> anyhow::Result<()> {
1003        let id_attr = config
1004            .getattr("exec_algorithm_id")
1005            .ok()
1006            .filter(|v| !v.is_none())
1007            .or_else(|| config.getattr("actor_id").ok().filter(|v| !v.is_none()));
1008
1009        if let Some(id_value) = id_attr {
1010            let actor_id = Self::exec_algorithm_actor_id(&id_value)?;
1011            actor.set_actor_id(actor_id);
1012        }
1013
1014        if let Ok(log_events) = config.getattr("log_events")
1015            && let Ok(log_events_val) = log_events.extract::<bool>()
1016        {
1017            actor.set_log_events(log_events_val);
1018        }
1019
1020        if let Ok(log_commands) = config.getattr("log_commands")
1021            && let Ok(log_commands_val) = log_commands.extract::<bool>()
1022        {
1023            actor.set_log_commands(log_commands_val);
1024        }
1025
1026        Ok(())
1027    }
1028
1029    fn exec_algorithm_actor_id(id_value: &Bound<'_, PyAny>) -> anyhow::Result<ActorId> {
1030        Ok(if let Ok(eaid) = id_value.extract::<ExecAlgorithmId>() {
1031            ActorId::new(eaid.inner())
1032        } else if let Ok(aid) = id_value.extract::<ActorId>() {
1033            aid
1034        } else if let Ok(aid_str) = id_value.extract::<String>() {
1035            ActorId::new_checked(&aid_str)?
1036        } else {
1037            anyhow::bail!("Invalid `exec_algorithm_id`/`actor_id` type");
1038        })
1039    }
1040
1041    fn try_add_py_execution_algorithm(
1042        engine: &mut BacktestEngine,
1043        exec_algorithm: &Py<PyAny>,
1044    ) -> PyResult<bool> {
1045        let py_exec_algorithm =
1046            Python::attach(|py| -> anyhow::Result<Option<PyExecutionAlgorithm>> {
1047                let bound = exec_algorithm.bind(py);
1048
1049                let config_instance = bound
1050                    .getattr("config")
1051                    .ok()
1052                    .filter(|config| !config.is_none());
1053
1054                let Ok(mut py_exec_algorithm_ref) =
1055                    bound.extract::<PyRefMut<PyExecutionAlgorithm>>()
1056                else {
1057                    return Ok(None);
1058                };
1059
1060                if let Some(config_obj) = config_instance.as_ref() {
1061                    py_exec_algorithm_ref.configure_from_py_config(config_obj)?;
1062                }
1063
1064                py_exec_algorithm_ref.set_python_instance(bound)?;
1065
1066                Ok(Some(py_exec_algorithm_ref.clone()))
1067            })
1068            .map_err(to_pyruntime_err)?;
1069
1070        let Some(py_exec_algorithm) = py_exec_algorithm else {
1071            return Ok(false);
1072        };
1073
1074        let exec_algorithm_id = engine
1075            .kernel_mut()
1076            .trader
1077            .borrow_mut()
1078            .add_py_execution_algorithm_instance(py_exec_algorithm, exec_algorithm)
1079            .map_err(to_pyruntime_err)?;
1080
1081        log::info!("Registered Python exec algorithm {exec_algorithm_id}");
1082        Ok(true)
1083    }
1084
1085    /// Rejects adding an execution algorithm when the trader is running or disposed.
1086    ///
1087    /// Checked before importing and constructing the Python class in the `from_config`
1088    /// path so a rejected addition never runs user constructor code.
1089    pub(crate) fn ensure_can_add_exec_algorithm(engine: &BacktestEngine) -> PyResult<()> {
1090        match engine.kernel().trader.borrow().state() {
1091            ComponentState::PreInitialized | ComponentState::Ready | ComponentState::Stopped => {
1092                Ok(())
1093            }
1094            ComponentState::Running => Err(to_pyruntime_err(
1095                "Cannot add execution algorithms to running trader",
1096            )),
1097            ComponentState::Disposed => {
1098                Err(to_pyruntime_err("Cannot add components to disposed trader"))
1099            }
1100            state => Err(to_pyruntime_err(format!(
1101                "Cannot add execution algorithms in current state: {state}"
1102            ))),
1103        }
1104    }
1105}
1106
1107#[cfg(feature = "examples")]
1108type BuiltinActorRegister = for<'py> fn(&mut BacktestEngine, &Bound<'py, PyAny>) -> PyResult<()>;
1109
1110#[cfg(feature = "examples")]
1111type BuiltinStrategyRegister = for<'py> fn(&mut BacktestEngine, &Bound<'py, PyAny>) -> PyResult<()>;
1112
1113#[cfg(feature = "examples")]
1114fn builtin_actor_register(_type_name: &str) -> Option<BuiltinActorRegister> {
1115    None
1116}
1117
1118#[cfg(feature = "examples")]
1119fn builtin_strategy_register(type_name: &str) -> Option<BuiltinStrategyRegister> {
1120    match type_name {
1121        "CompositeMarketMaker" => Some(register_composite_market_maker),
1122        "DeltaNeutralVol" => Some(register_delta_neutral_vol),
1123        "EmaCross" => Some(register_ema_cross),
1124        "GridMarketMaker" => Some(register_grid_market_maker),
1125        "HurstVpinDirectional" => Some(register_hurst_vpin_directional),
1126        "OrderBookImbalance" => Some(register_orderbook_imbalance),
1127        _ => None,
1128    }
1129}
1130
1131type NativeExecutionAlgorithmRegister =
1132    for<'py> fn(&mut BacktestEngine, &Bound<'py, PyAny>) -> PyResult<()>;
1133
1134fn native_exec_algorithm_register(type_name: &str) -> Option<NativeExecutionAlgorithmRegister> {
1135    match type_name {
1136        "TwapAlgorithm" => Some(register_twap_algorithm),
1137        _ => None,
1138    }
1139}
1140
1141fn register_twap_algorithm(engine: &mut BacktestEngine, config: &Bound<'_, PyAny>) -> PyResult<()> {
1142    let config = config.extract::<TwapAlgorithmConfig>()?;
1143    if config.exec_algorithm_id.is_none() {
1144        return Err(to_pyvalue_err(
1145            "TwapAlgorithm config requires `exec_algorithm_id`",
1146        ));
1147    }
1148    engine
1149        .add_exec_algorithm(TwapAlgorithm::new(config))
1150        .map_err(to_pyruntime_err)
1151}
1152
1153#[cfg(feature = "examples")]
1154fn register_composite_market_maker(
1155    engine: &mut BacktestEngine,
1156    config: &Bound<'_, PyAny>,
1157) -> PyResult<()> {
1158    let config = config.extract::<CompositeMarketMakerConfig>()?;
1159    engine
1160        .add_strategy(CompositeMarketMaker::new(config))
1161        .map_err(to_pyruntime_err)
1162}
1163
1164#[cfg(feature = "examples")]
1165fn register_delta_neutral_vol(
1166    engine: &mut BacktestEngine,
1167    config: &Bound<'_, PyAny>,
1168) -> PyResult<()> {
1169    let config = config.extract::<DeltaNeutralVolConfig>()?;
1170    engine
1171        .add_strategy(DeltaNeutralVol::new(config))
1172        .map_err(to_pyruntime_err)
1173}
1174
1175#[cfg(feature = "examples")]
1176fn register_ema_cross(engine: &mut BacktestEngine, config: &Bound<'_, PyAny>) -> PyResult<()> {
1177    let config = config.extract::<EmaCrossConfig>()?;
1178    engine
1179        .add_strategy(EmaCross::from_config(config))
1180        .map_err(to_pyruntime_err)
1181}
1182
1183#[cfg(feature = "examples")]
1184fn register_grid_market_maker(
1185    engine: &mut BacktestEngine,
1186    config: &Bound<'_, PyAny>,
1187) -> PyResult<()> {
1188    let config = config.extract::<GridMarketMakerConfig>()?;
1189    engine
1190        .add_strategy(GridMarketMaker::new(config))
1191        .map_err(to_pyruntime_err)
1192}
1193
1194#[cfg(feature = "examples")]
1195fn register_hurst_vpin_directional(
1196    engine: &mut BacktestEngine,
1197    config: &Bound<'_, PyAny>,
1198) -> PyResult<()> {
1199    let config = config.extract::<HurstVpinDirectionalConfig>()?;
1200    let strategy =
1201        HurstVpinDirectional::new_checked(config).map_err(config_error_to_pyvalue_err)?;
1202    engine.add_strategy(strategy).map_err(to_pyruntime_err)
1203}
1204
1205#[cfg(feature = "examples")]
1206pub(super) fn register_orderbook_imbalance(
1207    engine: &mut BacktestEngine,
1208    config: &Bound<'_, PyAny>,
1209) -> PyResult<()> {
1210    let config = config.extract::<OrderBookImbalanceConfig>()?;
1211    engine
1212        .add_strategy(OrderBookImbalance::from_config(config).map_err(to_pyvalue_err)?)
1213        .map_err(to_pyruntime_err)
1214}
1215
1216#[cfg(all(test, feature = "examples"))]
1217mod tests {
1218    use nautilus_common::python::actor::PyDataActor;
1219    use nautilus_model::identifiers::{ActorId, ExecAlgorithmId};
1220    use pyo3::{
1221        IntoPyObjectExt, PyRef, PyRefMut, Python,
1222        types::{PyAnyMethods, PyDict, PyDictMethods},
1223    };
1224    use rstest::rstest;
1225
1226    use crate::{config::BacktestEngineConfig, engine::BacktestEngine};
1227
1228    #[rstest]
1229    #[case("CompositeMarketMaker")]
1230    #[case("DeltaNeutralVol")]
1231    #[case("EmaCross")]
1232    #[case("GridMarketMaker")]
1233    #[case("HurstVpinDirectional")]
1234    #[case("OrderBookImbalance")]
1235    fn test_builtin_strategy_register_accepts_supported_names(#[case] type_name: &str) {
1236        assert!(super::builtin_strategy_register(type_name).is_some());
1237    }
1238
1239    #[rstest]
1240    fn test_builtin_register_rejects_unknown_names() {
1241        assert!(super::builtin_strategy_register("UnknownStrategy").is_none());
1242        assert!(super::builtin_actor_register("UnknownActor").is_none());
1243    }
1244
1245    #[rstest]
1246    fn test_builtin_strategy_register_rejects_mismatched_config() {
1247        Python::initialize();
1248
1249        let mut engine = BacktestEngine::new(BacktestEngineConfig::default()).unwrap();
1250        Python::attach(|py| {
1251            let register = super::builtin_strategy_register("EmaCross").unwrap();
1252            let config = PyDict::new(py);
1253            let error = register(&mut engine, config.as_any()).unwrap_err();
1254
1255            assert!(error.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
1256        });
1257    }
1258
1259    #[rstest]
1260    fn test_builtin_actor_register_rejects_retired_imbalance() {
1261        assert!(super::builtin_actor_register("BookImbalanceActor").is_none());
1262    }
1263
1264    #[rstest]
1265    fn test_add_strategy_registers_python_instance() {
1266        use nautilus_model::identifiers::StrategyId;
1267        use nautilus_trading::python::strategy::PyStrategy;
1268        use pyo3::{ffi::c_str, types::PyAnyMethods};
1269
1270        Python::initialize();
1271
1272        let mut engine =
1273            super::PyBacktestEngine(BacktestEngine::new(BacktestEngineConfig::default()).unwrap());
1274
1275        Python::attach(|py| {
1276            let config = py
1277                .eval(
1278                    c_str!("type('_Cfg', (), {'strategy_id': 'S-INSTANCE-001'})()"),
1279                    None,
1280                    None,
1281                )
1282                .unwrap();
1283            let instance = py
1284                .get_type::<PyStrategy>()
1285                .as_any()
1286                .call1((config,))
1287                .unwrap();
1288
1289            engine.py_add_strategy(&instance).unwrap();
1290
1291            assert!(
1292                engine
1293                    .0
1294                    .kernel()
1295                    .trader
1296                    .borrow()
1297                    .strategy_ids()
1298                    .contains(&StrategyId::from("S-INSTANCE-001"))
1299            );
1300        });
1301    }
1302
1303    #[rstest]
1304    fn test_add_actor_registers_python_instance() {
1305        use nautilus_common::python::actor::PyDataActor;
1306        use nautilus_model::identifiers::ActorId;
1307        use pyo3::{ffi::c_str, types::PyAnyMethods};
1308
1309        Python::initialize();
1310
1311        let mut engine =
1312            super::PyBacktestEngine(BacktestEngine::new(BacktestEngineConfig::default()).unwrap());
1313
1314        Python::attach(|py| {
1315            let config = py
1316                .eval(
1317                    c_str!("type('_Cfg', (), {'actor_id': 'A-INSTANCE-001'})()"),
1318                    None,
1319                    None,
1320                )
1321                .unwrap();
1322            let instance = py
1323                .get_type::<PyDataActor>()
1324                .as_any()
1325                .call1((config,))
1326                .unwrap();
1327
1328            engine.py_add_actor(&instance).unwrap();
1329
1330            assert!(
1331                engine
1332                    .0
1333                    .kernel()
1334                    .trader
1335                    .borrow()
1336                    .actor_ids()
1337                    .contains(&ActorId::from("A-INSTANCE-001"))
1338            );
1339        });
1340    }
1341
1342    #[rstest]
1343    #[case::string("string", Some("EXEC-CONFIG"))]
1344    #[case::exec_id("exec_id", Some("EXEC-CONFIG"))]
1345    #[case::actor_id("actor_id", Some("EXEC-CONFIG"))]
1346    #[case::fallback("fallback", Some("ACTOR-FALLBACK"))]
1347    #[case::invalid("invalid", None)]
1348    fn test_add_exec_algorithm_registers_python_instance(
1349        #[case] id_type: &str,
1350        #[case] expected_id: Option<&str>,
1351    ) {
1352        Python::initialize();
1353        let mut engine =
1354            super::PyBacktestEngine(BacktestEngine::new(BacktestEngineConfig::default()).unwrap());
1355
1356        Python::attach(|py| {
1357            let attributes = PyDict::new(py);
1358            attributes.set_item("actor_id", "ACTOR-FALLBACK").unwrap();
1359            attributes.set_item("log_events", false).unwrap();
1360            attributes.set_item("log_commands", true).unwrap();
1361
1362            let id = match id_type {
1363                "string" => Some("EXEC-CONFIG".into_py_any(py).unwrap()),
1364                "exec_id" => Some(
1365                    ExecAlgorithmId::from("EXEC-CONFIG")
1366                        .into_py_any(py)
1367                        .unwrap(),
1368                ),
1369                "actor_id" => Some(ActorId::from("EXEC-CONFIG").into_py_any(py).unwrap()),
1370                "invalid" => Some(42.into_py_any(py).unwrap()),
1371                "fallback" => None,
1372                _ => unreachable!(),
1373            };
1374
1375            if let Some(id) = id {
1376                attributes.set_item("exec_algorithm_id", id).unwrap();
1377            }
1378
1379            let config = py
1380                .import("types")
1381                .unwrap()
1382                .getattr("SimpleNamespace")
1383                .unwrap()
1384                .call((), Some(&attributes))
1385                .unwrap();
1386            let instance = py.get_type::<PyDataActor>().call0().unwrap();
1387            {
1388                let mut actor = instance.extract::<PyRefMut<'_, PyDataActor>>().unwrap();
1389                actor.set_config(Some(config.unbind()));
1390                actor.set_log_events(true);
1391                actor.set_log_commands(false);
1392            }
1393
1394            let result = engine.py_add_exec_algorithm(&instance);
1395            if let Some(expected_id) = expected_id {
1396                result.unwrap();
1397                let actor = instance.extract::<PyRef<'_, PyDataActor>>().unwrap();
1398                assert_eq!(
1399                    engine.0.kernel().trader.borrow().exec_algorithm_ids(),
1400                    vec![ExecAlgorithmId::from(expected_id)]
1401                );
1402                assert_eq!(
1403                    (actor.config.log_events, actor.config.log_commands),
1404                    (false, true)
1405                );
1406            } else {
1407                assert_eq!(
1408                    result.unwrap_err().to_string(),
1409                    "RuntimeError: Invalid `exec_algorithm_id`/`actor_id` type"
1410                );
1411                assert_eq!(
1412                    engine.0.kernel().trader.borrow().exec_algorithm_ids(),
1413                    Vec::new()
1414                );
1415            }
1416        });
1417    }
1418
1419    #[rstest]
1420    fn test_add_exec_algorithm_retains_py_execution_algorithm_wrapper() {
1421        use nautilus_common::python::wrappers::get_python_wrapper;
1422        use nautilus_model::identifiers::{ComponentId, ExecAlgorithmId};
1423        use nautilus_trading::python::algorithm::PyExecutionAlgorithm;
1424        use pyo3::{ffi::c_str, types::PyAnyMethods};
1425
1426        Python::initialize();
1427
1428        let mut engine =
1429            super::PyBacktestEngine(BacktestEngine::new(BacktestEngineConfig::default()).unwrap());
1430
1431        Python::attach(|py| {
1432            let config = py
1433                .eval(
1434                    c_str!("type('_Cfg', (), {'exec_algorithm_id': 'EXEC-WRAPPED-001'})()"),
1435                    None,
1436                    None,
1437                )
1438                .unwrap();
1439            let instance = py
1440                .get_type::<PyExecutionAlgorithm>()
1441                .as_any()
1442                .call1((config,))
1443                .unwrap();
1444
1445            engine.py_add_exec_algorithm(&instance).unwrap();
1446
1447            assert!(
1448                engine
1449                    .0
1450                    .kernel()
1451                    .trader
1452                    .borrow()
1453                    .exec_algorithm_ids()
1454                    .contains(&ExecAlgorithmId::from("EXEC-WRAPPED-001"))
1455            );
1456            assert!(
1457                get_python_wrapper(ComponentId::from("EXEC-WRAPPED-001"))
1458                    .expect("registering must retain the algorithm's Python wrapper")
1459                    .bind(py)
1460                    .is(&instance)
1461            );
1462        });
1463    }
1464
1465    #[rstest]
1466    fn test_add_exec_algorithm_colliding_with_actor_leaves_the_actor_registered() {
1467        use nautilus_common::python::{actor::PyDataActor, wrappers::get_python_wrapper};
1468        use nautilus_model::identifiers::{ActorId, ComponentId};
1469        use nautilus_trading::python::algorithm::PyExecutionAlgorithm;
1470        use pyo3::{ffi::c_str, types::PyAnyMethods};
1471
1472        Python::initialize();
1473
1474        let mut engine =
1475            super::PyBacktestEngine(BacktestEngine::new(BacktestEngineConfig::default()).unwrap());
1476
1477        Python::attach(|py| {
1478            let actor_config = py
1479                .eval(
1480                    c_str!("type('_Cfg', (), {'actor_id': 'COLLIDING-ALGO'})()"),
1481                    None,
1482                    None,
1483                )
1484                .unwrap();
1485            let actor = py
1486                .get_type::<PyDataActor>()
1487                .as_any()
1488                .call1((actor_config,))
1489                .unwrap();
1490
1491            engine.py_add_actor(&actor).unwrap();
1492
1493            let algorithm_config = py
1494                .eval(
1495                    c_str!("type('_Cfg', (), {'exec_algorithm_id': 'COLLIDING-ALGO'})()"),
1496                    None,
1497                    None,
1498                )
1499                .unwrap();
1500            let algorithm = py
1501                .get_type::<PyExecutionAlgorithm>()
1502                .as_any()
1503                .call1((algorithm_config,))
1504                .unwrap();
1505
1506            let error = engine
1507                .py_add_exec_algorithm(&algorithm)
1508                .expect_err("an algorithm colliding with a live actor must not register");
1509            assert!(error.to_string().contains("already registered"));
1510
1511            assert_eq!(
1512                engine.0.kernel().trader.borrow().actor_ids(),
1513                vec![ActorId::from("COLLIDING-ALGO")]
1514            );
1515            assert!(
1516                engine
1517                    .0
1518                    .kernel()
1519                    .trader
1520                    .borrow()
1521                    .exec_algorithm_ids()
1522                    .is_empty()
1523            );
1524            assert!(
1525                get_python_wrapper(ComponentId::from("COLLIDING-ALGO"))
1526                    .expect("the actor must still hold its wrapper")
1527                    .bind(py)
1528                    .is(&actor)
1529            );
1530        });
1531    }
1532
1533    #[rstest]
1534    fn test_add_strategies_registers_multiple_python_instances() {
1535        use nautilus_model::identifiers::StrategyId;
1536        use nautilus_trading::python::strategy::PyStrategy;
1537        use pyo3::{ffi::c_str, types::PyAnyMethods};
1538
1539        Python::initialize();
1540
1541        let mut engine =
1542            super::PyBacktestEngine(BacktestEngine::new(BacktestEngineConfig::default()).unwrap());
1543
1544        Python::attach(|py| {
1545            let strategy_type = py.get_type::<PyStrategy>();
1546            let first_config = py
1547                .eval(
1548                    c_str!("type('_Cfg', (), {'strategy_id': 'S-MULTI-001'})()"),
1549                    None,
1550                    None,
1551                )
1552                .unwrap();
1553            let second_config = py
1554                .eval(
1555                    c_str!("type('_Cfg', (), {'strategy_id': 'S-MULTI-002'})()"),
1556                    None,
1557                    None,
1558                )
1559                .unwrap();
1560            let instances = vec![
1561                strategy_type
1562                    .as_any()
1563                    .call1((first_config,))
1564                    .unwrap()
1565                    .unbind(),
1566                strategy_type
1567                    .as_any()
1568                    .call1((second_config,))
1569                    .unwrap()
1570                    .unbind(),
1571            ];
1572
1573            engine.py_add_strategies(instances).unwrap();
1574
1575            let trader = engine.0.kernel().trader.borrow();
1576            let strategy_ids = trader.strategy_ids();
1577            assert!(strategy_ids.contains(&StrategyId::from("S-MULTI-001")));
1578            assert!(strategy_ids.contains(&StrategyId::from("S-MULTI-002")));
1579        });
1580    }
1581
1582    #[rstest]
1583    fn test_add_exec_algorithms_registers_multiple_python_instances() {
1584        use nautilus_common::python::actor::PyDataActor;
1585        use nautilus_model::identifiers::ExecAlgorithmId;
1586        use pyo3::{ffi::c_str, types::PyAnyMethods};
1587
1588        Python::initialize();
1589
1590        let mut engine =
1591            super::PyBacktestEngine(BacktestEngine::new(BacktestEngineConfig::default()).unwrap());
1592
1593        Python::attach(|py| {
1594            let algo_type = py.get_type::<PyDataActor>();
1595            let first_config = py
1596                .eval(
1597                    c_str!("type('_Cfg', (), {'exec_algorithm_id': 'EXEC-MULTI-001'})()"),
1598                    None,
1599                    None,
1600                )
1601                .unwrap();
1602            let second_config = py
1603                .eval(
1604                    c_str!("type('_Cfg', (), {'exec_algorithm_id': 'EXEC-MULTI-002'})()"),
1605                    None,
1606                    None,
1607                )
1608                .unwrap();
1609            let instances = vec![
1610                algo_type.as_any().call1((first_config,)).unwrap().unbind(),
1611                algo_type.as_any().call1((second_config,)).unwrap().unbind(),
1612            ];
1613
1614            engine.py_add_exec_algorithms(instances).unwrap();
1615
1616            let trader = engine.0.kernel().trader.borrow();
1617            let exec_algorithm_ids = trader.exec_algorithm_ids();
1618            assert!(exec_algorithm_ids.contains(&ExecAlgorithmId::from("EXEC-MULTI-001")));
1619            assert!(exec_algorithm_ids.contains(&ExecAlgorithmId::from("EXEC-MULTI-002")));
1620        });
1621    }
1622}
1623
1624fn pyobject_to_data(_py: Python, obj: &Bound<'_, PyAny>) -> PyResult<Data> {
1625    if let Ok(delta) = obj.extract::<OrderBookDelta>() {
1626        return Ok(Data::BookDelta(delta));
1627    }
1628
1629    if let Ok(deltas) = obj.extract::<OrderBookDeltas>() {
1630        return Ok(Data::BookDeltas(Box::new(deltas)));
1631    }
1632
1633    if let Ok(quote) = obj.extract::<QuoteTick>() {
1634        return Ok(Data::Quote(quote));
1635    }
1636
1637    if let Ok(trade) = obj.extract::<TradeTick>() {
1638        return Ok(Data::Trade(trade));
1639    }
1640
1641    if let Ok(bar) = obj.extract::<Bar>() {
1642        return Ok(Data::Bar(bar));
1643    }
1644
1645    if let Ok(depth) = obj.extract::<OrderBookDepth>() {
1646        return Ok(Data::BookDepth(Box::new(depth)));
1647    }
1648
1649    if let Ok(mark) = obj.extract::<MarkPriceUpdate>() {
1650        return Ok(Data::MarkPrice(mark));
1651    }
1652
1653    if let Ok(index) = obj.extract::<IndexPriceUpdate>() {
1654        return Ok(Data::IndexPrice(index));
1655    }
1656
1657    if let Ok(funding_rate) = obj.extract::<FundingRateUpdate>() {
1658        return Ok(Data::FundingRate(funding_rate));
1659    }
1660
1661    if let Ok(greeks) = obj.extract::<OptionGreeks>() {
1662        return Ok(Data::OptionGreeks(greeks));
1663    }
1664
1665    if let Ok(status) = obj.extract::<InstrumentStatus>() {
1666        return Ok(Data::InstrumentStatus(status));
1667    }
1668
1669    if let Ok(close) = obj.extract::<InstrumentClose>() {
1670        return Ok(Data::InstrumentClose(close));
1671    }
1672
1673    if let Ok(custom) = obj.extract::<CustomData>() {
1674        return Ok(Data::Custom(custom));
1675    }
1676
1677    #[cfg(feature = "defi")]
1678    if let Ok(defi) = obj.extract::<DefiData>() {
1679        return Ok(Data::Defi(Box::new(defi)));
1680    }
1681
1682    let type_name = obj.get_type().name()?;
1683    Err(to_pytype_err(format!("Cannot convert {type_name} to Data")))
1684}
1685
1686#[cfg(test)]
1687mod model_tests {
1688    use nautilus_execution::{
1689        matching_engine::config::OrderPriorityResetPolicy,
1690        models::fee::{FeeModelAny, MakerTakerFeeModel},
1691        python::{fee::PyFeeModel, fill::PyFillModel},
1692    };
1693    use nautilus_model::{
1694        accounts::AccountAny,
1695        data::{
1696            Bar, BarType, Data,
1697            stubs::{quote_audusd, stub_custom_data},
1698        },
1699        enums::{AccountType, BookType, OmsType, OtoTriggerMode},
1700        identifiers::Venue,
1701        instruments::{
1702            InstrumentAny,
1703            stubs::{audusd_sim, crypto_perpetual_ethusdt},
1704        },
1705        types::{Currency, Money, Price, Quantity},
1706    };
1707    use pyo3::{
1708        IntoPyObjectExt, Python,
1709        exceptions::PyRuntimeError,
1710        ffi::c_str,
1711        types::{PyAnyMethods, PyDict, PyDictMethods},
1712    };
1713    use rstest::rstest;
1714
1715    use crate::{
1716        config::{BacktestEngineConfig, SimulatedVenueConfig},
1717        engine::BacktestEngine,
1718    };
1719
1720    #[rstest]
1721    #[case::tick("TICK")]
1722    #[case::volume("VOLUME")]
1723    #[case::value("VALUE")]
1724    fn test_run_non_time_bar_raises_runtime_error(#[case] aggregation: &str) {
1725        Python::initialize();
1726
1727        let mut engine =
1728            super::PyBacktestEngine(BacktestEngine::new(BacktestEngineConfig::default()).unwrap());
1729        let config = SimulatedVenueConfig::builder()
1730            .venue(Venue::from("BINANCE"))
1731            .oms_type(OmsType::Netting)
1732            .account_type(AccountType::Margin)
1733            .book_type(BookType::L1_MBP)
1734            .starting_balances(vec![Money::from("1_000_000 USDT")])
1735            .fee_model(FeeModelAny::MakerTaker(MakerTakerFeeModel::zero()).into())
1736            .build()
1737            .unwrap();
1738        engine.0.add_venue(config).unwrap();
1739        let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
1740        engine.0.add_instrument(&instrument).unwrap();
1741        let bar_type =
1742            BarType::from(format!("ETHUSDT-PERP.BINANCE-200-{aggregation}-LAST-EXTERNAL").as_str());
1743
1744        let bar = Bar::new(
1745            bar_type,
1746            Price::from("1500.00"),
1747            Price::from("1505.00"),
1748            Price::from("1490.00"),
1749            Price::from("1502.00"),
1750            Quantity::from("100.000"),
1751            1_000_000_000.into(),
1752            1_000_000_000.into(),
1753        );
1754        engine
1755            .0
1756            .add_data(vec![Data::Bar(bar)], None, true, true)
1757            .unwrap();
1758
1759        let error = engine.py_run(None, None, None, false).unwrap_err();
1760        engine.0.dispose();
1761
1762        Python::attach(|py| {
1763            assert!(error.is_instance_of::<PyRuntimeError>(py));
1764        });
1765
1766        assert_eq!(
1767            error.to_string(),
1768            format!(
1769                "RuntimeError: Bar execution requires time-aggregated bars, received {bar_type}"
1770            )
1771        );
1772    }
1773
1774    #[rstest]
1775    fn test_pyobject_to_data_accepts_custom_data() {
1776        Python::initialize();
1777
1778        Python::attach(|py| {
1779            let custom = stub_custom_data(2, 42, None, None);
1780            let obj = custom.into_py_any(py).unwrap();
1781            let converted = super::pyobject_to_data(py, obj.bind(py)).unwrap();
1782
1783            let Data::Custom(converted) = converted else {
1784                panic!("Expected Data::Custom");
1785            };
1786            assert_eq!(converted.data_type.type_name(), "StubCustomData");
1787            assert_eq!(converted.data.ts_init().as_u64(), 2);
1788        });
1789    }
1790
1791    #[rstest]
1792    fn test_pyobject_to_data_rejects_duck_typed_object() {
1793        Python::initialize();
1794
1795        Python::attach(|py| {
1796            // Mirrors the attribute shape the removed Cython `from_pyobject` path accepted
1797            let obj = py
1798                .eval(
1799                    c_str!(
1800                        "type('FakeQuote', (), {\
1801                            'instrument_id': type('I', (), {'value': 'AUD/USD.SIM'})(), \
1802                            'bid_price': type('P', (), {'raw': 1, 'precision': 5})(), \
1803                            'ask_price': type('P', (), {'raw': 1, 'precision': 5})(), \
1804                            'bid_size': type('Q', (), {'raw': 1, 'precision': 0})(), \
1805                            'ask_size': type('Q', (), {'raw': 1, 'precision': 0})(), \
1806                            'ts_event': 0, \
1807                            'ts_init': 0\
1808                        })()"
1809                    ),
1810                    None,
1811                    None,
1812                )
1813                .unwrap();
1814
1815            let err = super::pyobject_to_data(py, &obj).unwrap_err();
1816
1817            assert_eq!(
1818                err.to_string(),
1819                "TypeError: Cannot convert FakeQuote to Data"
1820            );
1821        });
1822    }
1823
1824    #[rstest]
1825    fn test_add_venue_accepts_python_defined_fee_fill_and_margin_models() {
1826        Python::initialize();
1827
1828        let mut engine =
1829            super::PyBacktestEngine(BacktestEngine::new(BacktestEngineConfig::default()).unwrap());
1830        Python::attach(|py| {
1831            let locals = PyDict::new(py);
1832            locals
1833                .set_item("FeeModel", py.get_type::<PyFeeModel>())
1834                .unwrap();
1835            locals
1836                .set_item("FillModel", py.get_type::<PyFillModel>())
1837                .unwrap();
1838
1839            let fill_model = py
1840                .eval(
1841                    c_str!(
1842                        "type('CustomFillModel', (FillModel,), {\
1843                            'is_limit_filled': lambda self: True, \
1844                            'is_slipped': lambda self: False\
1845                        })()"
1846                    ),
1847                    None,
1848                    Some(&locals),
1849                )
1850                .unwrap();
1851            let fee_model = py
1852                .eval(
1853                    c_str!(
1854                        "type('CustomFeeModel', (FeeModel,), {\
1855                            'get_commission': \
1856                                lambda self, order, fill_quantity, fill_px, instrument: self.commission\
1857                        })()"
1858                    ),
1859                    None,
1860                    Some(&locals),
1861                )
1862                .unwrap();
1863            fee_model
1864                .setattr("commission", Money::from("0 USD").into_py_any(py).unwrap())
1865                .unwrap();
1866
1867            locals
1868                .set_item("initial", Money::from("123.45 USD"))
1869                .unwrap();
1870            locals
1871                .set_item("maintenance", Money::from("67.89 USD"))
1872                .unwrap();
1873            let margin_model = py.eval(c_str!("type('Margin', (), {'calculate_initial_margin': lambda self, *args: initial, 'calculate_maintenance_margin': lambda self, *args: maintenance})()"), Some(&locals), None).unwrap();
1874
1875            engine
1876                .py_add_venue(
1877                    Venue::from("SIM"),
1878                    OmsType::Netting,
1879                    AccountType::Margin,
1880                    vec![Money::from("1_000_000 USD")],
1881                    None::<Currency>,
1882                    None,
1883                    None,
1884                    Some(fill_model.unbind()),
1885                    Some(fee_model.unbind()),
1886                    Some(margin_model.unbind()),
1887                    None,
1888                    None,
1889                    BookType::L1_MBP,
1890                    false,
1891                    true,
1892                    true,
1893                    true,
1894                    true,
1895                    false,
1896                    true,
1897                    true,
1898                    false,
1899                    true,
1900                    false,
1901                    true,
1902                    false,
1903                    false,
1904                    false,
1905                    false,
1906                    OtoTriggerMode::Partial,
1907                    None,
1908                    false,
1909                    None,
1910                    true,
1911                    OrderPriorityResetPolicy::PriceChange,
1912                )
1913                .unwrap();
1914
1915            let instrument = InstrumentAny::CurrencyPair(audusd_sim());
1916            engine.0.add_instrument(&instrument).unwrap();
1917            engine
1918                .0
1919                .add_data(vec![Data::Quote(quote_audusd())], None, true, true)
1920                .unwrap();
1921            engine.py_run(None, None, None, false).unwrap();
1922            let account = engine
1923                .0
1924                .kernel()
1925                .cache
1926                .borrow()
1927                .account_for_venue(&Venue::from("SIM"))
1928                .unwrap()
1929                .clone();
1930
1931            let AccountAny::Margin(account) = account else {
1932                panic!("expected margin account")
1933            };
1934
1935            let quantity = Quantity::from(10000);
1936            let price = Price::from("0.81234");
1937            assert_eq!(
1938                account
1939                    .calculate_initial_margin(&instrument, quantity, price, None)
1940                    .unwrap(),
1941                Money::from("123.45 USD")
1942            );
1943            assert_eq!(
1944                account
1945                    .calculate_maintenance_margin(&instrument, quantity, price, None)
1946                    .unwrap(),
1947                Money::from("67.89 USD")
1948            );
1949            assert_eq!(engine.0.list_venues(), vec![Venue::from("SIM")]);
1950        });
1951    }
1952}
1953
1954#[cfg(test)]
1955mod lifecycle_tests {
1956    use indexmap::IndexMap;
1957    use nautilus_model::identifiers::ActorId;
1958    use nautilus_testkit::{cache::TestCacheDatabaseControl, components::StateActor};
1959    use pyo3::Python;
1960    use rstest::rstest;
1961
1962    use super::PyBacktestEngine;
1963    use crate::{config::BacktestEngineConfig, engine::BacktestEngine};
1964
1965    #[rstest]
1966    fn test_end_continues_after_state_persistence_error() {
1967        Python::initialize();
1968
1969        let actor_id = ActorId::from("PY-END-FAIL-SAVE-ACTOR");
1970        let (database, control) = TestCacheDatabaseControl::create();
1971        control.set_fail_update_actor(true);
1972        let config = BacktestEngineConfig {
1973            save_state: true,
1974            run_analysis: false,
1975            ..Default::default()
1976        };
1977        let mut engine = PyBacktestEngine(BacktestEngine::new(config).unwrap());
1978        engine
1979            .0
1980            .kernel_mut()
1981            .cache
1982            .borrow_mut()
1983            .set_database(Box::new(database));
1984        engine
1985            .0
1986            .add_actor(StateActor::new(
1987                actor_id,
1988                control.clone(),
1989                IndexMap::from([("state".to_string(), b"value".to_vec())]),
1990            ))
1991            .unwrap();
1992        engine.0.kernel_mut().start();
1993        engine.0.kernel_mut().start_trader().unwrap();
1994        engine.0.kernel_mut().stop_trader();
1995
1996        engine.py_end().unwrap();
1997        engine.0.dispose();
1998
1999        assert_eq!(
2000            control.events(),
2001            vec![
2002                "actor.on_start",
2003                "actor.on_stop",
2004                "actor.on_save",
2005                "actor.update:PY-END-FAIL-SAVE-ACTOR",
2006                "database.close",
2007            ]
2008        );
2009    }
2010}