nautilus_model/identifiers/
client_order_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 client order ID (assigned by the Posei system).
17
18use std::{
19    fmt::{Debug, Display, Formatter},
20    hash::Hash,
21};
22
23use nautilus_core::correctness::{FAILED, check_valid_string};
24use ustr::Ustr;
25
26/// Represents a valid client order ID (assigned by the Posei system).
27#[repr(C)]
28#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.model")
32)]
33pub struct ClientOrderId(Ustr);
34
35impl ClientOrderId {
36    /// Creates a new [`ClientOrderId`] instance with correctness checking.
37    ///
38    /// # Errors
39    ///
40    /// Returns an error if `value` is not a valid string.
41    ///
42    /// # Notes
43    ///
44    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
45    pub fn new_checked<T: AsRef<str>>(value: T) -> anyhow::Result<Self> {
46        let value = value.as_ref();
47        check_valid_string(value, stringify!(value))?;
48        Ok(Self(Ustr::from(value)))
49    }
50
51    /// Creates a new [`ClientOrderId`] instance.
52    ///
53    /// # Panics
54    ///
55    /// Panics if `value` is not a valid string.
56    pub fn new<T: AsRef<str>>(value: T) -> Self {
57        Self::new_checked(value).expect(FAILED)
58    }
59
60    /// Sets the inner identifier value.
61    #[allow(dead_code)]
62    pub(crate) fn set_inner(&mut self, value: &str) {
63        self.0 = Ustr::from(value);
64    }
65
66    /// Returns the inner identifier value.
67    #[must_use]
68    pub fn inner(&self) -> Ustr {
69        self.0
70    }
71
72    /// Returns the inner identifier value as a string slice.
73    #[must_use]
74    pub fn as_str(&self) -> &str {
75        self.0.as_str()
76    }
77}
78
79impl Debug for ClientOrderId {
80    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
81        write!(f, "{:?}", self.0)
82    }
83}
84
85impl Display for ClientOrderId {
86    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
87        write!(f, "{}", self.0)
88    }
89}
90
91#[must_use]
92pub fn optional_ustr_to_vec_client_order_ids(s: Option<Ustr>) -> Option<Vec<ClientOrderId>> {
93    s.map(|ustr| {
94        let s_str = ustr.to_string();
95        s_str
96            .split(',')
97            .map(ClientOrderId::new)
98            .collect::<Vec<ClientOrderId>>()
99    })
100}
101
102#[must_use]
103pub fn optional_vec_client_order_ids_to_ustr(vec: Option<Vec<ClientOrderId>>) -> Option<Ustr> {
104    vec.map(|client_order_ids| {
105        let s: String = client_order_ids
106            .into_iter()
107            .map(|id| id.to_string())
108            .collect::<Vec<String>>()
109            .join(",");
110        Ustr::from(&s)
111    })
112}
113
114////////////////////////////////////////////////////////////////////////////////
115// Tests
116////////////////////////////////////////////////////////////////////////////////
117#[cfg(test)]
118mod tests {
119    use rstest::rstest;
120    use ustr::Ustr;
121
122    use super::ClientOrderId;
123    use crate::identifiers::{
124        client_order_id::{
125            optional_ustr_to_vec_client_order_ids, optional_vec_client_order_ids_to_ustr,
126        },
127        stubs::*,
128    };
129
130    #[rstest]
131    fn test_string_reprs(client_order_id: ClientOrderId) {
132        assert_eq!(client_order_id.as_str(), "O-19700101-000000-001-001-1");
133        assert_eq!(format!("{client_order_id}"), "O-19700101-000000-001-001-1");
134    }
135
136    #[rstest]
137    fn test_optional_ustr_to_vec_client_order_ids() {
138        // Test with None
139        assert_eq!(optional_ustr_to_vec_client_order_ids(None), None);
140
141        // Test with Some
142        let ustr = Ustr::from("id1,id2,id3");
143        let client_order_ids = optional_ustr_to_vec_client_order_ids(Some(ustr)).unwrap();
144        assert_eq!(client_order_ids[0].as_str(), "id1");
145        assert_eq!(client_order_ids[1].as_str(), "id2");
146        assert_eq!(client_order_ids[2].as_str(), "id3");
147    }
148
149    #[rstest]
150    fn test_optional_vec_client_order_ids_to_ustr() {
151        // Test with None
152        assert_eq!(optional_vec_client_order_ids_to_ustr(None), None);
153
154        // Test with Some
155        let client_order_ids = vec![
156            ClientOrderId::from("id1"),
157            ClientOrderId::from("id2"),
158            ClientOrderId::from("id3"),
159        ];
160        let ustr = optional_vec_client_order_ids_to_ustr(Some(client_order_ids)).unwrap();
161        assert_eq!(ustr.to_string(), "id1,id2,id3");
162    }
163}