nautilus_model/identifiers/
position_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 position ID.
17
18use std::{
19    fmt::{Debug, Display, Formatter},
20    hash::Hash,
21};
22
23use nautilus_core::correctness::{check_valid_string, FAILED};
24use ustr::Ustr;
25
26/// Represents a valid position ID.
27#[repr(C)]
28#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model")
32)]
33pub struct PositionId(Ustr);
34
35impl PositionId {
36    /// Creates a new [`PositionId`] instance with correctness checking.
37    ///
38    /// # Errors
39    ///
40    /// This function returns an error:
41    /// - If `value` is not a valid string.
42    ///
43    /// # Notes
44    ///
45    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
46    pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
47        let value = value.as_ref();
48        check_valid_string(value, stringify!(value))?;
49        Ok(Self(Ustr::from(value)))
50    }
51
52    /// Creates a new [`PositionId`] instance.
53    ///
54    /// # Panics
55    ///
56    /// This function panics:
57    /// - If `value` is not a valid string.
58    pub fn new<T: AsRef<str>>(value: T) -> Self {
59        Self::new_checked(value).expect(FAILED)
60    }
61
62    /// Sets the inner identifier value.
63    pub(crate) fn set_inner(&mut self, value: &str) {
64        self.0 = Ustr::from(value);
65    }
66
67    /// Returns the inner identifier value.
68    #[must_use]
69    pub fn inner(&self) -> Ustr {
70        self.0
71    }
72
73    /// Returns the inner identifier value as a string slice.
74    #[must_use]
75    pub fn as_str(&self) -> &str {
76        self.0.as_str()
77    }
78
79    /// Checks if the position ID is virtual.
80    ///
81    /// Returns `true` if the position ID starts with "P-", otherwise `false`.
82    #[must_use]
83    pub fn is_virtual(&self) -> bool {
84        self.0.starts_with("P-")
85    }
86}
87
88impl Debug for PositionId {
89    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
90        write!(f, "{:?}", self.0)
91    }
92}
93impl Display for PositionId {
94    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
95        write!(f, "{}", self.0)
96    }
97}
98
99////////////////////////////////////////////////////////////////////////////////
100// Tests
101////////////////////////////////////////////////////////////////////////////////
102#[cfg(test)]
103mod tests {
104    use rstest::rstest;
105
106    use super::PositionId;
107    use crate::identifiers::stubs::*;
108
109    #[rstest]
110    fn test_string_reprs(position_id_test: PositionId) {
111        assert_eq!(position_id_test.as_str(), "P-123456789");
112        assert_eq!(format!("{position_id_test}"), "P-123456789");
113    }
114}