nautilus_model/identifiers/
client_order_id.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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 client order ID (assigned by the Nautilus system).
17
18use std::{
19    fmt::{Debug, Display},
20    hash::Hash,
21};
22
23use nautilus_core::correctness::{FAILED, check_valid_string_ascii};
24use ustr::Ustr;
25
26/// Represents a valid client order ID (assigned by the Nautilus system).
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 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_ascii(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    #[cfg_attr(not(feature = "python"), 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    /// Creates an external client order ID used when no ID was provided.
79    #[must_use]
80    pub fn external() -> Self {
81        // SAFETY: Constant value is safe
82        Self::new("EXTERNAL")
83    }
84
85    /// Returns whether this client order ID is external.
86    #[must_use]
87    pub fn is_external(&self) -> bool {
88        self.0.as_str() == "EXTERNAL"
89    }
90}
91
92impl Debug for ClientOrderId {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        write!(f, "\"{}\"", self.0)
95    }
96}
97
98impl Display for ClientOrderId {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        write!(f, "{}", self.0)
101    }
102}
103
104#[must_use]
105pub fn optional_ustr_to_vec_client_order_ids(s: Option<Ustr>) -> Option<Vec<ClientOrderId>> {
106    s.map(|ustr| {
107        let s_str = ustr.to_string();
108        s_str
109            .split(',')
110            .map(ClientOrderId::new)
111            .collect::<Vec<ClientOrderId>>()
112    })
113}
114
115#[must_use]
116pub fn optional_vec_client_order_ids_to_ustr(vec: Option<Vec<ClientOrderId>>) -> Option<Ustr> {
117    vec.map(|client_order_ids| {
118        let s: String = client_order_ids
119            .into_iter()
120            .map(|id| id.to_string())
121            .collect::<Vec<String>>()
122            .join(",");
123        Ustr::from(&s)
124    })
125}
126
127#[cfg(test)]
128mod tests {
129    use rstest::rstest;
130    use ustr::Ustr;
131
132    use super::ClientOrderId;
133    use crate::identifiers::{
134        client_order_id::{
135            optional_ustr_to_vec_client_order_ids, optional_vec_client_order_ids_to_ustr,
136        },
137        stubs::*,
138    };
139
140    #[rstest]
141    fn test_string_reprs(client_order_id: ClientOrderId) {
142        assert_eq!(client_order_id.as_str(), "O-19700101-000000-001-001-1");
143        assert_eq!(format!("{client_order_id}"), "O-19700101-000000-001-001-1");
144    }
145
146    #[rstest]
147    fn test_optional_ustr_to_vec_client_order_ids() {
148        // Test with None
149        assert_eq!(optional_ustr_to_vec_client_order_ids(None), None);
150
151        // Test with Some
152        let ustr = Ustr::from("id1,id2,id3");
153        let client_order_ids = optional_ustr_to_vec_client_order_ids(Some(ustr)).unwrap();
154        assert_eq!(client_order_ids[0].as_str(), "id1");
155        assert_eq!(client_order_ids[1].as_str(), "id2");
156        assert_eq!(client_order_ids[2].as_str(), "id3");
157    }
158
159    #[rstest]
160    fn test_optional_vec_client_order_ids_to_ustr() {
161        // Test with None
162        assert_eq!(optional_vec_client_order_ids_to_ustr(None), None);
163
164        // Test with Some
165        let client_order_ids = vec![
166            ClientOrderId::from("id1"),
167            ClientOrderId::from("id2"),
168            ClientOrderId::from("id3"),
169        ];
170        let ustr = optional_vec_client_order_ids_to_ustr(Some(client_order_ids)).unwrap();
171        assert_eq!(ustr.to_string(), "id1,id2,id3");
172    }
173}