Skip to main content

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::{
24    CorrectnessResult, CorrectnessResultExt, FAILED, check_valid_string_ascii,
25};
26use ustr::Ustr;
27
28/// Represents a valid client order ID (assigned by the Nautilus system).
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", from_py_object)
34)]
35#[cfg_attr(
36    feature = "python",
37    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
38)]
39pub struct ClientOrderId(Ustr);
40
41impl ClientOrderId {
42    /// Creates a new [`ClientOrderId`] instance with correctness checking.
43    ///
44    /// # Errors
45    ///
46    /// Returns an error if `value` is not a valid string.
47    ///
48    /// # Notes
49    ///
50    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
51    pub fn new_checked<T: AsRef<str>>(value: T) -> CorrectnessResult<Self> {
52        let value = value.as_ref();
53        check_valid_string_ascii(value, stringify!(value))?;
54        Ok(Self(Ustr::from(value)))
55    }
56
57    /// Creates a new [`ClientOrderId`] instance.
58    ///
59    /// # Panics
60    ///
61    /// Panics if `value` is not a valid string.
62    pub fn new<T: AsRef<str>>(value: T) -> Self {
63        Self::new_checked(value).expect_display(FAILED)
64    }
65
66    /// Sets the inner identifier value.
67    #[cfg_attr(not(feature = "python"), allow(dead_code))]
68    pub(crate) fn set_inner(&mut self, value: &str) {
69        self.0 = Ustr::from(value);
70    }
71
72    /// Returns the inner identifier value.
73    #[must_use]
74    pub fn inner(&self) -> Ustr {
75        self.0
76    }
77
78    /// Returns the inner identifier value as a string slice.
79    #[must_use]
80    pub fn as_str(&self) -> &str {
81        self.0.as_str()
82    }
83
84    /// Creates an external client order ID used when no ID was provided.
85    #[must_use]
86    pub fn external() -> Self {
87        Self::new("EXTERNAL")
88    }
89
90    /// Returns whether this client order ID is external.
91    #[must_use]
92    pub fn is_external(&self) -> bool {
93        self.0.as_str() == "EXTERNAL"
94    }
95}
96
97impl Debug for ClientOrderId {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        write!(f, "\"{}\"", self.0)
100    }
101}
102
103impl Display for ClientOrderId {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        write!(f, "{}", self.0)
106    }
107}
108
109#[must_use]
110pub fn optional_ustr_to_vec_client_order_ids(s: Option<Ustr>) -> Option<Vec<ClientOrderId>> {
111    s.map(|ustr| {
112        let s_str = ustr.to_string();
113        s_str
114            .split(',')
115            .map(ClientOrderId::new)
116            .collect::<Vec<ClientOrderId>>()
117    })
118}
119
120#[must_use]
121pub fn optional_vec_client_order_ids_to_ustr(vec: Option<Vec<ClientOrderId>>) -> Option<Ustr> {
122    vec.map(|client_order_ids| {
123        let s: String = client_order_ids
124            .into_iter()
125            .map(|id| id.to_string())
126            .collect::<Vec<String>>()
127            .join(",");
128        Ustr::from(&s)
129    })
130}
131
132#[cfg(test)]
133mod tests {
134    use rstest::rstest;
135    use ustr::Ustr;
136
137    use super::ClientOrderId;
138    use crate::identifiers::{
139        client_order_id::{
140            optional_ustr_to_vec_client_order_ids, optional_vec_client_order_ids_to_ustr,
141        },
142        stubs::*,
143    };
144
145    #[rstest]
146    fn test_string_reprs(client_order_id: ClientOrderId) {
147        assert_eq!(client_order_id.as_str(), "O-19700101-000000-001-001-1");
148        assert_eq!(format!("{client_order_id}"), "O-19700101-000000-001-001-1");
149    }
150
151    #[rstest]
152    #[should_panic(expected = "Condition failed: invalid string for 'value', was empty")]
153    fn test_new_with_empty_string_panics_with_display_format() {
154        let _ = ClientOrderId::new("");
155    }
156
157    #[rstest]
158    fn test_optional_ustr_to_vec_client_order_ids() {
159        // Test with None
160        assert_eq!(optional_ustr_to_vec_client_order_ids(None), None);
161
162        // Test with Some
163        let ustr = Ustr::from("id1,id2,id3");
164        let client_order_ids = optional_ustr_to_vec_client_order_ids(Some(ustr)).unwrap();
165        assert_eq!(client_order_ids[0].as_str(), "id1");
166        assert_eq!(client_order_ids[1].as_str(), "id2");
167        assert_eq!(client_order_ids[2].as_str(), "id3");
168    }
169
170    #[rstest]
171    fn test_optional_vec_client_order_ids_to_ustr() {
172        // Test with None
173        assert_eq!(optional_vec_client_order_ids_to_ustr(None), None);
174
175        // Test with Some
176        let client_order_ids = vec![
177            ClientOrderId::from("id1"),
178            ClientOrderId::from("id2"),
179            ClientOrderId::from("id3"),
180        ];
181        let ustr = optional_vec_client_order_ids_to_ustr(Some(client_order_ids)).unwrap();
182        assert_eq!(ustr.to_string(), "id1,id2,id3");
183    }
184}