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