Skip to main content

nautilus_model/python/identifiers/
instrument_id.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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, correctness_error_to_pyvalue_err};
23use pyo3::{
24    IntoPyObjectExt,
25    prelude::*,
26    pyclass::CompareOp,
27    types::{PyString, PyTuple},
28};
29
30use crate::{
31    enums::InstrumentClass,
32    identifiers::{InstrumentId, Symbol, Venue},
33    python::instrument_id_error_to_pyvalue_err,
34};
35
36#[pymethods]
37#[pyo3_stub_gen::derive::gen_stub_pymethods]
38impl InstrumentId {
39    /// Represents a valid instrument ID.
40    ///
41    /// The symbol and venue combination should uniquely identify the instrument.
42    #[new]
43    fn py_new(symbol: Symbol, venue: Venue) -> Self {
44        Self::new(symbol, venue)
45    }
46
47    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
48        let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
49        self.symbol = Symbol::new_checked(
50            py_tuple
51                .get_item(0)?
52                .cast::<PyString>()?
53                .extract::<&str>()?,
54        )
55        .map_err(correctness_error_to_pyvalue_err)?;
56        self.venue = Venue::new_checked(
57            py_tuple
58                .get_item(1)?
59                .cast::<PyString>()?
60                .extract::<&str>()?,
61        )
62        .map_err(correctness_error_to_pyvalue_err)?;
63        Ok(())
64    }
65
66    fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
67        (self.symbol.to_string(), self.venue.to_string()).into_py_any(py)
68    }
69
70    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
71        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
72        let state = self.__getstate__(py)?;
73        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
74    }
75
76    #[staticmethod]
77    fn _safe_constructor() -> Self {
78        Self::from_str("NULL.NULL").unwrap() // Safe default
79    }
80
81    #[expect(clippy::needless_pass_by_value)]
82    fn __richcmp__(&self, other: Py<PyAny>, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
83        if let Ok(other) = other.extract::<Self>(py) {
84            match op {
85                CompareOp::Eq => self.eq(&other).into_py_any_unwrap(py),
86                CompareOp::Ne => self.ne(&other).into_py_any_unwrap(py),
87                CompareOp::Ge => self.ge(&other).into_py_any_unwrap(py),
88                CompareOp::Gt => self.gt(&other).into_py_any_unwrap(py),
89                CompareOp::Le => self.le(&other).into_py_any_unwrap(py),
90                CompareOp::Lt => self.lt(&other).into_py_any_unwrap(py),
91            }
92        } else {
93            py.NotImplemented()
94        }
95    }
96
97    fn __hash__(&self) -> isize {
98        let mut h = DefaultHasher::new();
99        self.hash(&mut h);
100        h.finish() as isize
101    }
102
103    fn __repr__(&self) -> String {
104        format!("{}('{}')", stringify!(InstrumentId), self)
105    }
106
107    fn __str__(&self) -> String {
108        self.to_string()
109    }
110
111    #[getter]
112    #[pyo3(name = "symbol")]
113    fn py_symbol(&self) -> Symbol {
114        self.symbol
115    }
116
117    #[getter]
118    #[pyo3(name = "venue")]
119    fn py_venue(&self) -> Venue {
120        self.venue
121    }
122
123    #[getter]
124    fn value(&self) -> String {
125        self.to_string()
126    }
127
128    #[staticmethod]
129    #[pyo3(name = "from_str")]
130    fn py_from_str(value: &str) -> PyResult<Self> {
131        Self::from_str(value).map_err(instrument_id_error_to_pyvalue_err)
132    }
133
134    #[pyo3(name = "is_synthetic")]
135    fn py_is_synthetic(&self) -> bool {
136        self.is_synthetic()
137    }
138
139    /// Returns the parent-symbol components `(root, class)` if this id has
140    /// a recognised parent shape `<root>.<class>` in its symbol component.
141    ///
142    /// Returns `None` when the symbol has zero or more than one `.`, or when
143    /// the suffix is not a recognised `InstrumentClass` parent suffix
144    /// (see `InstrumentClass.try_from_parent_suffix`).
145    ///
146    /// Used to gate parent-style subscription fan-out: a `None` return means
147    /// the id does not refer to a parent group and must not be expanded.
148    #[pyo3(name = "parse_parent_components")]
149    fn py_parse_parent_components(&self) -> Option<(String, InstrumentClass)> {
150        self.parse_parent_components()
151            .map(|(root, class)| (root.to_string(), class))
152    }
153}