nautilus_model/identifiers/trader_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 trader 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/// 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 /// This function returns an error:
47 /// - If `value` is not a valid string, or does not contain a hyphen '-' separator.
48 ///
49 /// # Notes
50 ///
51 /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
52 pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
53 let value = value.as_ref();
54 check_valid_string(value, stringify!(value))?;
55 check_string_contains(value, "-", stringify!(value))?;
56 Ok(Self(Ustr::from(value)))
57 }
58
59 /// Creates a new [`TraderId`] instance.
60 ///
61 /// # Panics
62 ///
63 /// This function panics:
64 /// - If `value` is not a valid string, or does not contain a hyphen '-' separator.
65 pub fn new<T: AsRef<str>>(value: T) -> Self {
66 Self::new_checked(value).expect(FAILED)
67 }
68
69 /// Sets the inner identifier value.
70 pub(crate) fn set_inner(&mut self, value: &str) {
71 self.0 = Ustr::from(value);
72 }
73
74 /// Returns the inner identifier value.
75 #[must_use]
76 pub fn inner(&self) -> Ustr {
77 self.0
78 }
79
80 /// Returns the inner identifier value as a string slice.
81 #[must_use]
82 pub fn as_str(&self) -> &str {
83 self.0.as_str()
84 }
85
86 #[must_use]
87 pub fn get_tag(&self) -> &str {
88 // SAFETY: Unwrap safe as value previously validated
89 self.0.split('-').last().unwrap()
90 }
91}
92
93impl Debug for TraderId {
94 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
95 write!(f, "{:?}", self.0)
96 }
97}
98
99impl Display for TraderId {
100 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
101 write!(f, "{}", self.0)
102 }
103}
104
105////////////////////////////////////////////////////////////////////////////////
106// Tests
107////////////////////////////////////////////////////////////////////////////////
108#[cfg(test)]
109mod tests {
110 use rstest::rstest;
111
112 use crate::identifiers::{stubs::*, trader_id::TraderId};
113
114 #[rstest]
115 fn test_string_reprs(trader_id: TraderId) {
116 assert_eq!(trader_id.as_str(), "TRADER-001");
117 assert_eq!(format!("{trader_id}"), "TRADER-001");
118 }
119
120 #[rstest]
121 fn test_get_tag(trader_id: TraderId) {
122 assert_eq!(trader_id.get_tag(), "001");
123 }
124}