nautilus_model/identifiers/strategy_id.rs
1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2025 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, 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 = "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 /// # Panics
48 ///
49 /// This function panics:
50 /// - If `value` is not a valid string, or does not contain a hyphen '-' separator.
51 pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
52 let value = value.as_ref();
53 check_valid_string(value, stringify!(value))?;
54 if value != EXTERNAL_STRATEGY_ID {
55 check_string_contains(value, "-", stringify!(value))?;
56 }
57 Ok(Self(Ustr::from(value)))
58 }
59
60 /// Creates a new [`StrategyId`] instance.
61 ///
62 /// # Panics
63 ///
64 /// This function panics:
65 /// - If `value` is not a valid string.
66 pub fn new<T: AsRef<str>>(value: T) -> Self {
67 Self::new_checked(value).expect(FAILED)
68 }
69
70 /// Sets the inner identifier value.
71 #[allow(dead_code)]
72 pub(crate) fn set_inner(&mut self, value: &str) {
73 self.0 = Ustr::from(value);
74 }
75
76 /// Returns the inner identifier value.
77 #[must_use]
78 pub fn inner(&self) -> Ustr {
79 self.0
80 }
81
82 /// Returns the inner identifier value as a string slice.
83 #[must_use]
84 pub fn as_str(&self) -> &str {
85 self.0.as_str()
86 }
87
88 #[must_use]
89 pub fn external() -> Self {
90 // SAFETY:: Constant value is safe
91 Self::new(EXTERNAL_STRATEGY_ID)
92 }
93
94 #[must_use]
95 pub fn is_external(&self) -> bool {
96 self.0 == EXTERNAL_STRATEGY_ID
97 }
98
99 #[must_use]
100 pub fn get_tag(&self) -> &str {
101 // SAFETY: Unwrap safe as value previously validated
102 self.0.split('-').next_back().unwrap()
103 }
104}
105
106impl Debug for StrategyId {
107 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
108 write!(f, "{:?}", self.0)
109 }
110}
111
112impl Display for StrategyId {
113 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
114 write!(f, "{}", self.0)
115 }
116}
117
118////////////////////////////////////////////////////////////////////////////////
119// Tests
120////////////////////////////////////////////////////////////////////////////////
121#[cfg(test)]
122mod tests {
123 use rstest::rstest;
124
125 use super::StrategyId;
126 use crate::identifiers::stubs::*;
127
128 #[rstest]
129 fn test_string_reprs(strategy_id_ema_cross: StrategyId) {
130 assert_eq!(strategy_id_ema_cross.as_str(), "EMACross-001");
131 assert_eq!(format!("{strategy_id_ema_cross}"), "EMACross-001");
132 }
133
134 #[rstest]
135 fn test_get_external() {
136 assert_eq!(StrategyId::external().as_str(), "EXTERNAL");
137 }
138
139 #[rstest]
140 fn test_is_external() {
141 assert!(StrategyId::external().is_external());
142 }
143
144 #[rstest]
145 fn test_get_tag(strategy_id_ema_cross: StrategyId) {
146 assert_eq!(strategy_id_ema_cross.get_tag(), "001");
147 }
148}