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::{check_string_contains, check_valid_string, FAILED};
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 pub(crate) fn set_inner(&mut self, value: &str) {
72 self.0 = Ustr::from(value);
73 }
74
75 /// Returns the inner identifier value.
76 #[must_use]
77 pub fn inner(&self) -> Ustr {
78 self.0
79 }
80
81 /// Returns the inner identifier value as a string slice.
82 #[must_use]
83 pub fn as_str(&self) -> &str {
84 self.0.as_str()
85 }
86
87 #[must_use]
88 pub fn external() -> Self {
89 // SAFETY:: Constant value is safe
90 Self::new(EXTERNAL_STRATEGY_ID)
91 }
92
93 #[must_use]
94 pub fn is_external(&self) -> bool {
95 self.0 == EXTERNAL_STRATEGY_ID
96 }
97
98 #[must_use]
99 pub fn get_tag(&self) -> &str {
100 // SAFETY: Unwrap safe as value previously validated
101 self.0.split('-').last().unwrap()
102 }
103}
104
105impl Debug for StrategyId {
106 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
107 write!(f, "{:?}", self.0)
108 }
109}
110
111impl Display for StrategyId {
112 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
113 write!(f, "{}", self.0)
114 }
115}
116
117////////////////////////////////////////////////////////////////////////////////
118// Tests
119////////////////////////////////////////////////////////////////////////////////
120#[cfg(test)]
121mod tests {
122 use rstest::rstest;
123
124 use super::StrategyId;
125 use crate::identifiers::stubs::*;
126
127 #[rstest]
128 fn test_string_reprs(strategy_id_ema_cross: StrategyId) {
129 assert_eq!(strategy_id_ema_cross.as_str(), "EMACross-001");
130 assert_eq!(format!("{strategy_id_ema_cross}"), "EMACross-001");
131 }
132
133 #[rstest]
134 fn test_get_external() {
135 assert_eq!(StrategyId::external().as_str(), "EXTERNAL");
136 }
137
138 #[rstest]
139 fn test_is_external() {
140 assert!(StrategyId::external().is_external());
141 }
142
143 #[rstest]
144 fn test_get_tag(strategy_id_ema_cross: StrategyId) {
145 assert_eq!(strategy_id_ema_cross.get_tag(), "001");
146 }
147}