1use 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};
26use rust_decimal::Decimal;
27
28use crate::{
29 identifiers::{InstrumentId, Symbol},
30 instruments::CryptoFuture,
31 python::instruments::register_crypto_currencies_from_dict,
32 types::{Currency, Money, Price, Quantity},
33};
34
35#[pymethods]
36#[pyo3_stub_gen::derive::gen_stub_pymethods]
37impl CryptoFuture {
38 #[expect(clippy::too_many_arguments)]
40 #[new]
41 #[pyo3(signature = (instrument_id, raw_symbol, underlying, quote_currency, settlement_currency, is_inverse, activation_ns, expiration_ns, price_precision, size_precision, price_increment, size_increment,ts_event, ts_init, multiplier=None, lot_size=None, max_quantity=None, min_quantity=None, max_notional=None, min_notional=None, max_price=None, min_price=None, margin_init=None, margin_maint=None, maker_fee=None, taker_fee=None, info=None))]
42 fn py_new(
43 instrument_id: InstrumentId,
44 raw_symbol: Symbol,
45 underlying: Currency,
46 quote_currency: Currency,
47 settlement_currency: Currency,
48 is_inverse: bool,
49 activation_ns: u64,
50 expiration_ns: u64,
51 price_precision: u8,
52 size_precision: u8,
53 price_increment: Price,
54 size_increment: Quantity,
55 ts_event: u64,
56 ts_init: u64,
57 multiplier: Option<Quantity>,
58 lot_size: Option<Quantity>,
59 max_quantity: Option<Quantity>,
60 min_quantity: Option<Quantity>,
61 max_notional: Option<Money>,
62 min_notional: Option<Money>,
63 max_price: Option<Price>,
64 min_price: Option<Price>,
65 margin_init: Option<Decimal>,
66 margin_maint: Option<Decimal>,
67 maker_fee: Option<Decimal>,
68 taker_fee: Option<Decimal>,
69 info: Option<Py<PyDict>>,
70 ) -> PyResult<Self> {
71 let info_map = if let Some(info_dict) = info {
73 Python::attach(|py| from_pydict(py, info_dict))?
74 } else {
75 None
76 };
77
78 Self::new_checked(
79 instrument_id,
80 raw_symbol,
81 underlying,
82 quote_currency,
83 settlement_currency,
84 is_inverse,
85 activation_ns.into(),
86 expiration_ns.into(),
87 price_precision,
88 size_precision,
89 price_increment,
90 size_increment,
91 multiplier,
92 lot_size,
93 max_quantity,
94 min_quantity,
95 max_notional,
96 min_notional,
97 max_price,
98 min_price,
99 margin_init,
100 margin_maint,
101 maker_fee,
102 taker_fee,
103 info_map,
104 ts_event.into(),
105 ts_init.into(),
106 )
107 .map_err(to_pyvalue_err)
108 }
109
110 fn __hash__(&self) -> isize {
111 let mut hasher = DefaultHasher::new();
112 self.hash(&mut hasher);
113 hasher.finish() as isize
114 }
115
116 fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
117 match op {
118 CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
119 CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
120 _ => py.NotImplemented(),
121 }
122 }
123
124 #[getter]
125 fn type_name(&self) -> &'static str {
126 stringify!(CryptoFuture)
127 }
128
129 #[getter]
130 #[pyo3(name = "id")]
131 fn py_id(&self) -> InstrumentId {
132 self.id
133 }
134
135 #[getter]
136 #[pyo3(name = "raw_symbol")]
137 fn py_raw_symbol(&self) -> Symbol {
138 self.raw_symbol
139 }
140
141 #[getter]
142 #[pyo3(name = "underlying")]
143 fn py_underlying(&self) -> Currency {
144 self.underlying
145 }
146
147 #[getter]
148 #[pyo3(name = "quote_currency")]
149 fn py_quote_currency(&self) -> Currency {
150 self.quote_currency
151 }
152
153 #[getter]
154 #[pyo3(name = "settlement_currency")]
155 fn py_settlement_currency(&self) -> Currency {
156 self.settlement_currency
157 }
158
159 #[getter]
160 #[pyo3(name = "is_inverse")]
161 fn py_is_inverse(&self) -> bool {
162 self.is_inverse
163 }
164
165 #[getter]
166 #[pyo3(name = "activation_ns")]
167 fn py_activation_ns(&self) -> u64 {
168 self.activation_ns.as_u64()
169 }
170
171 #[getter]
172 #[pyo3(name = "expiration_ns")]
173 fn py_expiration_ns(&self) -> u64 {
174 self.expiration_ns.as_u64()
175 }
176
177 #[getter]
178 #[pyo3(name = "price_precision")]
179 fn py_price_precision(&self) -> u8 {
180 self.price_precision
181 }
182
183 #[getter]
184 #[pyo3(name = "size_precision")]
185 fn py_size_precision(&self) -> u8 {
186 self.size_precision
187 }
188
189 #[getter]
190 #[pyo3(name = "price_increment")]
191 fn py_price_increment(&self) -> Price {
192 self.price_increment
193 }
194
195 #[getter]
196 #[pyo3(name = "size_increment")]
197 fn py_size_increment(&self) -> Quantity {
198 self.size_increment
199 }
200
201 #[getter]
202 #[pyo3(name = "multiplier")]
203 fn py_multiplier(&self) -> Quantity {
204 self.multiplier
205 }
206
207 #[getter]
208 #[pyo3(name = "lot_size")]
209 fn py_lot_size(&self) -> Quantity {
210 self.lot_size
211 }
212
213 #[getter]
214 #[pyo3(name = "max_quantity")]
215 fn py_max_quantity(&self) -> Option<Quantity> {
216 self.max_quantity
217 }
218
219 #[getter]
220 #[pyo3(name = "min_quantity")]
221 fn py_min_quantity(&self) -> Option<Quantity> {
222 self.min_quantity
223 }
224
225 #[getter]
226 #[pyo3(name = "max_notional")]
227 fn py_max_notional(&self) -> Option<Money> {
228 self.max_notional
229 }
230
231 #[getter]
232 #[pyo3(name = "min_notional")]
233 fn py_min_notional(&self) -> Option<Money> {
234 self.min_notional
235 }
236
237 #[getter]
238 #[pyo3(name = "max_price")]
239 fn py_max_price(&self) -> Option<Price> {
240 self.max_price
241 }
242
243 #[getter]
244 #[pyo3(name = "min_price")]
245 fn py_min_price(&self) -> Option<Price> {
246 self.min_price
247 }
248
249 #[getter]
250 #[pyo3(name = "margin_init")]
251 fn py_margin_init(&self) -> Decimal {
252 self.margin_init
253 }
254
255 #[getter]
256 #[pyo3(name = "margin_maint")]
257 fn py_margin_maint(&self) -> Decimal {
258 self.margin_maint
259 }
260
261 #[getter]
262 #[pyo3(name = "maker_fee")]
263 fn py_maker_fee(&self) -> Decimal {
264 self.maker_fee
265 }
266
267 #[getter]
268 #[pyo3(name = "taker_fee")]
269 fn py_taker_fee(&self) -> Decimal {
270 self.taker_fee
271 }
272
273 #[getter]
274 #[pyo3(name = "info")]
275 fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
276 if let Some(ref info_map) = self.info {
278 let py_dict = PyDict::new(py);
279
280 for (key, value) in info_map {
281 let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
283 let py_value =
284 PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
285 py_dict.set_item(key, py_value)?;
286 }
287 Ok(py_dict.unbind())
288 } else {
289 Ok(PyDict::new(py).unbind())
290 }
291 }
292
293 #[getter]
294 #[pyo3(name = "ts_event")]
295 fn py_ts_event(&self) -> u64 {
296 self.ts_event.as_u64()
297 }
298
299 #[getter]
300 #[pyo3(name = "ts_init")]
301 fn py_ts_init(&self) -> u64 {
302 self.ts_init.as_u64()
303 }
304
305 #[staticmethod]
306 #[pyo3(name = "from_dict")]
307 fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
308 register_crypto_currencies_from_dict(py, &values, &["underlying"]);
309 from_dict_pyo3(py, values)
310 }
311
312 #[pyo3(name = "to_dict")]
313 fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
314 let dict = PyDict::new(py);
315 dict.set_item("type", stringify!(CryptoFuture))?;
316 dict.set_item("id", self.id.to_string())?;
317 dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
318 dict.set_item("underlying", self.underlying.code.to_string())?;
319 dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
320 dict.set_item(
321 "settlement_currency",
322 self.settlement_currency.code.to_string(),
323 )?;
324 dict.set_item("is_inverse", self.is_inverse)?;
325 dict.set_item("activation_ns", self.activation_ns.as_u64())?;
326 dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
327 dict.set_item("price_precision", self.price_precision)?;
328 dict.set_item("size_precision", self.size_precision)?;
329 dict.set_item("price_increment", self.price_increment.to_string())?;
330 dict.set_item("size_increment", self.size_increment.to_string())?;
331 dict.set_item("margin_init", self.margin_init.to_string())?;
332 dict.set_item("margin_maint", self.margin_maint.to_string())?;
333 dict.set_item("multiplier", self.multiplier.to_string())?;
334 dict.set_item("lot_size", self.lot_size.to_string())?;
335 if let Some(ref info_map) = self.info {
337 let info_dict = PyDict::new(py);
338
339 for (key, value) in info_map {
340 let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
341 let py_value =
342 PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
343 info_dict.set_item(key, py_value)?;
344 }
345 dict.set_item("info", info_dict)?;
346 } else {
347 dict.set_item("info", PyDict::new(py))?;
348 }
349 dict.set_item("maker_fee", self.maker_fee.to_string())?;
350 dict.set_item("taker_fee", self.taker_fee.to_string())?;
351 dict.set_item("ts_event", self.ts_event.as_u64())?;
352 dict.set_item("ts_init", self.ts_init.as_u64())?;
353 match self.max_quantity {
354 Some(value) => dict.set_item("max_quantity", value.to_string())?,
355 None => dict.set_item("max_quantity", py.None())?,
356 }
357
358 match self.min_quantity {
359 Some(value) => dict.set_item("min_quantity", value.to_string())?,
360 None => dict.set_item("min_quantity", py.None())?,
361 }
362
363 match self.max_notional {
364 Some(value) => dict.set_item("max_notional", value.to_string())?,
365 None => dict.set_item("max_notional", py.None())?,
366 }
367
368 match self.min_notional {
369 Some(value) => dict.set_item("min_notional", value.to_string())?,
370 None => dict.set_item("min_notional", py.None())?,
371 }
372
373 match self.max_price {
374 Some(value) => dict.set_item("max_price", value.to_string())?,
375 None => dict.set_item("max_price", py.None())?,
376 }
377
378 match self.min_price {
379 Some(value) => dict.set_item("min_price", value.to_string())?,
380 None => dict.set_item("min_price", py.None())?,
381 }
382 Ok(dict.into())
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use pyo3::{prelude::*, types::PyDict};
389 use rstest::rstest;
390
391 use crate::{
392 enums::CurrencyType,
393 instruments::{CryptoFuture, stubs::*},
394 types::Currency,
395 };
396
397 #[rstest]
398 fn test_dict_round_trip(crypto_future_btcusdt: CryptoFuture) {
399 Python::initialize();
400 Python::attach(|py| {
401 let crypto_future = crypto_future_btcusdt;
402 let values = crypto_future.py_to_dict(py).unwrap();
403 let values: Py<PyDict> = values.extract(py).unwrap();
404 let new_crypto_future = CryptoFuture::py_from_dict(py, values).unwrap();
405 assert_eq!(crypto_future, new_crypto_future);
406 });
407 }
408
409 #[rstest]
410 fn test_from_dict_unknown_underlying_registers_as_crypto(crypto_future_btcusdt: CryptoFuture) {
411 Python::initialize();
414 Python::attach(|py| {
415 let values = crypto_future_btcusdt.py_to_dict(py).unwrap();
416 let values: Py<PyDict> = values.extract(py).unwrap();
417 values.bind(py).set_item("underlying", "NEWFUT").unwrap();
418
419 let new_future = CryptoFuture::py_from_dict(py, values).unwrap();
420 assert_eq!(new_future.underlying.code.as_str(), "NEWFUT");
421 assert_eq!(new_future.underlying.precision, 8);
422 assert_eq!(new_future.underlying.currency_type, CurrencyType::Crypto);
423 assert!(Currency::try_from_str("NEWFUT").is_some());
424 });
425 }
426}