nautilus-model 0.55.0

Domain model for the Nautilus trading engine
Documentation
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
};

use nautilus_core::{
    from_pydict,
    python::{IntoPyObjectNautilusExt, serialization::from_dict_pyo3, to_pyvalue_err},
};
use pyo3::{basic::CompareOp, prelude::*, types::PyDict};

use crate::{
    identifiers::{InstrumentId, Symbol},
    instruments::IndexInstrument,
    types::{Currency, Price, Quantity},
};

#[pymethods]
#[pyo3_stub_gen::derive::gen_stub_pymethods]
impl IndexInstrument {
    /// Represents a generic index instrument.
    ///
    /// An index is typically not directly tradable.
    #[allow(clippy::too_many_arguments)]
    #[new]
    #[pyo3(signature = (instrument_id, raw_symbol, currency, price_precision, size_precision, price_increment, size_increment, ts_event, ts_init, info=None))]
    fn py_new(
        instrument_id: InstrumentId,
        raw_symbol: Symbol,
        currency: Currency,
        price_precision: u8,
        size_precision: u8,
        price_increment: Price,
        size_increment: Quantity,
        ts_event: u64,
        ts_init: u64,
        info: Option<Py<PyDict>>,
    ) -> PyResult<Self> {
        let info_map = if let Some(info_dict) = info {
            Python::attach(|py| from_pydict(py, info_dict))?
        } else {
            None
        };

        Self::new_checked(
            instrument_id,
            raw_symbol,
            currency,
            price_precision,
            size_precision,
            price_increment,
            size_increment,
            info_map,
            ts_event.into(),
            ts_init.into(),
        )
        .map_err(to_pyvalue_err)
    }

    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
        match op {
            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
            _ => py.NotImplemented(),
        }
    }

    fn __hash__(&self) -> isize {
        let mut hasher = DefaultHasher::new();
        self.hash(&mut hasher);
        hasher.finish() as isize
    }

    #[getter]
    fn type_name(&self) -> &'static str {
        stringify!(IndexInstrument)
    }

    #[getter]
    #[pyo3(name = "id")]
    fn py_id(&self) -> InstrumentId {
        self.id
    }

    #[getter]
    #[pyo3(name = "raw_symbol")]
    fn py_raw_symbol(&self) -> Symbol {
        self.raw_symbol
    }

    #[getter]
    #[pyo3(name = "quote_currency")]
    fn py_quote_currency(&self) -> Currency {
        self.currency
    }

    #[getter]
    #[pyo3(name = "price_precision")]
    fn py_price_precision(&self) -> u8 {
        self.price_precision
    }

    #[getter]
    #[pyo3(name = "size_precision")]
    fn py_size_precision(&self) -> u8 {
        self.size_precision
    }

    #[getter]
    #[pyo3(name = "price_increment")]
    fn py_price_increment(&self) -> Price {
        self.price_increment
    }

    #[getter]
    #[pyo3(name = "size_increment")]
    fn py_size_increment(&self) -> Quantity {
        self.size_increment
    }

    #[getter]
    #[pyo3(name = "ts_event")]
    fn py_ts_event(&self) -> u64 {
        self.ts_event.as_u64()
    }

    #[getter]
    #[pyo3(name = "ts_init")]
    fn py_ts_init(&self) -> u64 {
        self.ts_init.as_u64()
    }

    #[getter]
    #[pyo3(name = "info")]
    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
        if let Some(ref info_map) = self.info {
            let py_dict = PyDict::new(py);
            for (key, value) in info_map {
                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
                let py_value =
                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
                py_dict.set_item(key, py_value)?;
            }
            Ok(py_dict.unbind())
        } else {
            Ok(PyDict::new(py).unbind())
        }
    }

    #[staticmethod]
    #[pyo3(name = "from_dict")]
    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
        from_dict_pyo3(py, values)
    }

    #[pyo3(name = "to_dict")]
    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let dict = PyDict::new(py);
        dict.set_item("type", stringify!(IndexInstrument))?;
        dict.set_item("id", self.id.to_string())?;
        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
        dict.set_item("currency", self.currency.code.to_string())?;
        dict.set_item("price_precision", self.price_precision)?;
        dict.set_item("size_precision", self.size_precision)?;
        dict.set_item("price_increment", self.price_increment.to_string())?;
        dict.set_item("size_increment", self.size_increment.to_string())?;
        dict.set_item("ts_event", self.ts_event.as_u64())?;
        dict.set_item("ts_init", self.ts_init.as_u64())?;

        if let Some(ref info_map) = self.info {
            let info_dict = PyDict::new(py);
            for (key, value) in info_map {
                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
                let py_value =
                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
                info_dict.set_item(key, py_value)?;
            }
            dict.set_item("info", info_dict)?;
        } else {
            dict.set_item("info", PyDict::new(py))?;
        }
        Ok(dict.into())
    }
}