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