1use std::{
17 collections::{HashMap, hash_map::DefaultHasher},
18 hash::{Hash, Hasher},
19 str::FromStr,
20};
21
22use nautilus_core::{
23 UnixNanos,
24 python::{
25 IntoPyObjectNautilusExt,
26 serialization::{from_dict_pyo3, to_dict_pyo3},
27 to_pyvalue_err,
28 },
29 serialization::{
30 Serializable,
31 msgpack::{FromMsgPack, ToMsgPack},
32 },
33};
34use pyo3::{
35 IntoPyObjectExt,
36 prelude::*,
37 pyclass::CompareOp,
38 types::{PyDict, PyInt, PyString, PyTuple},
39};
40
41use crate::{
42 data::QuoteTick,
43 enums::PriceType,
44 identifiers::InstrumentId,
45 python::common::PY_MODULE_MODEL,
46 types::{
47 price::{Price, PriceRaw},
48 quantity::{Quantity, QuantityRaw},
49 },
50};
51
52#[pymethods]
53#[pyo3_stub_gen::derive::gen_stub_pymethods]
54impl QuoteTick {
55 #[new]
57 fn py_new(
58 instrument_id: InstrumentId,
59 bid_price: Price,
60 ask_price: Price,
61 bid_size: Quantity,
62 ask_size: Quantity,
63 ts_event: u64,
64 ts_init: u64,
65 ) -> PyResult<Self> {
66 Self::new_checked(
67 instrument_id,
68 bid_price,
69 ask_price,
70 bid_size,
71 ask_size,
72 ts_event.into(),
73 ts_init.into(),
74 )
75 .map_err(to_pyvalue_err)
76 }
77
78 fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
79 let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
80 let binding = py_tuple.get_item(0)?;
81 let instrument_id_str: &str = binding.cast::<PyString>()?.extract()?;
82 let bid_price_raw: PriceRaw = py_tuple.get_item(1)?.cast::<PyInt>()?.extract()?;
83 let ask_price_raw: PriceRaw = py_tuple.get_item(2)?.cast::<PyInt>()?.extract()?;
84 let bid_price_prec: u8 = py_tuple.get_item(3)?.cast::<PyInt>()?.extract()?;
85 let ask_price_prec: u8 = py_tuple.get_item(4)?.cast::<PyInt>()?.extract()?;
86
87 let bid_size_raw: QuantityRaw = py_tuple.get_item(5)?.cast::<PyInt>()?.extract()?;
88 let ask_size_raw: QuantityRaw = py_tuple.get_item(6)?.cast::<PyInt>()?.extract()?;
89 let bid_size_prec: u8 = py_tuple.get_item(7)?.cast::<PyInt>()?.extract()?;
90 let ask_size_prec: u8 = py_tuple.get_item(8)?.cast::<PyInt>()?.extract()?;
91 let ts_event: u64 = py_tuple.get_item(9)?.cast::<PyInt>()?.extract()?;
92 let ts_init: u64 = py_tuple.get_item(10)?.cast::<PyInt>()?.extract()?;
93
94 self.instrument_id = InstrumentId::from_str(instrument_id_str).map_err(to_pyvalue_err)?;
95 self.bid_price = Price::from_raw(bid_price_raw, bid_price_prec);
96 self.ask_price = Price::from_raw(ask_price_raw, ask_price_prec);
97 self.bid_size = Quantity::from_raw(bid_size_raw, bid_size_prec);
98 self.ask_size = Quantity::from_raw(ask_size_raw, ask_size_prec);
99 self.ts_event = ts_event.into();
100 self.ts_init = ts_init.into();
101
102 Ok(())
103 }
104
105 fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
106 (
107 self.instrument_id.to_string(),
108 self.bid_price.raw,
109 self.ask_price.raw,
110 self.bid_price.precision,
111 self.ask_price.precision,
112 self.bid_size.raw,
113 self.ask_size.raw,
114 self.bid_size.precision,
115 self.ask_size.precision,
116 self.ts_event.as_u64(),
117 self.ts_init.as_u64(),
118 )
119 .into_py_any(py)
120 }
121
122 fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
123 let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
124 let state = self.__getstate__(py)?;
125 (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
126 }
127
128 #[staticmethod]
129 fn _safe_constructor() -> PyResult<Self> {
130 Self::new_checked(
131 InstrumentId::from("NULL.NULL"),
132 Price::zero(0),
133 Price::zero(0),
134 Quantity::zero(0),
135 Quantity::zero(0),
136 UnixNanos::default(),
137 UnixNanos::default(),
138 )
139 .map_err(to_pyvalue_err)
140 }
141
142 fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
143 match op {
144 CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
145 CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
146 _ => py.NotImplemented(),
147 }
148 }
149
150 fn __hash__(&self) -> isize {
151 let mut h = DefaultHasher::new();
152 self.hash(&mut h);
153 h.finish() as isize
154 }
155
156 fn __repr__(&self) -> String {
157 format!("{}({})", stringify!(QuoteTick), self)
158 }
159
160 fn __str__(&self) -> String {
161 self.to_string()
162 }
163
164 #[getter]
165 #[pyo3(name = "instrument_id")]
166 fn py_instrument_id(&self) -> InstrumentId {
167 self.instrument_id
168 }
169
170 #[getter]
171 #[pyo3(name = "bid_price")]
172 fn py_bid_price(&self) -> Price {
173 self.bid_price
174 }
175
176 #[getter]
177 #[pyo3(name = "ask_price")]
178 fn py_ask_price(&self) -> Price {
179 self.ask_price
180 }
181
182 #[getter]
183 #[pyo3(name = "bid_size")]
184 fn py_bid_size(&self) -> Quantity {
185 self.bid_size
186 }
187
188 #[getter]
189 #[pyo3(name = "ask_size")]
190 fn py_ask_size(&self) -> Quantity {
191 self.ask_size
192 }
193
194 #[getter]
195 #[pyo3(name = "ts_event")]
196 fn py_ts_event(&self) -> u64 {
197 self.ts_event.as_u64()
198 }
199
200 #[getter]
201 #[pyo3(name = "ts_init")]
202 fn py_ts_init(&self) -> u64 {
203 self.ts_init.as_u64()
204 }
205
206 #[staticmethod]
207 #[pyo3(name = "fully_qualified_name")]
208 fn py_fully_qualified_name() -> String {
209 format!("{}:{}", PY_MODULE_MODEL, stringify!(QuoteTick))
210 }
211
212 #[staticmethod]
214 #[pyo3(name = "get_metadata")]
215 fn py_get_metadata(
216 instrument_id: &InstrumentId,
217 price_precision: u8,
218 size_precision: u8,
219 ) -> HashMap<String, String> {
220 Self::get_metadata(instrument_id, price_precision, size_precision)
221 }
222
223 #[staticmethod]
225 #[pyo3(name = "get_fields")]
226 fn py_get_fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {
227 let py_dict = PyDict::new(py);
228 for (k, v) in Self::get_fields() {
229 py_dict.set_item(k, v)?;
230 }
231
232 Ok(py_dict)
233 }
234
235 #[staticmethod]
236 #[pyo3(name = "from_raw")]
237 #[expect(clippy::too_many_arguments)]
238 fn py_from_raw(
239 instrument_id: InstrumentId,
240 bid_price_raw: PriceRaw,
241 ask_price_raw: PriceRaw,
242 bid_price_prec: u8,
243 ask_price_prec: u8,
244 bid_size_raw: QuantityRaw,
245 ask_size_raw: QuantityRaw,
246 bid_size_prec: u8,
247 ask_size_prec: u8,
248 ts_event: u64,
249 ts_init: u64,
250 ) -> PyResult<Self> {
251 Self::new_checked(
252 instrument_id,
253 Price::from_raw(bid_price_raw, bid_price_prec),
254 Price::from_raw(ask_price_raw, ask_price_prec),
255 Quantity::from_raw(bid_size_raw, bid_size_prec),
256 Quantity::from_raw(ask_size_raw, ask_size_prec),
257 ts_event.into(),
258 ts_init.into(),
259 )
260 .map_err(to_pyvalue_err)
261 }
262
263 #[staticmethod]
265 #[pyo3(name = "from_dict")]
266 fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
267 from_dict_pyo3(py, values)
268 }
269
270 #[pyo3(name = "extract_price")]
276 fn py_extract_price(&self, price_type: PriceType) -> PyResult<Price> {
277 self.extract_price(price_type).map_err(to_pyvalue_err)
278 }
279
280 #[pyo3(name = "extract_size")]
286 fn py_extract_size(&self, price_type: PriceType) -> PyResult<Quantity> {
287 self.extract_size(price_type).map_err(to_pyvalue_err)
288 }
289
290 #[pyo3(name = "to_dict")]
292 fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
293 to_dict_pyo3(py, self)
294 }
295
296 #[pyo3(name = "to_json_bytes")]
298 fn py_to_json_bytes(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
299 self.to_json_bytes()
300 .map_err(to_pyvalue_err)?
301 .into_py_any(py)
302 }
303
304 #[pyo3(name = "to_msgpack_bytes")]
306 fn py_to_msgpack_bytes(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
307 self.to_msgpack_bytes()
308 .map_err(to_pyvalue_err)?
309 .into_py_any(py)
310 }
311}
312
313#[pymethods]
314impl QuoteTick {
315 #[staticmethod]
316 #[pyo3(name = "from_json")]
317 fn py_from_json(data: &[u8]) -> PyResult<Self> {
318 Self::from_json_bytes(data).map_err(to_pyvalue_err)
319 }
320
321 #[staticmethod]
322 #[pyo3(name = "from_msgpack")]
323 fn py_from_msgpack(data: &[u8]) -> PyResult<Self> {
324 Self::from_msgpack_bytes(data).map_err(to_pyvalue_err)
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use pyo3::Python;
331 use rstest::rstest;
332
333 use crate::{
334 data::{QuoteTick, stubs::quote_ethusdt_binance},
335 identifiers::InstrumentId,
336 types::{Price, Quantity},
337 };
338
339 #[rstest]
340 #[case(
341 Price::new(0.010_000, 6),
342 Price::new(0.010_001_0, 7), Quantity::new(0.001_000, 6),
344 Quantity::new(0.001_000, 6),
345)]
346 #[case(
347 Price::new(0.010_000, 6),
348 Price::new(0.010_001, 6),
349 Quantity::new(0.001_000, 6),
350 Quantity::new(0.001_000_0, 7), )]
352 fn test_quote_tick_py_new_invalid_precisions(
353 #[case] bid_price: Price,
354 #[case] ask_price: Price,
355 #[case] bid_size: Quantity,
356 #[case] ask_size: Quantity,
357 ) {
358 let instrument_id = InstrumentId::from("ETH-USDT-SWAP.OKX");
359 let ts_event = 0;
360 let ts_init = 1;
361
362 let result = QuoteTick::py_new(
363 instrument_id,
364 bid_price,
365 ask_price,
366 bid_size,
367 ask_size,
368 ts_event,
369 ts_init,
370 );
371
372 assert!(result.is_err());
373 }
374
375 #[rstest]
376 fn test_to_dict(quote_ethusdt_binance: QuoteTick) {
377 let quote = quote_ethusdt_binance;
378
379 Python::initialize();
380 Python::attach(|py| {
381 let dict_string = quote.py_to_dict(py).unwrap().to_string();
382 let expected_string = "{'type': 'QuoteTick', 'instrument_id': 'ETHUSDT-PERP.BINANCE', 'bid_price': '10000.0000', 'ask_price': '10001.0000', 'bid_size': '1.00000000', 'ask_size': '1.00000000', 'ts_event': 0, 'ts_init': 1}";
383 assert_eq!(dict_string, expected_string);
384 });
385 }
386
387 #[rstest]
388 fn test_from_dict(quote_ethusdt_binance: QuoteTick) {
389 let quote = quote_ethusdt_binance;
390
391 Python::initialize();
392 Python::attach(|py| {
393 let dict = quote.py_to_dict(py).unwrap();
394 let parsed = QuoteTick::py_from_dict(py, dict).unwrap();
395 assert_eq!(parsed, quote);
396 });
397 }
398}