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