nautilus_model/python/data/
status.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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::{HashMap, hash_map::DefaultHasher},
18    hash::{Hash, Hasher},
19    str::FromStr,
20};
21
22use nautilus_core::{
23    python::{
24        IntoPyObjectNautilusExt,
25        serialization::{from_dict_pyo3, to_dict_pyo3},
26        to_pyvalue_err,
27    },
28    serialization::Serializable,
29};
30use pyo3::{prelude::*, pyclass::CompareOp, types::PyDict};
31use ustr::Ustr;
32
33use crate::{
34    data::status::InstrumentStatus,
35    enums::{FromU16, MarketStatusAction},
36    identifiers::InstrumentId,
37    python::common::PY_MODULE_MODEL,
38};
39
40impl InstrumentStatus {
41    /// Create a new [`InstrumentStatus`] extracted from the given [`PyAny`].
42    pub fn from_pyobject(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
43        let instrument_id_obj: Bound<'_, PyAny> = obj.getattr("instrument_id")?.extract()?;
44        let instrument_id_str: String = instrument_id_obj.getattr("value")?.extract()?;
45        let instrument_id =
46            InstrumentId::from_str(instrument_id_str.as_str()).map_err(to_pyvalue_err)?;
47
48        let action_obj: Bound<'_, PyAny> = obj.getattr("action")?.extract()?;
49        let action_u16: u16 = action_obj.getattr("value")?.extract()?;
50        let action = MarketStatusAction::from_u16(action_u16).unwrap();
51
52        let ts_event: u64 = obj.getattr("ts_event")?.extract()?;
53        let ts_init: u64 = obj.getattr("ts_init")?.extract()?;
54
55        let reason_str: Option<String> = obj.getattr("reason")?.extract()?;
56        let reason = reason_str.map(|reason_str| Ustr::from(&reason_str));
57
58        let trading_event_str: Option<String> = obj.getattr("trading_event")?.extract()?;
59        let trading_event =
60            trading_event_str.map(|trading_event_str| Ustr::from(&trading_event_str));
61
62        let is_trading: Option<bool> = obj.getattr("is_trading")?.extract()?;
63        let is_quoting: Option<bool> = obj.getattr("is_quoting")?.extract()?;
64        let is_short_sell_restricted: Option<bool> =
65            obj.getattr("is_short_sell_restricted")?.extract()?;
66
67        Ok(Self::new(
68            instrument_id,
69            action,
70            ts_event.into(),
71            ts_init.into(),
72            reason,
73            trading_event,
74            is_trading,
75            is_quoting,
76            is_short_sell_restricted,
77        ))
78    }
79}
80
81#[pymethods]
82impl InstrumentStatus {
83    #[new]
84    #[pyo3(signature = (instrument_id, action, ts_event, ts_init, reason=None, trading_event=None, is_trading=None, is_quoting=None, is_short_sell_restricted=None))]
85    #[allow(clippy::too_many_arguments)]
86    fn py_new(
87        instrument_id: InstrumentId,
88        action: MarketStatusAction,
89        ts_event: u64,
90        ts_init: u64,
91        reason: Option<String>,
92        trading_event: Option<String>,
93        is_trading: Option<bool>,
94        is_quoting: Option<bool>,
95        is_short_sell_restricted: Option<bool>,
96    ) -> Self {
97        Self::new(
98            instrument_id,
99            action,
100            ts_event.into(),
101            ts_init.into(),
102            reason.map(|s| Ustr::from(&s)),
103            trading_event.map(|s| Ustr::from(&s)),
104            is_trading,
105            is_quoting,
106            is_short_sell_restricted,
107        )
108    }
109
110    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
111        match op {
112            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
113            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
114            _ => py.NotImplemented(),
115        }
116    }
117
118    fn __hash__(&self) -> isize {
119        let mut h = DefaultHasher::new();
120        self.hash(&mut h);
121        h.finish() as isize
122    }
123
124    fn __repr__(&self) -> String {
125        format!("{}({})", stringify!(InstrumentStatus), self)
126    }
127
128    fn __str__(&self) -> String {
129        self.to_string()
130    }
131
132    #[getter]
133    #[pyo3(name = "instrument_id")]
134    fn py_instrument_id(&self) -> InstrumentId {
135        self.instrument_id
136    }
137
138    #[getter]
139    #[pyo3(name = "action")]
140    fn py_action(&self) -> MarketStatusAction {
141        self.action
142    }
143
144    #[getter]
145    #[pyo3(name = "ts_event")]
146    fn py_ts_event(&self) -> u64 {
147        self.ts_event.as_u64()
148    }
149
150    #[getter]
151    #[pyo3(name = "ts_init")]
152    fn py_ts_init(&self) -> u64 {
153        self.ts_init.as_u64()
154    }
155
156    #[getter]
157    #[pyo3(name = "reason")]
158    fn py_reason(&self) -> Option<String> {
159        self.reason.map(|x| x.to_string())
160    }
161
162    #[getter]
163    #[pyo3(name = "trading_event")]
164    fn py_trading_event(&self) -> Option<String> {
165        self.trading_event.map(|x| x.to_string())
166    }
167
168    #[getter]
169    #[pyo3(name = "is_trading")]
170    fn py_is_trading(&self) -> Option<bool> {
171        self.is_trading
172    }
173
174    #[getter]
175    #[pyo3(name = "is_quoting")]
176    fn py_is_quoting(&self) -> Option<bool> {
177        self.is_quoting
178    }
179
180    #[getter]
181    #[pyo3(name = "is_short_sell_restricted")]
182    fn py_is_short_sell_restricted(&self) -> Option<bool> {
183        self.is_short_sell_restricted
184    }
185
186    #[staticmethod]
187    #[pyo3(name = "fully_qualified_name")]
188    fn py_fully_qualified_name() -> String {
189        format!("{}:{}", PY_MODULE_MODEL, stringify!(InstrumentStatus))
190    }
191
192    /// Returns a new object from the given dictionary representation.
193    #[staticmethod]
194    #[pyo3(name = "from_dict")]
195    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
196        from_dict_pyo3(py, values)
197    }
198
199    #[staticmethod]
200    #[pyo3(name = "get_metadata")]
201    fn py_get_metadata(instrument_id: &InstrumentId) -> PyResult<HashMap<String, String>> {
202        Ok(Self::get_metadata(instrument_id))
203    }
204
205    #[staticmethod]
206    #[pyo3(name = "from_json")]
207    fn py_from_json(data: Vec<u8>) -> PyResult<Self> {
208        Self::from_json_bytes(&data).map_err(to_pyvalue_err)
209    }
210
211    #[staticmethod]
212    #[pyo3(name = "from_msgpack")]
213    fn py_from_msgpack(data: Vec<u8>) -> PyResult<Self> {
214        Self::from_msgpack_bytes(&data).map_err(to_pyvalue_err)
215    }
216
217    /// Return a dictionary representation of the object.
218    #[pyo3(name = "as_dict")]
219    fn py_as_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
220        to_dict_pyo3(py, self)
221    }
222
223    /// Return JSON encoded bytes representation of the object.
224    #[pyo3(name = "as_json")]
225    fn py_as_json(&self, py: Python<'_>) -> Py<PyAny> {
226        // Unwrapping is safe when serializing a valid object
227        self.as_json_bytes().unwrap().into_py_any_unwrap(py)
228    }
229
230    /// Return MsgPack encoded bytes representation of the object.
231    #[pyo3(name = "as_msgpack")]
232    fn py_as_msgpack(&self, py: Python<'_>) -> Py<PyAny> {
233        // Unwrapping is safe when serializing a valid object
234        self.as_msgpack_bytes().unwrap().into_py_any_unwrap(py)
235    }
236}
237
238////////////////////////////////////////////////////////////////////////////////
239// Tests
240////////////////////////////////////////////////////////////////////////////////
241#[cfg(test)]
242mod tests {
243    use nautilus_core::python::IntoPyObjectNautilusExt;
244    use pyo3::Python;
245    use rstest::rstest;
246
247    use crate::data::{status::InstrumentStatus, stubs::stub_instrument_status};
248
249    #[rstest]
250    fn test_as_dict(stub_instrument_status: InstrumentStatus) {
251        pyo3::prepare_freethreaded_python();
252
253        Python::with_gil(|py| {
254            let dict_string = stub_instrument_status.py_as_dict(py).unwrap().to_string();
255            let expected_string = r"{'type': 'InstrumentStatus', 'instrument_id': 'MSFT.XNAS', 'action': 'TRADING', 'ts_event': 1, 'ts_init': 2, 'reason': None, 'trading_event': None, 'is_trading': None, 'is_quoting': None, 'is_short_sell_restricted': None}";
256            assert_eq!(dict_string, expected_string);
257        });
258    }
259
260    #[rstest]
261    fn test_from_dict(stub_instrument_status: InstrumentStatus) {
262        pyo3::prepare_freethreaded_python();
263
264        Python::with_gil(|py| {
265            let dict = stub_instrument_status.py_as_dict(py).unwrap();
266            let parsed = InstrumentStatus::py_from_dict(py, dict).unwrap();
267            assert_eq!(parsed, stub_instrument_status);
268        });
269    }
270
271    #[rstest]
272    fn test_from_pyobject(stub_instrument_status: InstrumentStatus) {
273        pyo3::prepare_freethreaded_python();
274
275        Python::with_gil(|py| {
276            let status_pyobject = stub_instrument_status.into_py_any_unwrap(py);
277            let parsed_status = InstrumentStatus::from_pyobject(status_pyobject.bind(py)).unwrap();
278            assert_eq!(parsed_status, stub_instrument_status);
279        });
280    }
281}