Skip to main content

nautilus_model/python/identifiers/
symbol.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};
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::symbol::Symbol;
30
31#[pymethods]
32#[pyo3_stub_gen::derive::gen_stub_pymethods]
33impl Symbol {
34    /// Represents a valid ticker symbol ID for a tradable instrument.
35    #[new]
36    fn py_new(value: &str) -> PyResult<Self> {
37        Self::new_checked(value).map_err(to_pyvalue_err)
38    }
39
40    #[staticmethod]
41    #[pyo3(name = "_safe_constructor")]
42    fn py_safe_constructor() -> Self {
43        Self::from("NULL")
44    }
45
46    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
47        let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
48        let binding = py_tuple.get_item(0)?;
49        let value = binding.cast::<PyString>()?.extract::<&str>()?;
50        let validated = Self::new_checked(value).map_err(to_pyvalue_err)?;
51        self.set_inner(validated.as_str());
52        Ok(())
53    }
54
55    fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
56        (self.to_string(),).into_py_any(py)
57    }
58
59    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
60        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
61        let state = self.__getstate__(py)?;
62        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
63    }
64
65    #[expect(clippy::needless_pass_by_value)]
66    fn __richcmp__(&self, other: Py<PyAny>, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
67        if let Ok(other) = other.extract::<Self>(py) {
68            match op {
69                CompareOp::Eq => self.eq(&other).into_py_any_unwrap(py),
70                CompareOp::Ne => self.ne(&other).into_py_any_unwrap(py),
71                CompareOp::Ge => self.ge(&other).into_py_any_unwrap(py),
72                CompareOp::Gt => self.gt(&other).into_py_any_unwrap(py),
73                CompareOp::Le => self.le(&other).into_py_any_unwrap(py),
74                CompareOp::Lt => self.lt(&other).into_py_any_unwrap(py),
75            }
76        } else {
77            py.NotImplemented()
78        }
79    }
80
81    fn __hash__(&self) -> isize {
82        let mut h = DefaultHasher::new();
83        self.hash(&mut h);
84        h.finish() as isize
85    }
86
87    fn __repr__(&self) -> String {
88        format!("{}('{}')", stringify!(Symbol), self)
89    }
90
91    fn __str__(&self) -> String {
92        self.to_string()
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
101    #[getter]
102    #[pyo3(name = "value")]
103    fn py_value(&self) -> String {
104        self.to_string()
105    }
106
107    /// Returns true if the symbol string contains a period (`.`).
108    #[getter]
109    #[pyo3(name = "is_composite")]
110    fn py_is_composite(&self) -> bool {
111        self.is_composite()
112    }
113
114    /// Returns the symbol root.
115    ///
116    /// The symbol root is the substring that appears before the first period (`.`)
117    /// in the full symbol string. It typically represents the underlying asset for
118    /// futures and options contracts. If no period is found, the entire symbol
119    /// string is considered the root.
120    #[getter]
121    #[pyo3(name = "root")]
122    fn py_root(&self) -> &str {
123        self.root()
124    }
125
126    /// Returns the symbol topic.
127    ///
128    /// The symbol topic is the root symbol with a wildcard (`*`) appended if the symbol has a root,
129    /// otherwise returns the full symbol string.
130    #[getter]
131    #[pyo3(name = "topic")]
132    fn py_topic(&self) -> String {
133        self.topic()
134    }
135}