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]
32impl TradeId {
33 #[new]
34 fn py_new(value: &str) -> PyResult<Self> {
35 Self::new_checked(value).map_err(to_pyvalue_err)
36 }
37
38 fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
39 let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
40 let binding = py_tuple.get_item(0)?;
41 let value_str = binding.cast::<PyString>()?.extract::<&str>()?;
42 *self = Self::new(value_str);
43 Ok(())
44 }
45
46 fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
47 (self.to_string(),).into_py_any(py)
48 }
49
50 fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
51 let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
52 let state = self.__getstate__(py)?;
53 (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
54 }
55
56 #[staticmethod]
57 fn _safe_constructor() -> Self {
58 Self::from("NULL")
59 }
60
61 fn __richcmp__(&self, other: Py<PyAny>, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
62 if let Ok(other) = other.extract::<Self>(py) {
63 match op {
64 CompareOp::Eq => self.eq(&other).into_py_any_unwrap(py),
65 CompareOp::Ne => self.ne(&other).into_py_any_unwrap(py),
66 CompareOp::Ge => self.ge(&other).into_py_any_unwrap(py),
67 CompareOp::Gt => self.gt(&other).into_py_any_unwrap(py),
68 CompareOp::Le => self.le(&other).into_py_any_unwrap(py),
69 CompareOp::Lt => self.lt(&other).into_py_any_unwrap(py),
70 }
71 } else {
72 py.NotImplemented()
73 }
74 }
75
76 fn __hash__(&self) -> isize {
77 let mut h = DefaultHasher::new();
78 self.hash(&mut h);
79 h.finish() as isize
80 }
81
82 fn __repr__(&self) -> String {
83 format!("{}('{}')", stringify!(TradeId), self)
84 }
85
86 fn __str__(&self) -> String {
87 self.to_string()
88 }
89
90 #[getter]
91 fn value(&self) -> &str {
92 self.as_str()
93 }
94
95 #[staticmethod]
96 #[pyo3(name = "from_str")]
97 fn py_from_str(value: &str) -> PyResult<Self> {
98 Self::new_checked(value).map_err(to_pyvalue_err)
99 }
100}