nautilus_model/python/identifiers/
instrument_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
16#![allow(deprecated)]
17// TODO: We still rely on `IntoPy` for now, so temporarily ignore
18// these deprecations until fully migrated to `IntoPyObject`.
19
20use std::{
21    collections::hash_map::DefaultHasher,
22    hash::{Hash, Hasher},
23    str::FromStr,
24};
25
26use nautilus_core::python::to_pyvalue_err;
27use pyo3::{
28    prelude::*,
29    pyclass::CompareOp,
30    types::{PyString, PyTuple},
31};
32
33use crate::identifiers::{InstrumentId, Symbol, Venue};
34
35#[pymethods]
36impl InstrumentId {
37    #[new]
38    fn py_new(symbol: Symbol, venue: Venue) -> Self {
39        Self::new(symbol, venue)
40    }
41
42    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
43        let py_tuple: &Bound<'_, PyTuple> = state.downcast::<PyTuple>()?;
44        self.symbol = Symbol::new_checked(
45            py_tuple
46                .get_item(0)?
47                .downcast::<PyString>()?
48                .extract::<&str>()?,
49        )
50        .map_err(to_pyvalue_err)?;
51        self.venue = Venue::new_checked(
52            py_tuple
53                .get_item(1)?
54                .downcast::<PyString>()?
55                .extract::<&str>()?,
56        )
57        .map_err(to_pyvalue_err)?;
58        Ok(())
59    }
60
61    fn __getstate__(&self, py: Python) -> PyResult<PyObject> {
62        Ok((self.symbol.to_string(), self.venue.to_string()).to_object(py))
63    }
64
65    fn __reduce__(&self, py: Python) -> PyResult<PyObject> {
66        let safe_constructor = py.get_type_bound::<Self>().getattr("_safe_constructor")?;
67        let state = self.__getstate__(py)?;
68        Ok((safe_constructor, PyTuple::empty(py), state).to_object(py))
69    }
70
71    #[staticmethod]
72    fn _safe_constructor() -> PyResult<Self> {
73        Ok(Self::from_str("NULL.NULL").unwrap()) // Safe default
74    }
75
76    fn __richcmp__(&self, other: PyObject, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
77        if let Ok(other) = other.extract::<Self>(py) {
78            match op {
79                CompareOp::Eq => self.eq(&other).into_py(py),
80                CompareOp::Ne => self.ne(&other).into_py(py),
81                CompareOp::Ge => self.ge(&other).into_py(py),
82                CompareOp::Gt => self.gt(&other).into_py(py),
83                CompareOp::Le => self.le(&other).into_py(py),
84                CompareOp::Lt => self.lt(&other).into_py(py),
85            }
86        } else {
87            py.NotImplemented()
88        }
89    }
90
91    fn __hash__(&self) -> isize {
92        let mut h = DefaultHasher::new();
93        self.hash(&mut h);
94        h.finish() as isize
95    }
96
97    fn __repr__(&self) -> String {
98        format!("{}('{}')", stringify!(InstrumentId), self)
99    }
100
101    fn __str__(&self) -> String {
102        self.to_string()
103    }
104
105    #[getter]
106    #[pyo3(name = "symbol")]
107    fn py_symbol(&self) -> Symbol {
108        self.symbol
109    }
110
111    #[getter]
112    #[pyo3(name = "venue")]
113    fn py_venue(&self) -> Venue {
114        self.venue
115    }
116
117    #[getter]
118    fn value(&self) -> String {
119        self.to_string()
120    }
121
122    #[staticmethod]
123    #[pyo3(name = "from_str")]
124    fn py_from_str(value: &str) -> PyResult<Self> {
125        Self::from_str(value).map_err(to_pyvalue_err)
126    }
127
128    #[pyo3(name = "is_synthetic")]
129    fn py_is_synthetic(&self) -> bool {
130        self.is_synthetic()
131    }
132}
133
134impl ToPyObject for InstrumentId {
135    fn to_object(&self, py: Python) -> PyObject {
136        self.into_py(py)
137    }
138}