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