nautilus_model/identifiers/
strategy_id.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Represents a valid strategy ID.
17
18use std::fmt::{Debug, Display, Formatter};
19
20use nautilus_core::correctness::{FAILED, check_string_contains, check_valid_string};
21use ustr::Ustr;
22
23/// The identifier for all 'external' strategy IDs (not local to this system instance).
24const EXTERNAL_STRATEGY_ID: &str = "EXTERNAL";
25
26/// Represents a valid strategy ID.
27#[repr(C)]
28#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.model")
32)]
33pub struct StrategyId(Ustr);
34
35impl StrategyId {
36    /// Creates a new [`StrategyId`] instance.
37    ///
38    /// Must be correctly formatted with two valid strings either side of a hyphen.
39    /// It is expected a strategy ID is the class name of the strategy,
40    /// with an order ID tag number separated by a hyphen.
41    ///
42    /// Example: "EMACross-001".
43    ///
44    /// The reason for the numerical component of the ID is so that order and position IDs
45    /// do not collide with those from another strategy within the node instance.
46    ///
47    /// # Errors
48    ///
49    /// Returns an error if `value` is not a valid strategy format or missing '-' separator.
50    ///
51    /// # Panics
52    ///
53    /// Panics if `value` is not a valid string, or does not contain a hyphen '-' separator.
54    pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
55        let value = value.as_ref();
56        check_valid_string(value, stringify!(value))?;
57        if value != EXTERNAL_STRATEGY_ID {
58            check_string_contains(value, "-", stringify!(value))?;
59        }
60        Ok(Self(Ustr::from(value)))
61    }
62
63    /// Creates a new [`StrategyId`] instance.
64    ///
65    /// # Panics
66    ///
67    /// Panics if `value` is not a valid string.
68    pub fn new<T: AsRef<str>>(value: T) -> Self {
69        Self::new_checked(value).expect(FAILED)
70    }
71
72    /// Sets the inner identifier value.
73    #[allow(dead_code)]
74    pub(crate) fn set_inner(&mut self, value: &str) {
75        self.0 = Ustr::from(value);
76    }
77
78    /// Returns the inner identifier value.
79    #[must_use]
80    pub fn inner(&self) -> Ustr {
81        self.0
82    }
83
84    /// Returns the inner identifier value as a string slice.
85    #[must_use]
86    pub fn as_str(&self) -> &str {
87        self.0.as_str()
88    }
89
90    #[must_use]
91    pub fn external() -> Self {
92        // SAFETY:: Constant value is safe
93        Self::new(EXTERNAL_STRATEGY_ID)
94    }
95
96    #[must_use]
97    pub fn is_external(&self) -> bool {
98        self.0 == EXTERNAL_STRATEGY_ID
99    }
100
101    /// Returns the numerical tag portion of the strategy ID.
102    ///
103    /// # Panics
104    ///
105    /// Panics if the internal ID does not contain a '-' separator.
106    #[must_use]
107    pub fn get_tag(&self) -> &str {
108        // SAFETY: Unwrap safe as value previously validated
109        self.0.split('-').next_back().unwrap()
110    }
111}
112
113impl Debug for StrategyId {
114    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
115        write!(f, "{:?}", self.0)
116    }
117}
118
119impl Display for StrategyId {
120    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
121        write!(f, "{}", self.0)
122    }
123}
124
125////////////////////////////////////////////////////////////////////////////////
126// Tests
127////////////////////////////////////////////////////////////////////////////////
128#[cfg(test)]
129mod tests {
130    use rstest::rstest;
131
132    use super::StrategyId;
133    use crate::identifiers::stubs::*;
134
135    #[rstest]
136    fn test_string_reprs(strategy_id_ema_cross: StrategyId) {
137        assert_eq!(strategy_id_ema_cross.as_str(), "EMACross-001");
138        assert_eq!(format!("{strategy_id_ema_cross}"), "EMACross-001");
139    }
140
141    #[rstest]
142    fn test_get_external() {
143        assert_eq!(StrategyId::external().as_str(), "EXTERNAL");
144    }
145
146    #[rstest]
147    fn test_is_external() {
148        assert!(StrategyId::external().is_external());
149    }
150
151    #[rstest]
152    fn test_get_tag(strategy_id_ema_cross: StrategyId) {
153        assert_eq!(strategy_id_ema_cross.get_tag(), "001");
154    }
155}