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