nautilus_model/identifiers/
account_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 account ID.
17
18use std::{
19    fmt::{Debug, Display, Formatter},
20    hash::Hash,
21};
22
23use nautilus_core::correctness::{FAILED, check_string_contains, check_valid_string};
24use ustr::Ustr;
25
26use super::Venue;
27
28/// Represents a valid account 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.core.nautilus_pyo3.model")
34)]
35pub struct AccountId(Ustr);
36
37impl AccountId {
38    /// Creates a new [`AccountId`] instance with correctness checking.
39    ///
40    /// Must be correctly formatted with two valid strings either side of a hyphen '-'.
41    ///
42    /// It is expected an account ID is the name of the issuer with an account number
43    /// separated by a hyphen.
44    ///
45    /// # Errors
46    ///
47    /// This function returns an error:
48    /// - If `value` is not a valid string.
49    /// - If `value` length is greater than 36.
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(value, stringify!(value))?;
57        check_string_contains(value, "-", stringify!(value))?;
58        Ok(Self(Ustr::from(value)))
59    }
60
61    /// Creates a new [`AccountId`] instance.
62    ///
63    /// # Panics
64    ///
65    /// This function panics:
66    /// - If `value` is not a valid string, or value length is greater than 36.
67    pub fn new<T: AsRef<str>>(value: T) -> Self {
68        Self::new_checked(value).expect(FAILED)
69    }
70
71    /// Sets the inner identifier value.
72    #[allow(dead_code)]
73    pub(crate) fn set_inner(&mut self, value: &str) {
74        self.0 = Ustr::from(value);
75    }
76
77    /// Returns the inner identifier value.
78    #[must_use]
79    pub fn inner(&self) -> Ustr {
80        self.0
81    }
82
83    /// Returns the inner identifier value as a string slice.
84    #[must_use]
85    pub fn as_str(&self) -> &str {
86        self.0.as_str()
87    }
88
89    /// Returns the account issuer for this identifier.
90    #[must_use]
91    pub fn get_issuer(&self) -> Venue {
92        // SAFETY: Account ID is guaranteed to have chars either side of a hyphen
93        Venue::from_str_unchecked(self.0.split_once('-').unwrap().0)
94    }
95
96    /// Returns the account ID assigned by the issuer.
97    #[must_use]
98    pub fn get_issuers_id(&self) -> &str {
99        // SAFETY: Account ID is guaranteed to have chars either side of a hyphen
100        self.0.split_once('-').unwrap().1
101    }
102}
103
104impl Debug for AccountId {
105    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
106        write!(f, "{:?}", self.0)
107    }
108}
109
110impl Display for AccountId {
111    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
112        write!(f, "{}", self.0)
113    }
114}
115
116////////////////////////////////////////////////////////////////////////////////
117// Tests
118////////////////////////////////////////////////////////////////////////////////
119#[cfg(test)]
120mod tests {
121    use rstest::rstest;
122
123    use super::*;
124    use crate::identifiers::stubs::*;
125
126    #[rstest]
127    #[should_panic]
128    fn test_account_id_new_invalid_string() {
129        AccountId::new("");
130    }
131
132    #[rstest]
133    #[should_panic]
134    fn test_account_id_new_missing_hyphen() {
135        AccountId::new("123456789");
136    }
137
138    #[rstest]
139    fn test_account_id_fmt() {
140        let s = "IB-U123456789";
141        let account_id = AccountId::new(s);
142        let formatted = format!("{account_id}");
143        assert_eq!(formatted, s);
144    }
145
146    #[rstest]
147    fn test_string_reprs(account_ib: AccountId) {
148        assert_eq!(account_ib.as_str(), "IB-1234567890");
149    }
150
151    #[rstest]
152    fn test_get_issuer(account_ib: AccountId) {
153        assert_eq!(account_ib.get_issuer(), Venue::new("IB"));
154    }
155
156    #[rstest]
157    fn test_get_issuers_id(account_ib: AccountId) {
158        assert_eq!(account_ib.get_issuers_id(), "1234567890");
159    }
160}