nautilus_model/python/identifiers/
trade_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
16use std::{
17    collections::hash_map::DefaultHasher,
18    ffi::CString,
19    hash::{Hash, Hasher},
20};
21
22use nautilus_core::python::{IntoPyObjectNautilusExt, to_pyvalue_err};
23use pyo3::{
24    IntoPyObjectExt,
25    prelude::*,
26    pyclass::CompareOp,
27    types::{PyString, PyTuple},
28};
29
30use crate::identifiers::trade_id::{TRADE_ID_LEN, TradeId};
31
32#[pymethods]
33impl TradeId {
34    #[new]
35    fn py_new(value: &str) -> PyResult<Self> {
36        Self::new_checked(value).map_err(to_pyvalue_err)
37    }
38
39    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
40        let py_tuple: &Bound<'_, PyTuple> = state.downcast::<PyTuple>()?;
41        let binding = py_tuple.get_item(0)?;
42        let value_str = binding.downcast::<PyString>()?.extract::<&str>()?;
43
44        // TODO: Extract this to single function
45        let c_string = CString::new(value_str).expect("`CString` conversion failed");
46        let bytes = c_string.as_bytes_with_nul();
47        let mut value = [0; TRADE_ID_LEN];
48        value[..bytes.len()].copy_from_slice(bytes);
49        self.value = value;
50
51        Ok(())
52    }
53
54    fn __getstate__(&self, py: Python) -> PyResult<PyObject> {
55        (self.to_string(),).into_py_any(py)
56    }
57
58    fn __reduce__(&self, py: Python) -> PyResult<PyObject> {
59        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
60        let state = self.__getstate__(py)?;
61        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
62    }
63
64    #[staticmethod]
65    fn _safe_constructor() -> Self {
66        Self::from("NULL")
67    }
68
69    fn __richcmp__(&self, other: PyObject, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
70        if let Ok(other) = other.extract::<Self>(py) {
71            match op {
72                CompareOp::Eq => self.eq(&other).into_py_any_unwrap(py),
73                CompareOp::Ne => self.ne(&other).into_py_any_unwrap(py),
74                CompareOp::Ge => self.ge(&other).into_py_any_unwrap(py),
75                CompareOp::Gt => self.gt(&other).into_py_any_unwrap(py),
76                CompareOp::Le => self.le(&other).into_py_any_unwrap(py),
77                CompareOp::Lt => self.lt(&other).into_py_any_unwrap(py),
78            }
79        } else {
80            py.NotImplemented()
81        }
82    }
83
84    fn __hash__(&self) -> isize {
85        let mut h = DefaultHasher::new();
86        self.hash(&mut h);
87        h.finish() as isize
88    }
89
90    fn __repr__(&self) -> String {
91        format!("{}('{}')", stringify!(TradeId), self)
92    }
93
94    fn __str__(&self) -> String {
95        self.to_string()
96    }
97
98    #[getter]
99    fn value(&self) -> String {
100        self.to_string()
101    }
102
103    #[staticmethod]
104    #[pyo3(name = "from_str")]
105    fn py_from_str(value: &str) -> PyResult<Self> {
106        Self::new_checked(value).map_err(to_pyvalue_err)
107    }
108}