nautilus-system 0.53.0

System orchestration for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Central orchestrator for managing actors, strategies, and execution algorithms.
//!
//! The `Trader` component serves as the primary coordination layer between the kernel
//! and individual trading components. It manages component lifecycles, provides
//! unique identification, and coordinates with system engines.

use std::{cell::RefCell, fmt::Debug, rc::Rc};

use ahash::AHashMap;
use nautilus_common::{
    actor::{DataActor, registry::try_get_actor_unchecked},
    cache::Cache,
    clock::{Clock, TestClock},
    component::{
        Component, dispose_component, register_component_actor, reset_component, start_component,
        stop_component,
    },
    enums::{ComponentState, ComponentTrigger, Environment},
    msgbus,
    msgbus::{
        TypedHandler,
        switchboard::{get_event_orders_topic, get_event_positions_topic},
    },
    timer::{TimeEvent, TimeEventCallback},
};
use nautilus_core::{UUID4, UnixNanos};
use nautilus_model::{
    events::{OrderEventAny, PositionEvent},
    identifiers::{ActorId, ComponentId, ExecAlgorithmId, StrategyId, TraderId},
};
use nautilus_portfolio::portfolio::Portfolio;
use nautilus_trading::strategy::Strategy;
use ustr::Ustr;

/// Central orchestrator for managing trading components.
///
/// The `Trader` manages the lifecycle and coordination of actors, strategies,
/// and execution algorithms within the trading system. It provides component
/// registration, state management, and integration with system engines.
///
/// # Notes
///
/// Strategies implement `Strategy::stop() -> bool` which returns whether to proceed
/// with the component stop. This enables `manage_stop` behavior where the strategy
/// can defer stopping until a market exit completes.
///
/// We store type-erased closures because the component registry stores trait objects
/// and we need to call `Strategy::stop()` which requires the concrete type. The
/// closure is created during `add_strategy` when the concrete type `T` is known.
pub struct Trader {
    /// The unique trader identifier.
    pub trader_id: TraderId,
    /// The unique instance identifier.
    pub instance_id: UUID4,
    /// The trading environment context.
    pub environment: Environment,
    /// Component state for lifecycle management.
    state: ComponentState,
    /// System clock for timestamping.
    clock: Rc<RefCell<dyn Clock>>,
    /// System cache for data storage.
    cache: Rc<RefCell<Cache>>,
    /// Portfolio reference for strategy registration.
    portfolio: Rc<RefCell<Portfolio>>,
    /// Registered actor IDs (actors stored in global registry).
    actor_ids: Vec<ActorId>,
    /// Registered strategy IDs (strategies stored in global registry).
    strategy_ids: Vec<StrategyId>,
    /// Strategy stop functions for managed stop behavior.
    strategy_stop_fns: AHashMap<StrategyId, Box<dyn FnMut() -> bool>>,
    /// Msgbus handler IDs for strategy event subscriptions (order, position).
    strategy_handler_ids: AHashMap<StrategyId, (Ustr, Ustr)>,
    /// Registered exec algorithm IDs (algorithms stored in global registry).
    exec_algorithm_ids: Vec<ExecAlgorithmId>,
    /// Component clocks for individual components.
    clocks: AHashMap<ComponentId, Rc<RefCell<dyn Clock>>>,
    /// Timestamp when the trader was created.
    ts_created: UnixNanos,
    /// Timestamp when the trader was last started.
    ts_started: Option<UnixNanos>,
    /// Timestamp when the trader was last stopped.
    ts_stopped: Option<UnixNanos>,
}

impl Debug for Trader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", stringify!(TraderId)) // TODO
    }
}

impl Trader {
    /// Creates a new [`Trader`] instance.
    #[must_use]
    pub fn new(
        trader_id: TraderId,
        instance_id: UUID4,
        environment: Environment,
        clock: Rc<RefCell<dyn Clock>>,
        cache: Rc<RefCell<Cache>>,
        portfolio: Rc<RefCell<Portfolio>>,
    ) -> Self {
        let ts_created = clock.borrow().timestamp_ns();

        Self {
            trader_id,
            instance_id,
            environment,
            state: ComponentState::PreInitialized,
            clock,
            cache,
            portfolio,
            actor_ids: Vec::new(),
            strategy_ids: Vec::new(),
            strategy_stop_fns: AHashMap::new(),
            strategy_handler_ids: AHashMap::new(),
            exec_algorithm_ids: Vec::new(),
            clocks: AHashMap::new(),
            ts_created,
            ts_started: None,
            ts_stopped: None,
        }
    }

    /// Returns the trader ID.
    #[must_use]
    pub const fn trader_id(&self) -> TraderId {
        self.trader_id
    }

    /// Returns the instance ID.
    #[must_use]
    pub const fn instance_id(&self) -> UUID4 {
        self.instance_id
    }

    /// Returns the trading environment.
    #[must_use]
    pub const fn environment(&self) -> Environment {
        self.environment
    }

    /// Returns the current component state.
    #[must_use]
    pub const fn state(&self) -> ComponentState {
        self.state
    }

    /// Returns the timestamp when the trader was created (UNIX nanoseconds).
    #[must_use]
    pub const fn ts_created(&self) -> UnixNanos {
        self.ts_created
    }

    /// Returns the timestamp when the trader was last started (UNIX nanoseconds).
    #[must_use]
    pub const fn ts_started(&self) -> Option<UnixNanos> {
        self.ts_started
    }

    /// Returns the timestamp when the trader was last stopped (UNIX nanoseconds).
    #[must_use]
    pub const fn ts_stopped(&self) -> Option<UnixNanos> {
        self.ts_stopped
    }

    /// Returns the number of registered actors.
    #[must_use]
    pub const fn actor_count(&self) -> usize {
        self.actor_ids.len()
    }

    /// Returns the number of registered strategies.
    #[must_use]
    pub const fn strategy_count(&self) -> usize {
        self.strategy_ids.len()
    }

    /// Returns the number of registered execution algorithms.
    #[must_use]
    pub const fn exec_algorithm_count(&self) -> usize {
        self.exec_algorithm_ids.len()
    }

    /// Returns references to all component clocks for backtest time advancement.
    pub fn get_component_clocks(&self) -> Vec<Rc<RefCell<dyn Clock>>> {
        self.clocks.values().cloned().collect()
    }

    /// Returns the total number of registered components.
    #[must_use]
    pub const fn component_count(&self) -> usize {
        self.actor_ids.len() + self.strategy_ids.len() + self.exec_algorithm_ids.len()
    }

    /// Returns a list of all registered actor IDs.
    #[must_use]
    pub fn actor_ids(&self) -> Vec<ActorId> {
        self.actor_ids.clone()
    }

    /// Returns a list of all registered strategy IDs.
    #[must_use]
    pub fn strategy_ids(&self) -> Vec<StrategyId> {
        self.strategy_ids.clone()
    }

    /// Returns a list of all registered execution algorithm IDs.
    #[must_use]
    pub fn exec_algorithm_ids(&self) -> Vec<ExecAlgorithmId> {
        self.exec_algorithm_ids.clone()
    }

    /// Creates a clock for a component.
    ///
    /// Creates a test clock in backtest environment, otherwise returns a reference
    /// to the system clock.
    fn create_component_clock(&self) -> Rc<RefCell<dyn Clock>> {
        match self.environment {
            Environment::Backtest => {
                // Create individual test clock for component in backtest
                Rc::new(RefCell::new(TestClock::new()))
            }
            Environment::Live | Environment::Sandbox => {
                // Share system clock in live environments
                self.clock.clone()
            }
        }
    }

    /// Adds an actor to the trader.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The trader is not in a valid state for adding components.
    /// - An actor with the same ID is already registered.
    pub fn add_actor<T>(&mut self, actor: T) -> anyhow::Result<()>
    where
        T: DataActor + Component + Debug + 'static,
    {
        self.validate_component_registration()?;

        let actor_id = actor.actor_id();

        // Check for duplicate registration
        if self.actor_ids.contains(&actor_id) {
            anyhow::bail!("Actor {actor_id} is already registered");
        }

        let clock = self.create_component_clock();
        let component_id = ComponentId::new(actor_id.inner().as_str());
        self.clocks.insert(component_id, clock.clone());

        let mut actor_mut = actor;
        actor_mut.register(self.trader_id, clock, self.cache.clone())?;

        self.add_registered_actor(actor_mut)
    }

    /// Adds an actor to the trader using a factory function.
    ///
    /// The factory function is called at registration time to create the actor,
    /// avoiding cloning issues with non-cloneable actor types.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The factory function fails to create the actor.
    /// - The trader is not in a valid state for adding components.
    /// - An actor with the same ID is already registered.
    pub fn add_actor_from_factory<F, T>(&mut self, factory: F) -> anyhow::Result<()>
    where
        F: FnOnce() -> anyhow::Result<T>,
        T: DataActor + Component + Debug + 'static,
    {
        let actor = factory()?;

        self.add_actor(actor)
    }

    /// Adds an already registered actor to the trader's component registry.
    ///
    /// # Errors
    ///
    /// Returns an error if the actor cannot be registered in the component registry.
    pub fn add_registered_actor<T>(&mut self, actor: T) -> anyhow::Result<()>
    where
        T: DataActor + Component + Debug + 'static,
    {
        let actor_id = actor.actor_id();

        // Register in both component and actor registries (this consumes the actor)
        register_component_actor(actor);

        // Store actor ID for lifecycle management
        self.actor_ids.push(actor_id);

        log::info!("Registered actor {actor_id} with trader {}", self.trader_id);

        Ok(())
    }

    /// Adds an actor ID to the trader's lifecycle management without consuming the actor.
    ///
    /// This is useful when the actor is already registered in the global component registry
    /// but the trader needs to track it for lifecycle management. The caller is responsible
    /// for ensuring the actor is properly registered in the global registries.
    ///
    /// # Errors
    ///
    /// Returns an error if the actor ID is already tracked by this trader.
    pub fn add_actor_id_for_lifecycle(&mut self, actor_id: ActorId) -> anyhow::Result<()> {
        // Check for duplicate registration
        if self.actor_ids.contains(&actor_id) {
            anyhow::bail!("Actor '{actor_id}' is already tracked by trader");
        }

        // Store actor ID for lifecycle management
        self.actor_ids.push(actor_id);

        log::debug!(
            "Added actor ID '{actor_id}' to trader {} for lifecycle management",
            self.trader_id
        );

        Ok(())
    }

    /// Adds a strategy to the trader.
    ///
    /// Strategies are registered in both the component registry (for lifecycle management)
    /// and the actor registry (for data callbacks via msgbus). The strategy's `StrategyCore`
    /// is also registered with the portfolio for order management.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The trader is not in a valid state for adding components.
    /// - A strategy with the same ID is already registered.
    pub fn add_strategy<T>(&mut self, mut strategy: T) -> anyhow::Result<()>
    where
        T: Strategy + Component + Debug + 'static,
    {
        self.validate_component_registration()?;

        let strategy_id = StrategyId::from(strategy.component_id().inner().as_str());

        // Check for duplicate registration
        if self.strategy_ids.contains(&strategy_id) {
            anyhow::bail!("Strategy {strategy_id} is already registered");
        }

        let clock = self.create_component_clock();
        let component_id = strategy.component_id();
        self.clocks.insert(component_id, clock.clone());

        // Register strategy core with portfolio for order management
        strategy.core_mut().register(
            self.trader_id,
            clock.clone(),
            self.cache.clone(),
            self.portfolio.clone(),
        )?;

        // Register default time event handler for this strategy
        let actor_id = strategy.actor_id().inner();
        let callback = TimeEventCallback::from(move |event: TimeEvent| {
            if let Some(mut actor) = try_get_actor_unchecked::<T>(&actor_id) {
                actor.handle_time_event(&event);
            } else {
                log::error!("Strategy {actor_id} not found for time event handling");
            }
        });
        clock.borrow_mut().register_default_handler(callback);

        // Transition to Ready state
        strategy.initialize()?;

        // Register in both component and actor registries
        register_component_actor(strategy);

        let order_topic = get_event_orders_topic(strategy_id);
        let order_actor_id = actor_id;
        let order_handler = TypedHandler::from(move |event: &OrderEventAny| {
            if let Some(mut strategy) = try_get_actor_unchecked::<T>(&order_actor_id) {
                strategy.handle_order_event(event.clone());
            } else {
                log::error!("Strategy {order_actor_id} not found for order event handling");
            }
        });
        let order_handler_id = order_handler.id();
        msgbus::subscribe_order_events(order_topic.into(), order_handler, None);

        let position_topic = get_event_positions_topic(strategy_id);
        let position_handler = TypedHandler::from(move |event: &PositionEvent| {
            if let Some(mut strategy) = try_get_actor_unchecked::<T>(&actor_id) {
                strategy.handle_position_event(event.clone());
            } else {
                log::error!("Strategy {actor_id} not found for position event handling");
            }
        });
        let position_handler_id = position_handler.id();
        msgbus::subscribe_position_events(position_topic.into(), position_handler, None);

        self.strategy_ids.push(strategy_id);
        self.strategy_handler_ids
            .insert(strategy_id, (order_handler_id, position_handler_id));

        let stop_actor_id = actor_id;
        let stop_fn = Box::new(move || -> bool {
            if let Some(mut strategy) = try_get_actor_unchecked::<T>(&stop_actor_id) {
                Strategy::stop(&mut *strategy)
            } else {
                log::error!("Strategy {stop_actor_id} not found for stop");
                true // Proceed with component stop anyway
            }
        });
        self.strategy_stop_fns.insert(strategy_id, stop_fn);

        log::info!(
            "Registered strategy {strategy_id} with trader {}",
            self.trader_id
        );

        Ok(())
    }

    /// Adds an execution algorithm to the trader.
    ///
    /// Execution algorithms are registered in both the component registry (for lifecycle
    /// management) and the actor registry (for data callbacks via msgbus).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The trader is not in a valid state for adding components.
    /// - An execution algorithm with the same ID is already registered.
    pub fn add_exec_algorithm<T>(&mut self, mut exec_algorithm: T) -> anyhow::Result<()>
    where
        T: DataActor + Component + Debug + 'static,
    {
        self.validate_component_registration()?;

        let exec_algorithm_id =
            ExecAlgorithmId::from(exec_algorithm.component_id().inner().as_str());

        // Check for duplicate registration
        if self.exec_algorithm_ids.contains(&exec_algorithm_id) {
            anyhow::bail!("Execution algorithm '{exec_algorithm_id}' is already registered");
        }

        let clock = self.create_component_clock();
        let component_id = exec_algorithm.component_id();
        self.clocks.insert(component_id, clock.clone());

        exec_algorithm.register(self.trader_id, clock, self.cache.clone())?;

        // Register in both component and actor registries
        register_component_actor(exec_algorithm);

        self.exec_algorithm_ids.push(exec_algorithm_id);

        log::info!(
            "Registered execution algorithm {exec_algorithm_id} with trader {}",
            self.trader_id
        );

        Ok(())
    }

    /// Validates that the trader is in a valid state for component registration.
    fn validate_component_registration(&self) -> anyhow::Result<()> {
        match self.state {
            ComponentState::PreInitialized | ComponentState::Ready | ComponentState::Stopped => {
                Ok(())
            }
            ComponentState::Running => {
                anyhow::bail!("Cannot add components while trader is running")
            }
            ComponentState::Disposed => {
                anyhow::bail!("Cannot add components to disposed trader")
            }
            _ => anyhow::bail!("Cannot add components in current state: {}", self.state),
        }
    }

    /// Starts all registered components.
    ///
    /// # Errors
    ///
    /// Returns an error if any component fails to start.
    pub fn start_components(&mut self) -> anyhow::Result<()> {
        for actor_id in &self.actor_ids {
            log::debug!("Starting actor {actor_id}");
            start_component(&actor_id.inner())?;
        }

        for strategy_id in &self.strategy_ids {
            log::debug!("Starting strategy {strategy_id}");
            start_component(&strategy_id.inner())?;
        }

        for exec_algorithm_id in &self.exec_algorithm_ids {
            log::debug!("Starting execution algorithm {exec_algorithm_id}");
            start_component(&exec_algorithm_id.inner())?;
        }

        Ok(())
    }

    /// Stops all registered components.
    ///
    /// # Errors
    ///
    /// Returns an error if any component fails to stop.
    pub fn stop_components(&mut self) -> anyhow::Result<()> {
        for actor_id in &self.actor_ids {
            log::debug!("Stopping actor {actor_id}");
            stop_component(&actor_id.inner())?;
        }

        for exec_algorithm_id in &self.exec_algorithm_ids {
            log::debug!("Stopping execution algorithm {exec_algorithm_id}");
            stop_component(&exec_algorithm_id.inner())?;
        }

        for strategy_id in self.strategy_ids.clone() {
            log::debug!("Stopping strategy {strategy_id}");
            let should_proceed = self
                .strategy_stop_fns
                .get_mut(&strategy_id)
                .is_none_or(|stop_fn| stop_fn());
            if should_proceed {
                stop_component(&strategy_id.inner())?;
            }
        }

        Ok(())
    }

    /// Resets all registered components.
    ///
    /// # Errors
    ///
    /// Returns an error if any component fails to reset.
    pub fn reset_components(&mut self) -> anyhow::Result<()> {
        for actor_id in &self.actor_ids {
            log::debug!("Resetting actor {actor_id}");
            reset_component(&actor_id.inner())?;
        }

        for strategy_id in &self.strategy_ids {
            log::debug!("Resetting strategy {strategy_id}");
            reset_component(&strategy_id.inner())?;
        }

        for exec_algorithm_id in &self.exec_algorithm_ids {
            log::debug!("Resetting execution algorithm {exec_algorithm_id}");
            reset_component(&exec_algorithm_id.inner())?;
        }

        Ok(())
    }

    /// Disposes of all registered components.
    ///
    /// # Errors
    ///
    /// Returns an error if any component fails to dispose.
    pub fn dispose_components(&mut self) -> anyhow::Result<()> {
        for actor_id in &self.actor_ids {
            log::debug!("Disposing actor {actor_id}");
            dispose_component(&actor_id.inner())?;
        }

        for strategy_id in &self.strategy_ids {
            log::debug!("Disposing strategy {strategy_id}");
            dispose_component(&strategy_id.inner())?;
        }

        for exec_algorithm_id in &self.exec_algorithm_ids {
            log::debug!("Disposing execution algorithm {exec_algorithm_id}");
            dispose_component(&exec_algorithm_id.inner())?;
        }

        self.actor_ids.clear();
        self.strategy_ids.clear();
        self.exec_algorithm_ids.clear();
        self.clocks.clear();

        Ok(())
    }

    /// Clears all registered strategies, disposing each and removing their clocks.
    ///
    /// # Errors
    ///
    /// Returns an error if any strategy fails to dispose.
    pub fn clear_strategies(&mut self) -> anyhow::Result<()> {
        for strategy_id in &self.strategy_ids {
            log::debug!("Disposing strategy {strategy_id}");
            dispose_component(&strategy_id.inner())?;
            let component_id = ComponentId::new(strategy_id.inner().as_str());
            self.clocks.remove(&component_id);

            // Remove only this strategy's own msgbus handlers
            if let Some((order_hid, position_hid)) = self.strategy_handler_ids.get(strategy_id) {
                let order_topic = get_event_orders_topic(*strategy_id);
                let position_topic = get_event_positions_topic(*strategy_id);
                msgbus::remove_order_event_handler(order_topic.into(), *order_hid);
                msgbus::remove_position_event_handler(position_topic.into(), *position_hid);
            }
        }

        self.strategy_ids.clear();
        self.strategy_stop_fns.clear();
        self.strategy_handler_ids.clear();

        Ok(())
    }

    /// Clears all registered execution algorithms, disposing each and removing their clocks.
    ///
    /// # Errors
    ///
    /// Returns an error if any execution algorithm fails to dispose.
    pub fn clear_exec_algorithms(&mut self) -> anyhow::Result<()> {
        for exec_algorithm_id in &self.exec_algorithm_ids {
            log::debug!("Disposing execution algorithm {exec_algorithm_id}");
            dispose_component(&exec_algorithm_id.inner())?;
            let component_id = ComponentId::new(exec_algorithm_id.inner().as_str());
            self.clocks.remove(&component_id);
        }

        self.exec_algorithm_ids.clear();

        Ok(())
    }

    /// Initializes the trader, transitioning from `PreInitialized` to `Ready` state.
    ///
    /// This method must be called before starting the trader.
    ///
    /// # Errors
    ///
    /// Returns an error if the trader cannot be initialized from its current state.
    pub fn initialize(&mut self) -> anyhow::Result<()> {
        let new_state = self.state.transition(&ComponentTrigger::Initialize)?;
        self.state = new_state;

        Ok(())
    }

    fn on_start(&mut self) -> anyhow::Result<()> {
        self.start_components()?;

        // Transition to running state
        self.ts_started = Some(self.clock.borrow().timestamp_ns());

        Ok(())
    }

    fn on_stop(&mut self) -> anyhow::Result<()> {
        self.stop_components()?;

        self.ts_stopped = Some(self.clock.borrow().timestamp_ns());

        Ok(())
    }

    fn on_reset(&mut self) -> anyhow::Result<()> {
        self.reset_components()?;

        self.ts_started = None;
        self.ts_stopped = None;

        Ok(())
    }

    fn on_dispose(&mut self) -> anyhow::Result<()> {
        if self.is_running() {
            self.stop()?;
        }

        self.dispose_components()?;

        Ok(())
    }
}

impl Component for Trader {
    fn component_id(&self) -> ComponentId {
        ComponentId::new(format!("Trader-{}", self.trader_id))
    }

    fn state(&self) -> ComponentState {
        self.state
    }

    fn transition_state(&mut self, trigger: ComponentTrigger) -> anyhow::Result<()> {
        self.state = self.state.transition(&trigger)?;
        log::info!("{}", self.state.variant_name());
        Ok(())
    }

    fn register(
        &mut self,
        _trader_id: TraderId,
        _clock: Rc<RefCell<dyn Clock>>,
        _cache: Rc<RefCell<Cache>>,
    ) -> anyhow::Result<()> {
        anyhow::bail!("Trader cannot register with itself")
    }

    fn on_start(&mut self) -> anyhow::Result<()> {
        Self::on_start(self)
    }

    fn on_stop(&mut self) -> anyhow::Result<()> {
        Self::on_stop(self)
    }

    fn on_reset(&mut self) -> anyhow::Result<()> {
        Self::on_reset(self)
    }

    fn on_dispose(&mut self) -> anyhow::Result<()> {
        Self::on_dispose(self)
    }
}

#[cfg(test)]
mod tests {
    use std::{
        cell::RefCell,
        ops::{Deref, DerefMut},
        rc::Rc,
    };

    use nautilus_common::{
        actor::{DataActorCore, data_actor::DataActorConfig},
        cache::Cache,
        clock::TestClock,
        enums::{ComponentState, Environment},
        msgbus,
        msgbus::{MessageBus, TypedHandler, switchboard::get_event_orders_topic},
    };
    use nautilus_core::UUID4;
    use nautilus_data::engine::{DataEngine, config::DataEngineConfig};
    use nautilus_execution::engine::{ExecutionEngine, config::ExecutionEngineConfig};
    use nautilus_model::{
        events::OrderAccepted,
        identifiers::{ActorId, ComponentId, TraderId},
        stubs::TestDefault,
    };
    use nautilus_portfolio::portfolio::Portfolio;
    use nautilus_risk::engine::{RiskEngine, config::RiskEngineConfig};
    use nautilus_trading::strategy::{
        Strategy as StrategyTrait, config::StrategyConfig, core::StrategyCore,
    };
    use rstest::rstest;

    use super::*;

    // Simple DataActor wrapper for testing
    #[derive(Debug)]
    struct TestDataActor {
        core: DataActorCore,
    }

    impl TestDataActor {
        fn new(config: DataActorConfig) -> Self {
            Self {
                core: DataActorCore::new(config),
            }
        }
    }

    impl DataActor for TestDataActor {}

    impl Deref for TestDataActor {
        type Target = DataActorCore;
        fn deref(&self) -> &Self::Target {
            &self.core
        }
    }

    impl DerefMut for TestDataActor {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.core
        }
    }

    // Simple Strategy wrapper for testing
    #[derive(Debug)]
    struct TestStrategy {
        core: StrategyCore,
    }

    impl TestStrategy {
        fn new(config: StrategyConfig) -> Self {
            Self {
                core: StrategyCore::new(config),
            }
        }
    }

    impl DataActor for TestStrategy {}

    impl Deref for TestStrategy {
        type Target = DataActorCore;
        fn deref(&self) -> &Self::Target {
            &self.core
        }
    }

    impl DerefMut for TestStrategy {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.core
        }
    }

    impl StrategyTrait for TestStrategy {
        fn core(&self) -> &StrategyCore {
            &self.core
        }

        fn core_mut(&mut self) -> &mut StrategyCore {
            &mut self.core
        }
    }

    #[allow(clippy::type_complexity)]
    fn create_trader_components() -> (
        Rc<RefCell<MessageBus>>,
        Rc<RefCell<Cache>>,
        Rc<RefCell<Portfolio>>,
        Rc<RefCell<DataEngine>>,
        Rc<RefCell<RiskEngine>>,
        Rc<RefCell<ExecutionEngine>>,
        Rc<RefCell<TestClock>>,
    ) {
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();
        let clock = Rc::new(RefCell::new(TestClock::new()));
        // Set the clock to a non-zero time for test purposes
        clock.borrow_mut().set_time(1_000_000_000u64.into());
        let msgbus = Rc::new(RefCell::new(MessageBus::new(
            trader_id,
            instance_id,
            Some("test".to_string()),
            None,
        )));
        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
        let portfolio = Rc::new(RefCell::new(Portfolio::new(
            cache.clone(),
            clock.clone() as Rc<RefCell<dyn Clock>>,
            None,
        )));
        let data_engine = Rc::new(RefCell::new(DataEngine::new(
            clock.clone(),
            cache.clone(),
            Some(DataEngineConfig::default()),
        )));

        // Create separate cache and clock instances for RiskEngine to avoid borrowing conflicts
        let risk_cache = Rc::new(RefCell::new(Cache::new(None, None)));
        let risk_clock = Rc::new(RefCell::new(TestClock::new()));
        let risk_portfolio = Portfolio::new(
            risk_cache.clone(),
            risk_clock.clone() as Rc<RefCell<dyn Clock>>,
            None,
        );
        let risk_engine = Rc::new(RefCell::new(RiskEngine::new(
            RiskEngineConfig::default(),
            risk_portfolio,
            risk_clock as Rc<RefCell<dyn Clock>>,
            risk_cache,
        )));
        let exec_engine = Rc::new(RefCell::new(ExecutionEngine::new(
            clock.clone(),
            cache.clone(),
            Some(ExecutionEngineConfig::default()),
        )));

        (
            msgbus,
            cache,
            portfolio,
            data_engine,
            risk_engine,
            exec_engine,
            clock,
        )
    }

    #[rstest]
    fn test_trader_creation() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        let trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        assert_eq!(trader.trader_id(), trader_id);
        assert_eq!(trader.instance_id(), instance_id);
        assert_eq!(trader.environment(), Environment::Backtest);
        assert_eq!(trader.state(), ComponentState::PreInitialized);
        assert_eq!(trader.actor_count(), 0);
        assert_eq!(trader.strategy_count(), 0);
        assert_eq!(trader.exec_algorithm_count(), 0);
        assert_eq!(trader.component_count(), 0);
        assert!(!trader.is_running());
        assert!(!trader.is_stopped());
        assert!(!trader.is_disposed());
        assert!(trader.ts_created() > 0);
        assert!(trader.ts_started().is_none());
        assert!(trader.ts_stopped().is_none());
    }

    #[rstest]
    fn test_trader_component_id() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::from("TRADER-001");
        let instance_id = UUID4::new();

        let trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        assert_eq!(
            trader.component_id(),
            ComponentId::from("Trader-TRADER-001")
        );
    }

    #[rstest]
    fn test_add_actor_success() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        let mut trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        let actor = TestDataActor::new(DataActorConfig::default());
        let actor_id = actor.actor_id();

        let result = trader.add_actor(actor);
        assert!(result.is_ok());
        assert_eq!(trader.actor_count(), 1);
        assert_eq!(trader.component_count(), 1);
        assert!(trader.actor_ids().contains(&actor_id));
    }

    #[rstest]
    fn test_add_duplicate_actor_fails() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        let mut trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        let config = DataActorConfig {
            actor_id: Some(ActorId::from("TestActor")),
            ..Default::default()
        };
        let actor1 = TestDataActor::new(config.clone());
        let actor2 = TestDataActor::new(config);

        // First addition should succeed
        assert!(trader.add_actor(actor1).is_ok());
        assert_eq!(trader.actor_count(), 1);

        // Second addition should fail
        let result = trader.add_actor(actor2);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("already registered")
        );
        assert_eq!(trader.actor_count(), 1);
    }

    #[rstest]
    fn test_add_strategy_success() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        let mut trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        let config = StrategyConfig {
            strategy_id: Some(StrategyId::from("Test-Strategy")),
            ..Default::default()
        };
        let strategy = TestStrategy::new(config);
        let strategy_id = StrategyId::from(strategy.actor_id().inner().as_str());

        let result = trader.add_strategy(strategy);
        assert!(result.is_ok());
        assert_eq!(trader.strategy_count(), 1);
        assert_eq!(trader.component_count(), 1);
        assert!(trader.strategy_ids().contains(&strategy_id));
    }

    #[rstest]
    fn test_add_exec_algorithm_success() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        let mut trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        let config = DataActorConfig {
            actor_id: Some(ActorId::from("TestExecAlgorithm")),
            ..Default::default()
        };
        let exec_algorithm = TestDataActor::new(config);
        let exec_algorithm_id = ExecAlgorithmId::from(exec_algorithm.actor_id().inner().as_str());

        let result = trader.add_exec_algorithm(exec_algorithm);
        assert!(result.is_ok());
        assert_eq!(trader.exec_algorithm_count(), 1);
        assert_eq!(trader.component_count(), 1);
        assert!(trader.exec_algorithm_ids().contains(&exec_algorithm_id));
    }

    #[rstest]
    fn test_component_lifecycle() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        let mut trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        // Add components
        let actor = TestDataActor::new(DataActorConfig::default());

        let strategy_config = StrategyConfig {
            strategy_id: Some(StrategyId::from("Test-Strategy")),
            ..Default::default()
        };
        let strategy = TestStrategy::new(strategy_config);

        let exec_algorithm_config = DataActorConfig {
            actor_id: Some(ActorId::from("TestExecAlgorithm")),
            ..Default::default()
        };
        let exec_algorithm = TestDataActor::new(exec_algorithm_config);

        assert!(trader.add_actor(actor).is_ok());
        assert!(trader.add_strategy(strategy).is_ok());
        assert!(trader.add_exec_algorithm(exec_algorithm).is_ok());
        assert_eq!(trader.component_count(), 3);

        // Test start components
        let start_result = trader.start_components();
        assert!(start_result.is_ok(), "{:?}", start_result.unwrap_err());

        // Test stop components
        assert!(trader.stop_components().is_ok());

        // Test reset components
        assert!(trader.reset_components().is_ok());

        // Test dispose components
        assert!(trader.dispose_components().is_ok());
        assert_eq!(trader.component_count(), 0);
    }

    #[rstest]
    fn test_trader_component_lifecycle() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        let mut trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        // Initially pre-initialized
        assert_eq!(trader.state(), ComponentState::PreInitialized);
        assert!(!trader.is_running());
        assert!(!trader.is_stopped());
        assert!(!trader.is_disposed());

        // Cannot start from pre-initialized state
        assert!(trader.start().is_err());

        // Simulate initialization (normally done by kernel)
        trader.initialize().unwrap();

        // Test start
        assert!(trader.start().is_ok());
        assert_eq!(trader.state(), ComponentState::Running);
        assert!(trader.is_running());
        assert!(trader.ts_started().is_some());

        // Test stop
        assert!(trader.stop().is_ok());
        assert_eq!(trader.state(), ComponentState::Stopped);
        assert!(trader.is_stopped());
        assert!(trader.ts_stopped().is_some());

        // Test reset
        assert!(trader.reset().is_ok());
        assert_eq!(trader.state(), ComponentState::Ready);
        assert!(trader.ts_started().is_none());
        assert!(trader.ts_stopped().is_none());

        // Test dispose
        assert!(trader.dispose().is_ok());
        assert_eq!(trader.state(), ComponentState::Disposed);
        assert!(trader.is_disposed());
    }

    #[rstest]
    fn test_cannot_add_components_while_running() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        let mut trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        // Simulate running state
        trader.state = ComponentState::Running;

        let actor = TestDataActor::new(DataActorConfig::default());
        let result = trader.add_actor(actor);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("while trader is running")
        );
    }

    #[rstest]
    fn test_create_component_clock_backtest_vs_live() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        // Test backtest environment - should create individual test clocks
        let trader_backtest = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock.clone(),
            cache.clone(),
            portfolio.clone(),
        );

        let backtest_clock = trader_backtest.create_component_clock();
        // In backtest, component clock should be different from system clock
        assert_ne!(
            backtest_clock.as_ptr() as *const _,
            clock.as_ptr() as *const _
        );

        // Test live environment - should share system clock
        let trader_live = Trader::new(
            trader_id,
            instance_id,
            Environment::Live,
            clock.clone(),
            cache,
            portfolio,
        );

        let live_clock = trader_live.create_component_clock();
        // In live, component clock should be same as system clock
        assert_eq!(live_clock.as_ptr() as *const _, clock.as_ptr() as *const _);
    }

    #[rstest]
    fn test_clear_strategies_preserves_other_handlers() {
        let (_msgbus, cache, portfolio, _data_engine, _risk_engine, _exec_engine, clock) =
            create_trader_components();
        let trader_id = TraderId::test_default();
        let instance_id = UUID4::new();

        let mut trader = Trader::new(
            trader_id,
            instance_id,
            Environment::Backtest,
            clock,
            cache,
            portfolio,
        );

        let config = StrategyConfig {
            strategy_id: Some(StrategyId::from("Test-Strategy")),
            ..Default::default()
        };
        let strategy = TestStrategy::new(config);
        let strategy_id = StrategyId::from(strategy.actor_id().inner().as_str());
        trader.add_strategy(strategy).unwrap();

        // Simulate an exec algorithm subscribing to the same strategy topic
        let ext_received = Rc::new(RefCell::new(0));
        let ext_clone = ext_received.clone();
        let ext_handler =
            TypedHandler::from_with_id("exec-algo-handler", move |_: &OrderEventAny| {
                *ext_clone.borrow_mut() += 1;
            });
        let order_topic = get_event_orders_topic(strategy_id);
        msgbus::subscribe_order_events(order_topic.into(), ext_handler, None);

        trader.clear_strategies().unwrap();
        assert_eq!(trader.strategy_count(), 0);

        let event = OrderEventAny::Accepted(OrderAccepted::test_default());
        msgbus::publish_order_event(order_topic, &event);
        assert_eq!(*ext_received.borrow(), 1);
    }
}