Skip to main content

nautilus_model/python/instruments/
index_instrument.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::{
22    from_pydict,
23    python::{IntoPyObjectNautilusExt, serialization::from_dict_pyo3, to_pyvalue_err},
24};
25use pyo3::{basic::CompareOp, prelude::*, types::PyDict};
26
27use crate::{
28    identifiers::{InstrumentId, Symbol},
29    instruments::IndexInstrument,
30    types::{Currency, Price, Quantity},
31};
32
33#[pymethods]
34#[pyo3_stub_gen::derive::gen_stub_pymethods]
35impl IndexInstrument {
36    /// Represents a generic index instrument.
37    ///
38    /// An index is typically not directly tradable.
39    #[expect(clippy::too_many_arguments)]
40    #[new]
41    #[pyo3(signature = (instrument_id, raw_symbol, currency, price_precision, size_precision, price_increment, size_increment, ts_event, ts_init, info=None))]
42    fn py_new(
43        instrument_id: InstrumentId,
44        raw_symbol: Symbol,
45        currency: Currency,
46        price_precision: u8,
47        size_precision: u8,
48        price_increment: Price,
49        size_increment: Quantity,
50        ts_event: u64,
51        ts_init: u64,
52        info: Option<Py<PyDict>>,
53    ) -> PyResult<Self> {
54        let info_map = if let Some(info_dict) = info {
55            Python::attach(|py| from_pydict(py, info_dict))?
56        } else {
57            None
58        };
59
60        Self::new_checked(
61            instrument_id,
62            raw_symbol,
63            currency,
64            price_precision,
65            size_precision,
66            price_increment,
67            size_increment,
68            info_map,
69            ts_event.into(),
70            ts_init.into(),
71        )
72        .map_err(to_pyvalue_err)
73    }
74
75    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
76        match op {
77            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
78            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
79            _ => py.NotImplemented(),
80        }
81    }
82
83    fn __hash__(&self) -> isize {
84        let mut hasher = DefaultHasher::new();
85        self.hash(&mut hasher);
86        hasher.finish() as isize
87    }
88
89    #[getter]
90    fn type_name(&self) -> &'static str {
91        stringify!(IndexInstrument)
92    }
93
94    #[getter]
95    #[pyo3(name = "id")]
96    fn py_id(&self) -> InstrumentId {
97        self.id
98    }
99
100    #[getter]
101    #[pyo3(name = "raw_symbol")]
102    fn py_raw_symbol(&self) -> Symbol {
103        self.raw_symbol
104    }
105
106    #[getter]
107    #[pyo3(name = "quote_currency")]
108    fn py_quote_currency(&self) -> Currency {
109        self.currency
110    }
111
112    #[getter]
113    #[pyo3(name = "price_precision")]
114    fn py_price_precision(&self) -> u8 {
115        self.price_precision
116    }
117
118    #[getter]
119    #[pyo3(name = "size_precision")]
120    fn py_size_precision(&self) -> u8 {
121        self.size_precision
122    }
123
124    #[getter]
125    #[pyo3(name = "price_increment")]
126    fn py_price_increment(&self) -> Price {
127        self.price_increment
128    }
129
130    #[getter]
131    #[pyo3(name = "size_increment")]
132    fn py_size_increment(&self) -> Quantity {
133        self.size_increment
134    }
135
136    #[getter]
137    #[pyo3(name = "ts_event")]
138    fn py_ts_event(&self) -> u64 {
139        self.ts_event.as_u64()
140    }
141
142    #[getter]
143    #[pyo3(name = "ts_init")]
144    fn py_ts_init(&self) -> u64 {
145        self.ts_init.as_u64()
146    }
147
148    #[getter]
149    #[pyo3(name = "info")]
150    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
151        if let Some(ref info_map) = self.info {
152            let py_dict = PyDict::new(py);
153
154            for (key, value) in info_map {
155                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
156                let py_value =
157                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
158                py_dict.set_item(key, py_value)?;
159            }
160            Ok(py_dict.unbind())
161        } else {
162            Ok(PyDict::new(py).unbind())
163        }
164    }
165
166    #[staticmethod]
167    #[pyo3(name = "from_dict")]
168    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
169        from_dict_pyo3(py, values)
170    }
171
172    #[pyo3(name = "to_dict")]
173    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
174        let dict = PyDict::new(py);
175        dict.set_item("type", stringify!(IndexInstrument))?;
176        dict.set_item("id", self.id.to_string())?;
177        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
178        dict.set_item("currency", self.currency.code.to_string())?;
179        dict.set_item("price_precision", self.price_precision)?;
180        dict.set_item("size_precision", self.size_precision)?;
181        dict.set_item("price_increment", self.price_increment.to_string())?;
182        dict.set_item("size_increment", self.size_increment.to_string())?;
183        dict.set_item("ts_event", self.ts_event.as_u64())?;
184        dict.set_item("ts_init", self.ts_init.as_u64())?;
185
186        if let Some(ref info_map) = self.info {
187            let info_dict = PyDict::new(py);
188
189            for (key, value) in info_map {
190                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
191                let py_value =
192                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
193                info_dict.set_item(key, py_value)?;
194            }
195            dict.set_item("info", info_dict)?;
196        } else {
197            dict.set_item("info", PyDict::new(py))?;
198        }
199        Ok(dict.into())
200    }
201}