Skip to main content

nautilus_model/identifiers/
trader_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 trader ID.
17
18use std::fmt::{Debug, Display};
19
20use nautilus_core::correctness::{
21    CorrectnessResult, CorrectnessResultExt, FAILED, check_predicate_false, check_string_contains,
22    check_valid_string_ascii,
23};
24use ustr::Ustr;
25
26const EXTERNAL_TRADER_ID: &str = "EXTERNAL-0";
27
28/// Represents a valid trader ID.
29#[repr(C)]
30#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
31#[cfg_attr(
32    feature = "python",
33    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
34)]
35#[cfg_attr(
36    feature = "python",
37    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
38)]
39pub struct TraderId(Ustr);
40
41impl TraderId {
42    /// Creates a new [`TraderId`] instance.
43    ///
44    /// Must be correctly formatted with two valid strings either side of a hyphen.
45    /// It is expected a trader ID is the abbreviated name of the trader
46    /// with an order ID tag number separated by a hyphen.
47    ///
48    /// Example: "TESTER-001".
49    ///
50    /// The reason for the numerical component of the ID is so that order and position IDs
51    /// do not collide with those from another node instance.
52    ///
53    /// # Errors
54    ///
55    /// Returns an error if:
56    /// - `value` is not a valid ASCII string.
57    /// - `value` does not contain a hyphen '-' separator.
58    /// - Either the name or tag part (before/after the hyphen) is empty.
59    ///
60    /// # Notes
61    ///
62    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
63    pub fn new_checked<T: AsRef<str>>(value: T) -> CorrectnessResult<Self> {
64        let value = value.as_ref();
65        check_valid_string_ascii(value, stringify!(value))?;
66        check_string_contains(value, "-", stringify!(value))?;
67
68        if let Some((name, tag)) = value.rsplit_once('-') {
69            check_predicate_false(
70                name.is_empty(),
71                "`value` name part (before '-') cannot be empty",
72            )?;
73            check_predicate_false(
74                tag.is_empty(),
75                "`value` tag part (after '-') cannot be empty",
76            )?;
77        }
78
79        Ok(Self(Ustr::from(value)))
80    }
81
82    /// Creates a new [`TraderId`] instance.
83    ///
84    /// # Panics
85    ///
86    /// Panics if `value` is not a valid string, or does not contain a hyphen '-' separator.
87    pub fn new<T: AsRef<str>>(value: T) -> Self {
88        Self::new_checked(value).expect_display(FAILED)
89    }
90
91    /// Sets the inner identifier value.
92    #[cfg_attr(not(feature = "python"), allow(dead_code))]
93    pub(crate) fn set_inner(&mut self, value: &str) {
94        self.0 = Ustr::from(value);
95    }
96
97    /// Returns the inner identifier value.
98    #[must_use]
99    pub fn inner(&self) -> Ustr {
100        self.0
101    }
102
103    /// Returns the inner identifier value as a string slice.
104    #[must_use]
105    pub fn as_str(&self) -> &str {
106        self.0.as_str()
107    }
108
109    /// Returns the numerical tag portion of the trader ID.
110    ///
111    /// # Panics
112    ///
113    /// Panics if the internal ID string does not contain a '-' separator.
114    #[must_use]
115    pub fn get_tag(&self) -> &str {
116        self.0.split('-').next_back().unwrap()
117    }
118
119    /// Creates an external trader ID used for orders from external sources.
120    #[must_use]
121    pub fn external() -> Self {
122        Self::new(EXTERNAL_TRADER_ID)
123    }
124
125    /// Returns whether this trader ID is external.
126    #[must_use]
127    pub fn is_external(&self) -> bool {
128        self.0 == EXTERNAL_TRADER_ID
129    }
130}
131
132impl Default for TraderId {
133    /// Returns the default trader ID "TRADER-001".
134    fn default() -> Self {
135        Self::from("TRADER-001")
136    }
137}
138
139impl Debug for TraderId {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        write!(f, "\"{}\"", self.0)
142    }
143}
144
145impl Display for TraderId {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        write!(f, "{}", self.0)
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use nautilus_core::correctness::CorrectnessError;
154    use rstest::rstest;
155
156    use crate::identifiers::{stubs::*, trader_id::TraderId};
157
158    #[rstest]
159    fn test_string_reprs(trader_id: TraderId) {
160        assert_eq!(trader_id.as_str(), "TRADER-001");
161        assert_eq!(format!("{trader_id}"), "TRADER-001");
162    }
163
164    #[rstest]
165    fn test_get_tag(trader_id: TraderId) {
166        assert_eq!(trader_id.get_tag(), "001");
167    }
168
169    #[rstest]
170    fn test_external() {
171        let external = TraderId::external();
172        let local = TraderId::new("TRADER-001");
173
174        assert_eq!(external.as_str(), "EXTERNAL-0");
175        assert!(external.is_external());
176        assert!(!local.is_external());
177    }
178
179    #[rstest]
180    #[should_panic(expected = "name part (before '-') cannot be empty")]
181    fn test_new_with_empty_name_panics() {
182        let _ = TraderId::new("-001");
183    }
184
185    #[rstest]
186    #[should_panic(expected = "tag part (after '-') cannot be empty")]
187    fn test_new_with_empty_tag_panics() {
188        let _ = TraderId::new("TRADER-");
189    }
190
191    #[rstest]
192    fn test_new_checked_without_separator_returns_typed_error() {
193        let error = TraderId::new_checked("TRADER001").unwrap_err();
194
195        assert_eq!(
196            error,
197            CorrectnessError::MissingSubstring {
198                param: "value".to_string(),
199                pattern: "-".to_string(),
200                value: "TRADER001".to_string(),
201            }
202        );
203        assert_eq!(
204            error.to_string(),
205            "invalid string for 'value' did not contain '-', was 'TRADER001'"
206        );
207    }
208
209    #[rstest]
210    #[case("-001", "`value` name part (before '-') cannot be empty")]
211    #[case("TRADER-", "`value` tag part (after '-') cannot be empty")]
212    fn test_new_checked_with_empty_component_returns_typed_error(
213        #[case] value: &str,
214        #[case] expected: &str,
215    ) {
216        let error = TraderId::new_checked(value).unwrap_err();
217
218        assert_eq!(
219            error,
220            CorrectnessError::PredicateViolation {
221                message: expected.to_string(),
222            }
223        );
224        assert_eq!(error.to_string(), expected);
225    }
226}