nautilus_model/python/identifiers/
instrument_id.rs1use std::{
17 collections::hash_map::DefaultHasher,
18 hash::{Hash, Hasher},
19 str::FromStr,
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::{InstrumentId, Symbol, Venue};
31
32#[pymethods]
33#[pyo3_stub_gen::derive::gen_stub_pymethods]
34impl InstrumentId {
35 #[new]
39 fn py_new(symbol: Symbol, venue: Venue) -> Self {
40 Self::new(symbol, venue)
41 }
42
43 fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
44 let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
45 self.symbol = Symbol::new_checked(
46 py_tuple
47 .get_item(0)?
48 .cast::<PyString>()?
49 .extract::<&str>()?,
50 )
51 .map_err(to_pyvalue_err)?;
52 self.venue = Venue::new_checked(
53 py_tuple
54 .get_item(1)?
55 .cast::<PyString>()?
56 .extract::<&str>()?,
57 )
58 .map_err(to_pyvalue_err)?;
59 Ok(())
60 }
61
62 fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
63 (self.symbol.to_string(), self.venue.to_string()).into_py_any(py)
64 }
65
66 fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
67 let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
68 let state = self.__getstate__(py)?;
69 (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
70 }
71
72 #[staticmethod]
73 fn _safe_constructor() -> Self {
74 Self::from_str("NULL.NULL").unwrap() }
76
77 #[expect(clippy::needless_pass_by_value)]
78 fn __richcmp__(&self, other: Py<PyAny>, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
79 if let Ok(other) = other.extract::<Self>(py) {
80 match op {
81 CompareOp::Eq => self.eq(&other).into_py_any_unwrap(py),
82 CompareOp::Ne => self.ne(&other).into_py_any_unwrap(py),
83 CompareOp::Ge => self.ge(&other).into_py_any_unwrap(py),
84 CompareOp::Gt => self.gt(&other).into_py_any_unwrap(py),
85 CompareOp::Le => self.le(&other).into_py_any_unwrap(py),
86 CompareOp::Lt => self.lt(&other).into_py_any_unwrap(py),
87 }
88 } else {
89 py.NotImplemented()
90 }
91 }
92
93 fn __hash__(&self) -> isize {
94 let mut h = DefaultHasher::new();
95 self.hash(&mut h);
96 h.finish() as isize
97 }
98
99 fn __repr__(&self) -> String {
100 format!("{}('{}')", stringify!(InstrumentId), self)
101 }
102
103 fn __str__(&self) -> String {
104 self.to_string()
105 }
106
107 #[getter]
108 #[pyo3(name = "symbol")]
109 fn py_symbol(&self) -> Symbol {
110 self.symbol
111 }
112
113 #[getter]
114 #[pyo3(name = "venue")]
115 fn py_venue(&self) -> Venue {
116 self.venue
117 }
118
119 #[getter]
120 fn value(&self) -> String {
121 self.to_string()
122 }
123
124 #[staticmethod]
125 #[pyo3(name = "from_str")]
126 fn py_from_str(value: &str) -> PyResult<Self> {
127 Self::from_str(value).map_err(to_pyvalue_err)
128 }
129
130 #[pyo3(name = "is_synthetic")]
131 fn py_is_synthetic(&self) -> bool {
132 self.is_synthetic()
133 }
134}