Skip to main content

nautilus_trading/strategy/
core.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
16use std::{
17    cell::{Ref, RefCell, RefMut},
18    fmt::Debug,
19    rc::Rc,
20};
21
22use ahash::AHashMap;
23use nautilus_common::{
24    actor::{DataActorConfig, DataActorCore, DataActorNative},
25    cache::Cache,
26    clock::Clock,
27    factories::OrderFactory,
28};
29use nautilus_core::{
30    UUID4,
31    correctness::{CorrectnessResult, CorrectnessResultExt, FAILED},
32};
33use nautilus_execution::order_manager::manager::OrderManager;
34use nautilus_model::identifiers::{
35    ActorId, ClientOrderId, StrategyId, TraderId, UNASSIGNED_ORDER_ID_TAG, check_order_id_tag,
36    normalize_order_id_tag,
37};
38use nautilus_portfolio::portfolio::Portfolio;
39use ustr::Ustr;
40
41use super::{
42    api::{OrderApi, PortfolioApi},
43    config::StrategyConfig,
44};
45
46/// The core component of a [`Strategy`](crate::strategy::Strategy), managing data, orders,
47/// and state.
48///
49/// This struct is intended to be held as a member within a user's custom strategy struct.
50/// Use the `nautilus_strategy!` macro to provide the trait accessors required by
51/// [`Strategy`](crate::strategy::Strategy), [`StrategyNative`], and
52/// [`DataActor`](nautilus_common::actor::DataActor). It does not deref to
53/// [`DataActorCore`]; normal strategy logic should use facade methods on the
54/// strategy value.
55pub struct StrategyCore {
56    pub(crate) actor: DataActorCore,
57    /// The strategy configuration.
58    pub config: StrategyConfig,
59    strategy_id: Option<StrategyId>,
60    order_id_tag: Option<String>,
61    pub(crate) order_manager: Option<OrderManager>,
62    pub(crate) order_factory: Option<Rc<RefCell<OrderFactory>>>,
63    pub(crate) portfolio: Option<Rc<RefCell<Portfolio>>>,
64    pub(crate) gtd_timers: AHashMap<ClientOrderId, Ustr>,
65    pub(crate) managed_time_event_last_id: Option<UUID4>,
66    pub(crate) is_exiting: bool,
67    pub(crate) pending_stop: bool,
68    pub(crate) market_exit_attempts: u64,
69    pub(crate) market_exit_timer_name: Ustr,
70    pub(crate) market_exit_tag: Ustr,
71}
72
73impl Debug for StrategyCore {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        f.debug_struct(stringify!(StrategyCore))
76            .field("actor", &self.actor)
77            .field("config", &self.config)
78            .field("strategy_id", &self.strategy_id)
79            .field("order_id_tag", &self.order_id_tag)
80            .field("order_manager", &self.order_manager)
81            .field("order_factory", &self.order_factory)
82            .field("is_exiting", &self.is_exiting)
83            .field("pending_stop", &self.pending_stop)
84            .field("market_exit_attempts", &self.market_exit_attempts)
85            .finish()
86    }
87}
88
89/// Native-only access to internal strategy runtime state.
90///
91/// Use this trait from engine, runtime, testkit, or opt-in native strategy
92/// code when direct access to host runtime objects matters for an explicit
93/// latency-sensitive path, or when host integration code needs access below
94/// the facade API.
95///
96/// Do not import this trait in strategy code intended to run through Python or
97/// the plug-in authoring surface. Those surfaces should use facade methods such
98/// as `order()` and `portfolio()`, because native borrows, `Rc<RefCell<_>>`, and
99/// core references do not cross those boundaries.
100pub trait StrategyNative {
101    /// Returns the strategy core.
102    fn strategy_core(&self) -> &StrategyCore;
103
104    /// Returns the mutable strategy core.
105    fn strategy_core_mut(&mut self) -> &mut StrategyCore;
106
107    /// Returns a mutable borrow of the order factory.
108    ///
109    /// # Panics
110    ///
111    /// Panics if the strategy has not been registered.
112    fn order_factory(&mut self) -> RefMut<'_, OrderFactory> {
113        self.strategy_core_mut()
114            .order_factory
115            .as_ref()
116            .expect("Strategy not registered: OrderFactory not initialized")
117            .borrow_mut()
118    }
119
120    /// Returns a clone of the reference-counted order factory.
121    ///
122    /// # Panics
123    ///
124    /// Panics if the strategy has not been registered.
125    fn order_factory_rc(&self) -> Rc<RefCell<OrderFactory>> {
126        self.strategy_core()
127            .order_factory
128            .as_ref()
129            .expect("Strategy not registered: OrderFactory not initialized")
130            .clone()
131    }
132
133    /// Returns a clone of the reference-counted portfolio.
134    ///
135    /// # Panics
136    ///
137    /// Panics if the strategy has not been registered.
138    fn portfolio_rc(&self) -> Rc<RefCell<Portfolio>> {
139        self.strategy_core()
140            .portfolio
141            .as_ref()
142            .expect("Strategy not registered: Portfolio not initialized")
143            .clone()
144    }
145}
146
147impl StrategyCore {
148    /// Creates a new [`StrategyCore`] instance with correctness checking.
149    ///
150    /// # Errors
151    ///
152    /// Returns an error if the configured order ID tag contains the '-' strategy ID separator,
153    /// or if composing it into the strategy ID does not produce a valid [`StrategyId`].
154    pub fn new_checked(config: StrategyConfig) -> CorrectnessResult<Self> {
155        if let Some(order_id_tag) = config.order_id_tag.as_deref() {
156            check_order_id_tag(order_id_tag)?;
157        }
158
159        let configured_strategy_id = config.strategy_id;
160        let configured_order_id_tag = normalize_order_id_tag(config.order_id_tag.as_deref());
161        let strategy_id = configured_strategy_id
162            .map(|id| strategy_id_with_order_id_tag(id, configured_order_id_tag))
163            .transpose()?;
164        let order_id_tag = strategy_id
165            .map(|id| id.get_tag().to_string())
166            .or_else(|| configured_order_id_tag.map(str::to_string));
167
168        let actor_config = DataActorConfig {
169            actor_id: Some(
170                strategy_id
171                    .map_or_else(unassigned_strategy_actor_id, |id| ActorId::new(id.inner())),
172            ),
173            log_events: config.log_events,
174            log_commands: config.log_commands,
175        };
176
177        let strategy_id_str = strategy_id.map_or_default(|id| id.inner().to_string());
178        let market_exit_timer_name = Ustr::from(&format!("MARKET_EXIT_CHECK:{strategy_id_str}"));
179
180        Ok(Self {
181            actor: DataActorCore::new(actor_config),
182            config,
183            strategy_id,
184            order_id_tag,
185            order_manager: None,
186            order_factory: None,
187            portfolio: None,
188            gtd_timers: AHashMap::new(),
189            managed_time_event_last_id: None,
190            is_exiting: false,
191            pending_stop: false,
192            market_exit_attempts: 0,
193            market_exit_timer_name,
194            market_exit_tag: Ustr::from("MARKET_EXIT"),
195        })
196    }
197
198    /// Creates a new [`StrategyCore`] instance.
199    ///
200    /// # Panics
201    ///
202    /// Panics if the configured order ID tag contains the '-' strategy ID separator,
203    /// or if composing it into the strategy ID does not produce a valid [`StrategyId`].
204    #[must_use]
205    pub fn new(config: StrategyConfig) -> Self {
206        Self::new_checked(config).expect_display(FAILED)
207    }
208
209    /// Returns the strategy configuration.
210    #[must_use]
211    pub fn config(&self) -> &StrategyConfig {
212        &self.config
213    }
214
215    /// Changes the strategy ID before registration.
216    ///
217    /// # Errors
218    ///
219    /// Returns an error if composing the current order ID tag into `strategy_id` does not
220    /// produce a valid [`StrategyId`].
221    pub fn change_id(&mut self, strategy_id: StrategyId) -> anyhow::Result<()> {
222        let strategy_id = strategy_id_with_order_id_tag(strategy_id, self.order_id_tag())?;
223        self.set_runtime_strategy_id(strategy_id);
224        Ok(())
225    }
226
227    /// Changes the order ID tag before registration.
228    ///
229    /// # Errors
230    ///
231    /// Returns an error if `order_id_tag` contains the '-' strategy ID separator, or if
232    /// composing it into the current strategy ID does not produce a valid [`StrategyId`].
233    pub fn change_order_id_tag(&mut self, order_id_tag: &str) -> anyhow::Result<()> {
234        check_order_id_tag(order_id_tag)?;
235
236        let normalized_order_id_tag =
237            normalize_order_id_tag(Some(order_id_tag)).map(str::to_string);
238
239        if let Some(strategy_id) = self.strategy_id
240            && let Some(order_id_tag) = normalized_order_id_tag.as_deref()
241        {
242            let strategy_id = strategy_id_with_order_id_tag(strategy_id, Some(order_id_tag))?;
243            self.set_runtime_strategy_id(strategy_id);
244        } else {
245            self.order_id_tag = normalized_order_id_tag;
246        }
247
248        Ok(())
249    }
250
251    fn set_runtime_strategy_id(&mut self, strategy_id: StrategyId) {
252        let actor_id = ActorId::new(strategy_id.inner());
253        self.actor.actor_id = actor_id;
254        self.actor.config.actor_id = Some(actor_id);
255        self.strategy_id = Some(strategy_id);
256        self.order_id_tag = Some(strategy_id.get_tag().to_string());
257        self.market_exit_timer_name = Ustr::from(&format!("MARKET_EXIT_CHECK:{strategy_id}"));
258    }
259
260    /// Returns the runtime order ID tag.
261    #[must_use]
262    pub fn order_id_tag(&self) -> Option<&str> {
263        self.order_id_tag.as_deref()
264    }
265
266    /// Returns the runtime strategy ID.
267    #[must_use]
268    pub fn strategy_id(&self) -> Option<StrategyId> {
269        self.strategy_id
270    }
271
272    /// Registers the strategy with the trading engine components.
273    ///
274    /// This is typically called by the framework when the strategy is added to an engine.
275    ///
276    /// # Errors
277    ///
278    /// Returns an error if the configured order ID tag contains the '-' strategy ID separator,
279    /// or if registration with the actor core fails.
280    pub fn register(
281        &mut self,
282        trader_id: TraderId,
283        clock: Rc<RefCell<dyn Clock>>,
284        cache: Rc<RefCell<Cache>>,
285        portfolio: Rc<RefCell<Portfolio>>,
286    ) -> anyhow::Result<()> {
287        // Guards a config built without `StrategyConfig::validate`, such as a struct literal
288        if let Some(order_id_tag) = self.config.order_id_tag.as_deref() {
289            check_order_id_tag(order_id_tag)?;
290        }
291
292        let strategy_id = StrategyId::new(self.actor.actor_id.inner());
293
294        self.actor
295            .register(trader_id, clock.clone(), cache.clone())?;
296
297        // Update market exit timer name with actual strategy ID
298        self.market_exit_timer_name = Ustr::from(&format!("MARKET_EXIT_CHECK:{strategy_id}"));
299
300        self.strategy_id = Some(strategy_id);
301        self.order_id_tag = Some(strategy_id.get_tag().to_string());
302
303        self.order_factory = Some(Rc::new(RefCell::new(OrderFactory::new(
304            trader_id,
305            strategy_id,
306            None,
307            None,
308            clock.clone(),
309            self.config.use_uuid_client_order_ids,
310            self.config.use_hyphens_in_client_order_ids,
311        ))));
312
313        self.order_manager = Some(OrderManager::new(clock, cache, false));
314
315        self.portfolio = Some(portfolio);
316
317        Ok(())
318    }
319
320    /// Returns the user-facing order creation API.
321    ///
322    /// # Panics
323    ///
324    /// Panics if the strategy has not been registered.
325    #[must_use]
326    pub fn order(&self) -> OrderApi<'_> {
327        let order_factory = self
328            .order_factory
329            .as_ref()
330            .expect("Strategy not registered: OrderFactory not initialized");
331        OrderApi::new(order_factory.as_ref())
332    }
333
334    /// Returns the user-facing portfolio read API.
335    ///
336    /// # Panics
337    ///
338    /// Panics if the strategy has not been registered.
339    #[must_use]
340    pub(crate) fn portfolio_api(&self) -> PortfolioApi<'_> {
341        let portfolio = self
342            .portfolio
343            .as_ref()
344            .expect("Strategy not registered: Portfolio not initialized");
345        PortfolioApi::new(portfolio.as_ref())
346    }
347
348    pub(crate) fn actor_id(&self) -> ActorId {
349        self.actor.actor_id()
350    }
351
352    pub(crate) fn trader_id(&self) -> Option<TraderId> {
353        self.actor.trader_id()
354    }
355
356    pub(crate) fn clock_mut(&mut self) -> RefMut<'_, dyn Clock> {
357        DataActorNative::clock_mut(self)
358    }
359
360    pub(crate) fn cache_ref(&self) -> Ref<'_, Cache> {
361        DataActorNative::cache_ref(self)
362    }
363
364    pub(crate) fn cache_rc(&self) -> Rc<RefCell<Cache>> {
365        DataActorNative::cache_rc(self)
366    }
367
368    /// Resets the market exit state.
369    pub fn reset_market_exit_state(&mut self) {
370        self.is_exiting = false;
371        self.pending_stop = false;
372        self.market_exit_attempts = 0;
373    }
374}
375
376impl DataActorNative for StrategyCore {
377    fn core(&self) -> &DataActorCore {
378        &self.actor
379    }
380
381    fn core_mut(&mut self) -> &mut DataActorCore {
382        &mut self.actor
383    }
384}
385
386impl StrategyNative for StrategyCore {
387    fn strategy_core(&self) -> &StrategyCore {
388        self
389    }
390
391    fn strategy_core_mut(&mut self) -> &mut StrategyCore {
392        self
393    }
394}
395
396/// Returns the component identity for a strategy without a configured ID.
397///
398/// Registration replaces this with the class-derived ID and the assigned order ID tag. The
399/// unassigned tag keeps the identity convertible to a [`StrategyId`] until then.
400fn unassigned_strategy_actor_id() -> ActorId {
401    ActorId::from(format!(
402        "{}-{UNASSIGNED_ORDER_ID_TAG}",
403        stringify!(Strategy)
404    ))
405}
406
407fn strategy_id_with_order_id_tag(
408    strategy_id: StrategyId,
409    order_id_tag: Option<&str>,
410) -> CorrectnessResult<StrategyId> {
411    let Some(order_id_tag) = normalize_order_id_tag(order_id_tag) else {
412        return Ok(strategy_id);
413    };
414
415    if strategy_id.get_tag() == order_id_tag {
416        Ok(strategy_id)
417    } else {
418        StrategyId::new_checked(format!("{strategy_id}-{order_id_tag}"))
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use std::{cell::RefCell, rc::Rc};
425
426    use nautilus_common::{cache::Cache, clock::VirtualClock};
427    use nautilus_core::UnixNanos;
428    use nautilus_model::{
429        enums::{OrderSide, OrderType, TimeInForce, TrailingOffsetType, TriggerType},
430        identifiers::{AccountId, InstrumentId, StrategyId, TraderId},
431        orders::Order,
432        types::{Price, Quantity},
433    };
434    use nautilus_portfolio::portfolio::Portfolio;
435    use rstest::rstest;
436    use rust_decimal::Decimal;
437
438    use super::*;
439
440    fn create_test_config() -> StrategyConfig {
441        StrategyConfig {
442            strategy_id: Some(StrategyId::from("TEST-001")),
443            order_id_tag: Some("001".to_string()),
444            ..Default::default()
445        }
446    }
447
448    #[rstest]
449    fn test_strategy_core_new() {
450        let config = create_test_config();
451        let core = StrategyCore::new(config.clone());
452
453        assert_eq!(core.config.strategy_id, config.strategy_id);
454        assert_eq!(core.config.order_id_tag, config.order_id_tag);
455        assert_eq!(core.strategy_id(), config.strategy_id);
456        assert_eq!(core.order_id_tag(), Some("001"));
457        assert!(core.order_manager.is_none());
458        assert!(core.order_factory.is_none());
459        assert!(core.portfolio.is_none());
460        assert!(!core.is_exiting);
461        assert!(!core.pending_stop);
462        assert_eq!(core.market_exit_attempts, 0);
463    }
464
465    #[rstest]
466    fn test_strategy_core_new_without_configured_id_uses_the_unassigned_actor_id() {
467        let core = StrategyCore::new(StrategyConfig::default());
468
469        assert_eq!(core.actor_id(), ActorId::from("Strategy-None"));
470        assert_eq!(core.strategy_id(), None);
471        assert_eq!(core.order_id_tag(), None);
472        assert_eq!(
473            StrategyId::new(core.actor_id().inner()),
474            StrategyId::from("Strategy-None")
475        );
476    }
477
478    #[rstest]
479    fn test_strategy_core_new_applies_explicit_order_id_tag_to_strategy_id() {
480        let config = StrategyConfig {
481            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
482            order_id_tag: Some("T01".to_string()),
483            ..Default::default()
484        };
485
486        let core = StrategyCore::new(config.clone());
487
488        assert_eq!(core.actor_id(), ActorId::from("ExampleStrategy-XNAS-T01"));
489        assert_eq!(core.config.strategy_id, config.strategy_id);
490        assert_eq!(core.config.order_id_tag, config.order_id_tag);
491        assert_eq!(
492            core.strategy_id(),
493            Some(StrategyId::from("ExampleStrategy-XNAS-T01"))
494        );
495        assert_eq!(core.order_id_tag(), Some("T01"));
496    }
497
498    #[rstest]
499    fn test_strategy_core_new_uses_strategy_tag_when_order_id_tag_is_omitted() {
500        let config = StrategyConfig {
501            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
502            ..Default::default()
503        };
504
505        let core = StrategyCore::new(config.clone());
506
507        assert_eq!(core.actor_id(), ActorId::from("ExampleStrategy-XNAS"));
508        assert_eq!(core.config.strategy_id, config.strategy_id);
509        assert_eq!(core.config.order_id_tag, None);
510        assert_eq!(core.strategy_id(), config.strategy_id);
511        assert_eq!(core.order_id_tag(), Some("XNAS"));
512    }
513
514    #[rstest]
515    fn test_strategy_core_change_id_appends_existing_order_id_tag() {
516        let config = StrategyConfig {
517            order_id_tag: Some("T01".to_string()),
518            ..Default::default()
519        };
520        let mut core = StrategyCore::new(config);
521
522        core.change_id(StrategyId::from("ExampleStrategy-XNAS"))
523            .unwrap();
524
525        assert_eq!(core.actor_id(), ActorId::from("ExampleStrategy-XNAS-T01"));
526        assert_eq!(
527            core.strategy_id(),
528            Some(StrategyId::from("ExampleStrategy-XNAS-T01"))
529        );
530        assert_eq!(core.order_id_tag(), Some("T01"));
531    }
532
533    #[rstest]
534    fn test_strategy_core_change_order_id_tag_appends_to_existing_strategy_id() {
535        let config = StrategyConfig {
536            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
537            ..Default::default()
538        };
539        let mut core = StrategyCore::new(config);
540
541        core.change_order_id_tag("T01").unwrap();
542
543        assert_eq!(core.actor_id(), ActorId::from("ExampleStrategy-XNAS-T01"));
544        assert_eq!(
545            core.strategy_id(),
546            Some(StrategyId::from("ExampleStrategy-XNAS-T01"))
547        );
548        assert_eq!(core.order_id_tag(), Some("T01"));
549    }
550
551    #[rstest]
552    fn test_strategy_core_change_order_id_tag_does_not_duplicate_matching_tag() {
553        let config = StrategyConfig {
554            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS-T01")),
555            ..Default::default()
556        };
557        let mut core = StrategyCore::new(config);
558
559        core.change_order_id_tag("T01").unwrap();
560
561        assert_eq!(core.actor_id(), ActorId::from("ExampleStrategy-XNAS-T01"));
562        assert_eq!(
563            core.strategy_id(),
564            Some(StrategyId::from("ExampleStrategy-XNAS-T01"))
565        );
566        assert_eq!(core.order_id_tag(), Some("T01"));
567    }
568
569    #[rstest]
570    fn test_strategy_core_new_checked_rejects_order_id_tag_with_separator() {
571        let config = StrategyConfig {
572            strategy_id: Some(StrategyId::from("HyphenTagStrategy-A-B")),
573            order_id_tag: Some("A-B".to_string()),
574            ..Default::default()
575        };
576
577        let error = StrategyCore::new_checked(config).unwrap_err();
578
579        assert_eq!(
580            error.to_string(),
581            "`order_id_tag` cannot contain the '-' strategy ID separator, was 'A-B'"
582        );
583    }
584
585    #[rstest]
586    #[case(Some("001".to_string()))]
587    #[case(Some("None".to_string()))]
588    #[case(Some(String::new()))]
589    #[case(None)]
590    fn test_strategy_core_new_checked_accepts_usable_order_id_tag(
591        #[case] order_id_tag: Option<String>,
592    ) {
593        let config = StrategyConfig {
594            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
595            order_id_tag,
596            ..Default::default()
597        };
598
599        assert!(StrategyCore::new_checked(config).is_ok());
600    }
601
602    #[rstest]
603    #[should_panic(expected = "`order_id_tag` cannot contain the '-' strategy ID separator")]
604    fn test_strategy_core_new_panics_on_order_id_tag_with_separator() {
605        let config = StrategyConfig {
606            order_id_tag: Some("A-B".to_string()),
607            ..Default::default()
608        };
609
610        let _ = StrategyCore::new(config);
611    }
612
613    #[rstest]
614    fn test_strategy_core_change_order_id_tag_rejects_separator() {
615        let config = StrategyConfig {
616            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
617            ..Default::default()
618        };
619        let mut core = StrategyCore::new(config);
620
621        let error = core.change_order_id_tag("A-B").unwrap_err();
622
623        assert_eq!(
624            error.to_string(),
625            "`order_id_tag` cannot contain the '-' strategy ID separator, was 'A-B'"
626        );
627        assert_eq!(core.actor_id(), ActorId::from("ExampleStrategy-XNAS"));
628        assert_eq!(
629            core.strategy_id(),
630            Some(StrategyId::from("ExampleStrategy-XNAS"))
631        );
632        assert_eq!(core.order_id_tag(), Some("XNAS"));
633    }
634
635    #[rstest]
636    fn test_strategy_core_new_checked_rejects_non_ascii_order_id_tag() {
637        let config = StrategyConfig {
638            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
639            order_id_tag: Some("T01€".to_string()),
640            ..Default::default()
641        };
642
643        let error = StrategyCore::new_checked(config).unwrap_err();
644
645        assert_eq!(
646            error.to_string(),
647            "invalid string for 'value' contained a non-ASCII char, was 'ExampleStrategy-XNAS-T01€'"
648        );
649    }
650
651    #[rstest]
652    #[should_panic(
653        expected = "invalid string for 'value' contained a non-ASCII char, was 'ExampleStrategy-XNAS-T01€'"
654    )]
655    fn test_strategy_core_new_panics_on_non_ascii_order_id_tag() {
656        let config = StrategyConfig {
657            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
658            order_id_tag: Some("T01€".to_string()),
659            ..Default::default()
660        };
661
662        let _ = StrategyCore::new(config);
663    }
664
665    #[rstest]
666    fn test_strategy_core_change_order_id_tag_rejects_non_ascii() {
667        let config = StrategyConfig {
668            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
669            ..Default::default()
670        };
671        let mut core = StrategyCore::new(config);
672
673        let error = core.change_order_id_tag("T01€").unwrap_err();
674
675        assert_eq!(
676            error.to_string(),
677            "invalid string for 'value' contained a non-ASCII char, was 'ExampleStrategy-XNAS-T01€'"
678        );
679        assert_eq!(core.actor_id(), ActorId::from("ExampleStrategy-XNAS"));
680        assert_eq!(
681            core.strategy_id(),
682            Some(StrategyId::from("ExampleStrategy-XNAS"))
683        );
684        assert_eq!(core.order_id_tag(), Some("XNAS"));
685    }
686
687    #[rstest]
688    fn test_strategy_core_change_id_rejects_non_ascii_order_id_tag() {
689        let config = StrategyConfig {
690            order_id_tag: Some("T01€".to_string()),
691            ..Default::default()
692        };
693        let mut core = StrategyCore::new(config);
694
695        let error = core
696            .change_id(StrategyId::from("ExampleStrategy-XNAS"))
697            .unwrap_err();
698
699        assert_eq!(
700            error.to_string(),
701            "invalid string for 'value' contained a non-ASCII char, was 'ExampleStrategy-XNAS-T01€'"
702        );
703        assert_eq!(core.actor_id(), ActorId::from("Strategy-None"));
704        assert_eq!(core.strategy_id(), None);
705        assert_eq!(core.order_id_tag(), Some("T01€"));
706    }
707
708    #[rstest]
709    fn test_strategy_core_change_order_id_tag_without_strategy_id_stores_tag() {
710        let mut core = StrategyCore::new(StrategyConfig::default());
711
712        core.change_order_id_tag("T01").unwrap();
713
714        assert_eq!(core.actor_id(), ActorId::from("Strategy-None"));
715        assert_eq!(core.strategy_id(), None);
716        assert_eq!(core.order_id_tag(), Some("T01"));
717    }
718
719    #[rstest]
720    #[case("")]
721    #[case("None")]
722    fn test_strategy_core_change_order_id_tag_clears_unset_sentinel(#[case] order_id_tag: &str) {
723        let config = StrategyConfig {
724            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
725            ..Default::default()
726        };
727        let mut core = StrategyCore::new(config);
728
729        core.change_order_id_tag(order_id_tag).unwrap();
730
731        assert_eq!(core.actor_id(), ActorId::from("ExampleStrategy-XNAS"));
732        assert_eq!(
733            core.strategy_id(),
734            Some(StrategyId::from("ExampleStrategy-XNAS"))
735        );
736        assert_eq!(core.order_id_tag(), None);
737    }
738
739    #[rstest]
740    fn test_strategy_core_register_rejects_configured_order_id_tag_with_separator() {
741        let config = StrategyConfig {
742            strategy_id: Some(StrategyId::from("HyphenTagStrategy-001")),
743            order_id_tag: Some("001".to_string()),
744            ..Default::default()
745        };
746        let mut core = StrategyCore::new(config);
747        core.config.order_id_tag = Some("A-B".to_string());
748
749        let trader_id = TraderId::from("TRADER-001");
750        let clock = Rc::new(RefCell::new(VirtualClock::new()));
751        let cache = Rc::new(RefCell::new(Cache::default()));
752        let portfolio = Rc::new(RefCell::new(Portfolio::new(
753            clock.clone(),
754            cache.clone(),
755            None,
756        )));
757
758        let error = core
759            .register(trader_id, clock, cache, portfolio)
760            .unwrap_err();
761
762        assert_eq!(
763            error.to_string(),
764            "`order_id_tag` cannot contain the '-' strategy ID separator, was 'A-B'"
765        );
766        assert!(core.order_factory.is_none());
767        assert!(core.order_manager.is_none());
768        assert!(core.portfolio.is_none());
769        assert_eq!(core.trader_id(), None);
770    }
771
772    #[rstest]
773    fn test_strategy_core_register() {
774        let config = create_test_config();
775        let mut core = StrategyCore::new(config);
776
777        let trader_id = TraderId::from("TRADER-001");
778        let clock = Rc::new(RefCell::new(VirtualClock::new()));
779        let cache = Rc::new(RefCell::new(Cache::default()));
780        let portfolio = Rc::new(RefCell::new(Portfolio::new(
781            clock.clone(),
782            cache.clone(),
783            None,
784        )));
785
786        let result = core.register(trader_id, clock, cache, portfolio);
787        assert!(result.is_ok());
788
789        assert!(core.order_manager.is_some());
790        assert!(core.order_factory.is_some());
791        assert!(core.portfolio.is_some());
792        assert_eq!(core.trader_id(), Some(trader_id));
793    }
794
795    #[rstest]
796    fn test_strategy_core_register_uses_order_id_tag_for_order_api_ids() {
797        let config = StrategyConfig {
798            strategy_id: Some(StrategyId::from("ExampleStrategy-XNAS")),
799            order_id_tag: Some("T01".to_string()),
800            ..Default::default()
801        };
802        let mut core = StrategyCore::new(config);
803
804        let trader_id = TraderId::from("TRADER-001");
805        let clock = Rc::new(RefCell::new(VirtualClock::new()));
806        let cache = Rc::new(RefCell::new(Cache::default()));
807        let portfolio = Rc::new(RefCell::new(Portfolio::new(
808            clock.clone(),
809            cache.clone(),
810            None,
811        )));
812
813        core.register(trader_id, clock, cache, portfolio).unwrap();
814
815        let orders = core.order();
816        let client_order_id = orders.generate_client_order_id();
817        let order_list_id = orders.generate_order_list_id();
818
819        assert_eq!(
820            core.strategy_id(),
821            Some(StrategyId::from("ExampleStrategy-XNAS-T01"))
822        );
823        assert_eq!(client_order_id.as_str(), "O-19700101-000000-001-T01-1");
824        assert_eq!(order_list_id.as_str(), "OL-19700101-000000-001-T01-1");
825    }
826
827    #[rstest]
828    fn test_strategy_core_order_api_creates_orders() {
829        let core = registered_test_core();
830        let orders = core.order();
831
832        let market = orders.market(
833            InstrumentId::from("BTCUSDT.BINANCE"),
834            OrderSide::Buy,
835            Quantity::from("1.0"),
836            None,
837            None,
838            None,
839            None,
840            None,
841            None,
842            None,
843        );
844        let limit = orders.limit(
845            InstrumentId::from("BTCUSDT.BINANCE"),
846            OrderSide::Sell,
847            Quantity::from("2.0"),
848            Price::from("100.00"),
849            None,
850            None,
851            None,
852            None,
853            None,
854            None,
855            None,
856            None,
857            None,
858            None,
859            None,
860            None,
861        );
862
863        assert_eq!(market.order_type(), OrderType::Market);
864        assert_eq!(
865            market.client_order_id().as_str(),
866            "O-19700101-000000-001-001-1"
867        );
868        assert_eq!(limit.order_type(), OrderType::Limit);
869        assert_eq!(
870            limit.client_order_id().as_str(),
871            "O-19700101-000000-001-001-2"
872        );
873    }
874
875    #[rstest]
876    fn test_strategy_core_order_api_creates_remaining_order_types() {
877        let core = registered_test_core();
878        let orders = core.order();
879        let instrument_id = InstrumentId::from("BTCUSDT.BINANCE");
880        let trigger_instrument_id = InstrumentId::from("ETHUSDT.BINANCE");
881        let expire_time = UnixNanos::from(1_000);
882        let display_qty = Quantity::from("0.5");
883
884        let stop_market = orders.stop_market(
885            instrument_id,
886            OrderSide::Buy,
887            Quantity::from("1.0"),
888            Price::from("99.00"),
889            Some(TriggerType::LastPrice),
890            Some(TimeInForce::Gtd),
891            Some(expire_time),
892            Some(true),
893            Some(false),
894            Some(display_qty),
895            Some(TriggerType::BidAsk),
896            Some(trigger_instrument_id),
897            None,
898            None,
899            None,
900            None,
901        );
902        let stop_limit = orders.stop_limit(
903            instrument_id,
904            OrderSide::Sell,
905            Quantity::from("1.1"),
906            Price::from("101.00"),
907            Price::from("100.50"),
908            Some(TriggerType::LastPrice),
909            Some(TimeInForce::Gtd),
910            Some(expire_time),
911            Some(true),
912            Some(false),
913            Some(false),
914            Some(display_qty),
915            Some(TriggerType::BidAsk),
916            Some(trigger_instrument_id),
917            None,
918            None,
919            None,
920            None,
921        );
922        let market_to_limit = orders.market_to_limit(
923            instrument_id,
924            OrderSide::Buy,
925            Quantity::from("1.2"),
926            Some(TimeInForce::Gtd),
927            Some(expire_time),
928            Some(true),
929            Some(false),
930            Some(display_qty),
931            None,
932            None,
933            None,
934            None,
935        );
936        let market_if_touched = orders.market_if_touched(
937            instrument_id,
938            OrderSide::Sell,
939            Quantity::from("1.3"),
940            Price::from("98.50"),
941            Some(TriggerType::LastPrice),
942            Some(TimeInForce::Gtd),
943            Some(expire_time),
944            Some(false),
945            Some(false),
946            Some(TriggerType::BidAsk),
947            Some(trigger_instrument_id),
948            None,
949            None,
950            None,
951            None,
952        );
953        let limit_if_touched = orders.limit_if_touched(
954            instrument_id,
955            OrderSide::Buy,
956            Quantity::from("1.4"),
957            Price::from("97.50"),
958            Price::from("97.00"),
959            Some(TriggerType::LastPrice),
960            Some(TimeInForce::Gtd),
961            Some(expire_time),
962            Some(true),
963            Some(false),
964            Some(false),
965            Some(display_qty),
966            Some(TriggerType::BidAsk),
967            Some(trigger_instrument_id),
968            None,
969            None,
970            None,
971            None,
972        );
973        let trailing_stop_market = orders.trailing_stop_market(
974            instrument_id,
975            OrderSide::Sell,
976            Quantity::from("1.5"),
977            Decimal::new(25, 2),
978            Some(TrailingOffsetType::Price),
979            Some(Price::from("105.00")),
980            Some(Price::from("104.50")),
981            Some(TriggerType::LastPrice),
982            Some(TimeInForce::Gtd),
983            Some(expire_time),
984            Some(false),
985            Some(false),
986            Some(display_qty),
987            Some(TriggerType::BidAsk),
988            Some(trigger_instrument_id),
989            None,
990            None,
991            None,
992            None,
993        );
994        let trailing_stop_limit = orders.trailing_stop_limit(
995            instrument_id,
996            OrderSide::Buy,
997            Quantity::from("1.6"),
998            Price::from("96.00"),
999            Decimal::new(10, 2),
1000            Decimal::new(50, 2),
1001            Some(TrailingOffsetType::Price),
1002            Some(Price::from("97.00")),
1003            Some(Price::from("96.50")),
1004            Some(TriggerType::LastPrice),
1005            Some(TimeInForce::Gtd),
1006            Some(expire_time),
1007            Some(true),
1008            Some(false),
1009            Some(false),
1010            Some(display_qty),
1011            Some(TriggerType::BidAsk),
1012            Some(trigger_instrument_id),
1013            None,
1014            None,
1015            None,
1016            None,
1017        );
1018        let mut list_orders = vec![market_to_limit.clone(), stop_limit.clone()];
1019        let order_list = orders.create_list(&mut list_orders, expire_time);
1020
1021        assert_eq!(stop_market.order_type(), OrderType::StopMarket);
1022        assert_eq!(stop_market.trigger_price(), Some(Price::from("99.00")));
1023        assert_eq!(stop_market.trigger_type(), Some(TriggerType::LastPrice));
1024        assert_eq!(stop_market.time_in_force(), TimeInForce::Gtd);
1025        assert_eq!(stop_market.expire_time(), Some(expire_time));
1026        assert!(stop_market.is_reduce_only());
1027        assert_eq!(stop_market.display_qty(), Some(display_qty));
1028        assert_eq!(stop_market.emulation_trigger(), Some(TriggerType::BidAsk));
1029        assert_eq!(
1030            stop_market.trigger_instrument_id(),
1031            Some(trigger_instrument_id)
1032        );
1033
1034        assert_eq!(stop_limit.order_type(), OrderType::StopLimit);
1035        assert_eq!(stop_limit.price(), Some(Price::from("101.00")));
1036        assert_eq!(stop_limit.trigger_price(), Some(Price::from("100.50")));
1037        assert!(stop_limit.is_post_only());
1038
1039        assert_eq!(market_to_limit.order_type(), OrderType::MarketToLimit);
1040        assert_eq!(market_to_limit.time_in_force(), TimeInForce::Gtd);
1041        assert_eq!(market_to_limit.expire_time(), Some(expire_time));
1042        assert!(market_to_limit.is_reduce_only());
1043        assert_eq!(market_to_limit.display_qty(), Some(display_qty));
1044
1045        assert_eq!(market_if_touched.order_type(), OrderType::MarketIfTouched);
1046        assert_eq!(
1047            market_if_touched.trigger_price(),
1048            Some(Price::from("98.50"))
1049        );
1050        assert_eq!(
1051            market_if_touched.trigger_type(),
1052            Some(TriggerType::LastPrice)
1053        );
1054
1055        assert_eq!(limit_if_touched.order_type(), OrderType::LimitIfTouched);
1056        assert_eq!(limit_if_touched.price(), Some(Price::from("97.50")));
1057        assert_eq!(limit_if_touched.trigger_price(), Some(Price::from("97.00")));
1058        assert!(limit_if_touched.is_post_only());
1059
1060        assert_eq!(
1061            trailing_stop_market.order_type(),
1062            OrderType::TrailingStopMarket
1063        );
1064        assert_eq!(
1065            trailing_stop_market.trailing_offset(),
1066            Some(Decimal::new(25, 2))
1067        );
1068        assert_eq!(
1069            trailing_stop_market.trailing_offset_type(),
1070            Some(TrailingOffsetType::Price)
1071        );
1072        assert_eq!(
1073            trailing_stop_market.activation_price(),
1074            Some(Price::from("105.00"))
1075        );
1076        assert_eq!(
1077            trailing_stop_market.trigger_price(),
1078            Some(Price::from("104.50"))
1079        );
1080
1081        assert_eq!(
1082            trailing_stop_limit.order_type(),
1083            OrderType::TrailingStopLimit
1084        );
1085        assert_eq!(trailing_stop_limit.price(), Some(Price::from("96.00")));
1086        assert_eq!(
1087            trailing_stop_limit.limit_offset(),
1088            Some(Decimal::new(10, 2))
1089        );
1090        assert_eq!(
1091            trailing_stop_limit.trailing_offset(),
1092            Some(Decimal::new(50, 2))
1093        );
1094        assert_eq!(
1095            trailing_stop_limit.activation_price(),
1096            Some(Price::from("97.00"))
1097        );
1098        assert!(trailing_stop_limit.is_post_only());
1099
1100        assert_eq!(order_list.id, list_orders[0].order_list_id().unwrap());
1101        assert_eq!(order_list.id, list_orders[1].order_list_id().unwrap());
1102        assert_eq!(order_list.instrument_id, instrument_id);
1103        assert_eq!(
1104            order_list.client_order_ids,
1105            list_orders
1106                .iter()
1107                .map(Order::client_order_id)
1108                .collect::<Vec<_>>()
1109        );
1110    }
1111
1112    #[rstest]
1113    fn test_strategy_core_order_api_generates_ids() {
1114        let core = registered_test_core();
1115        let (client_order_id, order_list_id) = {
1116            let orders = core.order();
1117            (
1118                orders.generate_client_order_id(),
1119                orders.generate_order_list_id(),
1120            )
1121        };
1122
1123        let next_client_order_id = core.order().generate_client_order_id();
1124
1125        assert_eq!(client_order_id.as_str(), "O-19700101-000000-001-001-1");
1126        assert_eq!(order_list_id.as_str(), "OL-19700101-000000-001-001-1");
1127        assert_eq!(next_client_order_id.as_str(), "O-19700101-000000-001-001-2");
1128    }
1129
1130    #[rstest]
1131    fn test_strategy_core_order_api_creates_bracket_orders() {
1132        let core = registered_test_core();
1133
1134        let orders = core
1135            .order()
1136            .bracket()
1137            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
1138            .order_side(OrderSide::Buy)
1139            .quantity(Quantity::from("1.0"))
1140            .tp_price(Price::from("110.00"))
1141            .sl_trigger_price(Price::from("90.00"))
1142            .call();
1143        let order_list_id = orders[0].order_list_id();
1144
1145        assert_eq!(orders.len(), 3);
1146        assert_eq!(orders[0].order_type(), OrderType::Market);
1147        assert_eq!(orders[1].order_type(), OrderType::StopMarket);
1148        assert_eq!(orders[2].order_type(), OrderType::Limit);
1149        assert!(order_list_id.is_some());
1150        assert!(
1151            orders
1152                .iter()
1153                .all(|order| order.order_list_id() == order_list_id)
1154        );
1155    }
1156
1157    #[rstest]
1158    fn test_strategy_core_portfolio_api_returns_owned_reads() {
1159        let core = registered_test_core();
1160        let portfolio = core.portfolio_api();
1161        let instrument_id = InstrumentId::from("BTCUSDT.BINANCE");
1162        let venue = instrument_id.venue;
1163        let account_id = AccountId::from("SIM-001");
1164
1165        let is_initialized = portfolio.is_initialized();
1166        let balances_locked = portfolio.balances_locked(&venue, None);
1167        let initial_margins = portfolio.instrument_initial_margins(&venue, None);
1168        let maintenance_margins = portfolio.instrument_maintenance_margins(&venue, None);
1169        let unrealized_pnls = portfolio.unrealized_pnls(&venue, None);
1170        let realized_pnls = portfolio.realized_pnls(&venue, None);
1171        let net_exposures = portfolio.net_exposures(&venue, None);
1172        let unrealized_pnl = portfolio.unrealized_pnl(&instrument_id);
1173        let realized_pnl = portfolio.realized_pnl(&instrument_id);
1174        let total_pnl = portfolio.total_pnl(&instrument_id);
1175        let total_pnls = portfolio.total_pnls(&venue, None);
1176        let mark_values = portfolio.mark_values(&venue, None);
1177        let equity = portfolio.equity(&venue, None);
1178        let net_exposure = portfolio.net_exposure(&instrument_id, None);
1179        let is_flat = portfolio.is_net_flat(&instrument_id);
1180        let net_position = portfolio.net_position(&instrument_id);
1181        let missing_prices = portfolio.missing_price_instruments(&venue);
1182        let snapshots = portfolio.snapshots(&account_id);
1183        let recorded_realized_pnls = portfolio.recorded_realized_pnls();
1184        let built_snapshot = portfolio.build_snapshot(&account_id);
1185
1186        assert!(!is_initialized);
1187        assert!(balances_locked.is_empty());
1188        assert!(initial_margins.is_empty());
1189        assert!(maintenance_margins.is_empty());
1190        assert!(unrealized_pnls.is_some_and(|values| values.is_empty()));
1191        assert!(realized_pnls.is_some_and(|values| values.is_empty()));
1192        assert_eq!(net_exposures, None);
1193        assert_eq!(unrealized_pnl, None);
1194        assert_eq!(realized_pnl, None);
1195        assert_eq!(total_pnl, None);
1196        assert!(total_pnls.is_some_and(|values| values.is_empty()));
1197        assert!(mark_values.is_empty());
1198        assert!(equity.is_empty());
1199        assert_eq!(net_exposure, None);
1200        assert!(is_flat);
1201        assert_eq!(net_position, Decimal::ZERO);
1202        assert!(missing_prices.is_empty());
1203        assert!(snapshots.is_empty());
1204        assert!(recorded_realized_pnls.is_empty());
1205        assert_eq!(built_snapshot, None);
1206    }
1207
1208    #[rstest]
1209    fn test_strategy_core_actor_state_starts_unregistered() {
1210        let config = create_test_config();
1211        let core = StrategyCore::new(config);
1212
1213        assert!(core.trader_id().is_none());
1214    }
1215
1216    #[rstest]
1217    fn test_strategy_core_debug() {
1218        let config = create_test_config();
1219        let core = StrategyCore::new(config);
1220
1221        let debug_str = format!("{core:?}");
1222        assert!(debug_str.contains("StrategyCore"));
1223    }
1224
1225    fn registered_test_core() -> StrategyCore {
1226        let config = create_test_config();
1227        let mut core = StrategyCore::new(config);
1228
1229        let trader_id = TraderId::from("TRADER-001");
1230        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1231        let cache = Rc::new(RefCell::new(Cache::default()));
1232        let portfolio = Rc::new(RefCell::new(Portfolio::new(
1233            clock.clone(),
1234            cache.clone(),
1235            None,
1236        )));
1237
1238        core.register(trader_id, clock, cache, portfolio).unwrap();
1239        core
1240    }
1241}