nautilus_model/identifiers/
account_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 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 = "posei_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    /// Returns an error if:
48    /// - `value` is not a valid string.
49    /// - `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    /// Panics if `value` is not a valid string, or value length is greater than 36.
66    pub fn new<T: AsRef<str>>(value: T) -> Self {
67        Self::new_checked(value).expect(FAILED)
68    }
69
70    /// Sets the inner identifier value.
71    #[allow(dead_code)]
72    pub(crate) fn set_inner(&mut self, value: &str) {
73        self.0 = Ustr::from(value);
74    }
75
76    /// Returns the inner identifier value.
77    #[must_use]
78    pub fn inner(&self) -> Ustr {
79        self.0
80    }
81
82    /// Returns the inner identifier value as a string slice.
83    #[must_use]
84    pub fn as_str(&self) -> &str {
85        self.0.as_str()
86    }
87
88    /// Returns the account issuer for this identifier.
89    ///
90    /// # Panics
91    ///
92    /// Panics if the internal ID does not contain a hyphen separator.
93    #[must_use]
94    pub fn get_issuer(&self) -> Venue {
95        // SAFETY: Account ID is guaranteed to have chars either side of a hyphen
96        Venue::from_str_unchecked(self.0.split_once('-').unwrap().0)
97    }
98
99    /// Returns the account ID assigned by the issuer.
100    ///
101    /// # Panics
102    ///
103    /// Panics if the internal ID does not contain a hyphen separator.
104    #[must_use]
105    pub fn get_issuers_id(&self) -> &str {
106        // SAFETY: Account ID is guaranteed to have chars either side of a hyphen
107        self.0.split_once('-').unwrap().1
108    }
109}
110
111impl Debug for AccountId {
112    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
113        write!(f, "{:?}", self.0)
114    }
115}
116
117impl Display for AccountId {
118    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
119        write!(f, "{}", self.0)
120    }
121}
122
123////////////////////////////////////////////////////////////////////////////////
124// Tests
125////////////////////////////////////////////////////////////////////////////////
126#[cfg(test)]
127mod tests {
128    use rstest::rstest;
129
130    use super::*;
131    use crate::identifiers::stubs::*;
132
133    #[rstest]
134    #[should_panic]
135    fn test_account_id_new_invalid_string() {
136        AccountId::new("");
137    }
138
139    #[rstest]
140    #[should_panic]
141    fn test_account_id_new_missing_hyphen() {
142        AccountId::new("123456789");
143    }
144
145    #[rstest]
146    fn test_account_id_fmt() {
147        let s = "IB-U123456789";
148        let account_id = AccountId::new(s);
149        let formatted = format!("{account_id}");
150        assert_eq!(formatted, s);
151    }
152
153    #[rstest]
154    fn test_string_reprs(account_ib: AccountId) {
155        assert_eq!(account_ib.as_str(), "IB-1234567890");
156    }
157
158    #[rstest]
159    fn test_get_issuer(account_ib: AccountId) {
160        assert_eq!(account_ib.get_issuer(), Venue::new("IB"));
161    }
162
163    #[rstest]
164    fn test_get_issuers_id(account_ib: AccountId) {
165        assert_eq!(account_ib.get_issuers_id(), "1234567890");
166    }
167}