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::{FAILED, check_string_contains, check_valid_string_ascii};
21use ustr::Ustr;
22
23/// Represents a valid trader ID.
24#[repr(C)]
25#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
26#[cfg_attr(
27    feature = "python",
28    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model")
29)]
30pub struct TraderId(Ustr);
31
32impl TraderId {
33    /// Creates a new [`TraderId`] instance.
34    ///
35    /// Must be correctly formatted with two valid strings either side of a hyphen.
36    /// It is expected a trader ID is the abbreviated name of the trader
37    /// with an order ID tag number separated by a hyphen.
38    ///
39    /// Example: "TESTER-001".
40    ///
41    /// The reason for the numerical component of the ID is so that order and position IDs
42    /// do not collide with those from another node instance.
43    ///
44    /// # Errors
45    ///
46    /// Returns an error if:
47    /// - `value` is not a valid ASCII string.
48    /// - `value` does not contain a hyphen '-' separator.
49    /// - Either the name or tag part (before/after the hyphen) is empty.
50    ///
51    /// # Notes
52    ///
53    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
54    pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
55        let value = value.as_ref();
56        check_valid_string_ascii(value, stringify!(value))?;
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 [`TraderId`] instance.
74    ///
75    /// # Panics
76    ///
77    /// Panics if `value` is not a valid string, or does not contain a hyphen '-' separator.
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    /// Returns the numerical tag portion of the trader ID.
101    ///
102    /// # Panics
103    ///
104    /// Panics if the internal ID string does not contain a '-' separator.
105    #[must_use]
106    pub fn get_tag(&self) -> &str {
107        // SAFETY: Unwrap safe as value previously validated
108        self.0.split('-').next_back().unwrap()
109    }
110
111    /// Creates an external trader ID used for orders from external sources.
112    #[must_use]
113    pub fn external() -> Self {
114        // SAFETY: Constant value is safe
115        Self::new("EXTERNAL-0")
116    }
117
118    /// Returns whether this trader ID is external.
119    #[must_use]
120    pub fn is_external(&self) -> bool {
121        self.0.as_str() == "EXTERNAL-0"
122    }
123}
124
125impl Default for TraderId {
126    /// Returns the default trader ID "TRADER-001".
127    fn default() -> Self {
128        Self::from("TRADER-001")
129    }
130}
131
132impl Debug for TraderId {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        write!(f, "\"{}\"", self.0)
135    }
136}
137
138impl Display for TraderId {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        write!(f, "{}", self.0)
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use rstest::rstest;
147
148    use crate::identifiers::{stubs::*, trader_id::TraderId};
149
150    #[rstest]
151    fn test_string_reprs(trader_id: TraderId) {
152        assert_eq!(trader_id.as_str(), "TRADER-001");
153        assert_eq!(format!("{trader_id}"), "TRADER-001");
154    }
155
156    #[rstest]
157    fn test_get_tag(trader_id: TraderId) {
158        assert_eq!(trader_id.get_tag(), "001");
159    }
160
161    #[rstest]
162    #[should_panic(expected = "name part (before '-') cannot be empty")]
163    fn test_new_with_empty_name_panics() {
164        let _ = TraderId::new("-001");
165    }
166
167    #[rstest]
168    #[should_panic(expected = "tag part (after '-') cannot be empty")]
169    fn test_new_with_empty_tag_panics() {
170        let _ = TraderId::new("TRADER-");
171    }
172
173    #[rstest]
174    fn test_new_checked_with_empty_name_returns_error() {
175        assert!(TraderId::new_checked("-001").is_err());
176    }
177
178    #[rstest]
179    fn test_new_checked_with_empty_tag_returns_error() {
180        assert!(TraderId::new_checked("TRADER-").is_err());
181    }
182}