nautilus_model/identifiers/
strategy_id.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Represents a valid strategy ID.
17
18use std::fmt::{Debug, Display};
19
20use nautilus_core::correctness::{FAILED, check_string_contains, check_valid_string_ascii};
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 = "nautilus_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:
50    /// - `value` is not a valid ASCII string.
51    /// - `value` is not "EXTERNAL" and does not contain a hyphen '-' separator.
52    /// - Either the name or tag part (before/after the hyphen) is empty.
53    pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
54        let value = value.as_ref();
55        check_valid_string_ascii(value, stringify!(value))?;
56        if value != EXTERNAL_STRATEGY_ID {
57            check_string_contains(value, "-", stringify!(value))?;
58
59            if let Some((name, tag)) = value.rsplit_once('-') {
60                anyhow::ensure!(
61                    !name.is_empty(),
62                    "`value` name part (before '-') cannot be empty"
63                );
64                anyhow::ensure!(
65                    !tag.is_empty(),
66                    "`value` tag part (after '-') cannot be empty"
67                );
68            }
69        }
70        Ok(Self(Ustr::from(value)))
71    }
72
73    /// Creates a new [`StrategyId`] instance.
74    ///
75    /// # Panics
76    ///
77    /// Panics if `value` is not a valid string.
78    pub fn new<T: AsRef<str>>(value: T) -> Self {
79        Self::new_checked(value).expect(FAILED)
80    }
81
82    /// Sets the inner identifier value.
83    #[cfg_attr(not(feature = "python"), allow(dead_code))]
84    pub(crate) fn set_inner(&mut self, value: &str) {
85        self.0 = Ustr::from(value);
86    }
87
88    /// Returns the inner identifier value.
89    #[must_use]
90    pub fn inner(&self) -> Ustr {
91        self.0
92    }
93
94    /// Returns the inner identifier value as a string slice.
95    #[must_use]
96    pub fn as_str(&self) -> &str {
97        self.0.as_str()
98    }
99
100    #[must_use]
101    pub fn external() -> Self {
102        // SAFETY:: Constant value is safe
103        Self::new(EXTERNAL_STRATEGY_ID)
104    }
105
106    #[must_use]
107    pub fn is_external(&self) -> bool {
108        self.0 == EXTERNAL_STRATEGY_ID
109    }
110
111    /// Returns the numerical tag portion of the strategy ID.
112    ///
113    /// For external strategy IDs (no separator), returns the full ID string.
114    #[must_use]
115    pub fn get_tag(&self) -> &str {
116        self.0
117            .rsplit_once('-')
118            .map_or(self.0.as_str(), |(_, tag)| tag)
119    }
120}
121
122impl Debug for StrategyId {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        write!(f, "\"{}\"", self.0)
125    }
126}
127
128impl Display for StrategyId {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        write!(f, "{}", self.0)
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use rstest::rstest;
137
138    use super::StrategyId;
139    use crate::identifiers::stubs::*;
140
141    #[rstest]
142    fn test_string_reprs(strategy_id_ema_cross: StrategyId) {
143        assert_eq!(strategy_id_ema_cross.as_str(), "EMACross-001");
144        assert_eq!(format!("{strategy_id_ema_cross}"), "EMACross-001");
145    }
146
147    #[rstest]
148    fn test_get_external() {
149        assert_eq!(StrategyId::external().as_str(), "EXTERNAL");
150    }
151
152    #[rstest]
153    fn test_is_external() {
154        assert!(StrategyId::external().is_external());
155    }
156
157    #[rstest]
158    fn test_get_tag(strategy_id_ema_cross: StrategyId) {
159        assert_eq!(strategy_id_ema_cross.get_tag(), "001");
160    }
161
162    #[rstest]
163    fn test_get_tag_external() {
164        assert_eq!(StrategyId::external().get_tag(), "EXTERNAL");
165    }
166
167    #[rstest]
168    #[should_panic(expected = "name part (before '-') cannot be empty")]
169    fn test_new_with_empty_name_panics() {
170        let _ = StrategyId::new("-001");
171    }
172
173    #[rstest]
174    #[should_panic(expected = "tag part (after '-') cannot be empty")]
175    fn test_new_with_empty_tag_panics() {
176        let _ = StrategyId::new("EMACross-");
177    }
178
179    #[rstest]
180    fn test_new_checked_with_empty_name_returns_error() {
181        assert!(StrategyId::new_checked("-001").is_err());
182    }
183
184    #[rstest]
185    fn test_new_checked_with_empty_tag_returns_error() {
186        assert!(StrategyId::new_checked("EMACross-").is_err());
187    }
188}