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;
27use ustr::Ustr;
28
29use crate::{
30 enums::AssetClass,
31 identifiers::{InstrumentId, Symbol},
32 instruments::BinaryOption,
33 types::{Currency, Money, Price, Quantity},
34};
35
36#[pymethods]
37#[pyo3_stub_gen::derive::gen_stub_pymethods]
38impl BinaryOption {
39 #[expect(clippy::too_many_arguments)]
41 #[new]
42 #[pyo3(signature = (instrument_id, raw_symbol, asset_class, currency, activation_ns, expiration_ns, price_precision, size_precision, price_increment, size_increment, ts_event, ts_init, outcome=None, description=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, event_id=None))]
43 fn py_new(
44 instrument_id: InstrumentId,
45 raw_symbol: Symbol,
46 asset_class: AssetClass,
47 currency: Currency,
48 activation_ns: u64,
49 expiration_ns: u64,
50 price_precision: u8,
51 size_precision: u8,
52 price_increment: Price,
53 size_increment: Quantity,
54 ts_event: u64,
55 ts_init: u64,
56 outcome: Option<String>,
57 description: Option<String>,
58 max_quantity: Option<Quantity>,
59 min_quantity: Option<Quantity>,
60 max_notional: Option<Money>,
61 min_notional: Option<Money>,
62 max_price: Option<Price>,
63 min_price: Option<Price>,
64 margin_init: Option<Decimal>,
65 margin_maint: Option<Decimal>,
66 maker_fee: Option<Decimal>,
67 taker_fee: Option<Decimal>,
68 tick_scheme: Option<String>,
69 info: Option<Py<PyDict>>,
70 event_id: Option<String>,
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::builder()
80 .instrument_id(instrument_id)
81 .raw_symbol(raw_symbol)
82 .asset_class(asset_class)
83 .currency(currency)
84 .activation_ns(activation_ns.into())
85 .expiration_ns(expiration_ns.into())
86 .price_precision(price_precision)
87 .size_precision(size_precision)
88 .price_increment(price_increment)
89 .size_increment(size_increment)
90 .maybe_event_id(event_id.map(|value| Ustr::from(&value)))
91 .maybe_outcome(outcome.map(|x| Ustr::from(&x)))
92 .maybe_description(description.map(|x| Ustr::from(&x)))
93 .maybe_max_quantity(max_quantity)
94 .maybe_min_quantity(min_quantity)
95 .maybe_max_notional(max_notional)
96 .maybe_min_notional(min_notional)
97 .maybe_max_price(max_price)
98 .maybe_min_price(min_price)
99 .maybe_margin_init(margin_init)
100 .maybe_margin_maint(margin_maint)
101 .maybe_maker_fee(maker_fee)
102 .maybe_taker_fee(taker_fee)
103 .maybe_tick_scheme(tick_scheme.map(|name| ustr::Ustr::from(name.as_str())))
104 .maybe_info(info_map)
105 .ts_event(ts_event.into())
106 .ts_init(ts_init.into())
107 .build()
108 .map_err(to_pyvalue_err)
109 }
110
111 fn __hash__(&self) -> isize {
112 let mut hasher = DefaultHasher::new();
113 self.hash(&mut hasher);
114 hasher.finish() as isize
115 }
116
117 fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
118 match op {
119 CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
120 CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
121 _ => py.NotImplemented(),
122 }
123 }
124
125 #[getter]
126 fn type_name(&self) -> &'static str {
127 stringify!(BinaryOption)
128 }
129
130 #[getter]
131 #[pyo3(name = "id")]
132 fn py_id(&self) -> InstrumentId {
133 self.id
134 }
135
136 #[getter]
137 #[pyo3(name = "raw_symbol")]
138 fn py_raw_symbol(&self) -> Symbol {
139 self.raw_symbol
140 }
141
142 #[getter]
143 #[pyo3(name = "asset_class")]
144 fn py_asset_class(&self) -> AssetClass {
145 self.asset_class
146 }
147
148 #[getter]
149 #[pyo3(name = "currency")]
150 fn py_currency(&self) -> Currency {
151 self.currency
152 }
153
154 #[getter]
155 #[pyo3(name = "activation_ns")]
156 fn py_activation_ns(&self) -> u64 {
157 self.activation_ns.as_u64()
158 }
159
160 #[getter]
161 #[pyo3(name = "expiration_ns")]
162 fn py_expiration_ns(&self) -> u64 {
163 self.expiration_ns.as_u64()
164 }
165
166 #[getter]
167 #[pyo3(name = "price_precision")]
168 fn py_price_precision(&self) -> u8 {
169 self.price_precision
170 }
171
172 #[getter]
173 #[pyo3(name = "size_precision")]
174 fn py_size_precision(&self) -> u8 {
175 self.size_precision
176 }
177
178 #[getter]
179 #[pyo3(name = "price_increment")]
180 fn py_price_increment(&self) -> Price {
181 self.price_increment
182 }
183
184 #[getter]
185 #[pyo3(name = "size_increment")]
186 fn py_size_increment(&self) -> Quantity {
187 self.size_increment
188 }
189
190 #[getter]
191 #[pyo3(name = "event_id")]
192 fn py_event_id(&self) -> Option<&str> {
193 self.event_id.map(|value| value.as_str())
194 }
195
196 #[getter]
197 #[pyo3(name = "outcome")]
198 fn py_outcome(&self) -> Option<&str> {
199 match self.outcome {
200 Some(outcome) => Some(outcome.as_str()),
201 None => None,
202 }
203 }
204
205 #[getter]
206 #[pyo3(name = "description")]
207 fn py_description(&self) -> Option<&str> {
208 match self.description {
209 Some(description) => Some(description.as_str()),
210 None => None,
211 }
212 }
213
214 #[getter]
215 #[pyo3(name = "max_quantity")]
216 fn py_max_quantity(&self) -> Option<Quantity> {
217 self.max_quantity
218 }
219
220 #[getter]
221 #[pyo3(name = "min_quantity")]
222 fn py_min_quantity(&self) -> Option<Quantity> {
223 self.min_quantity
224 }
225
226 #[getter]
227 #[pyo3(name = "max_notional")]
228 fn py_max_notional(&self) -> Option<Money> {
229 self.max_notional
230 }
231
232 #[getter]
233 #[pyo3(name = "min_notional")]
234 fn py_min_notional(&self) -> Option<Money> {
235 self.min_notional
236 }
237
238 #[getter]
239 #[pyo3(name = "max_price")]
240 fn py_max_price(&self) -> Option<Price> {
241 self.max_price
242 }
243
244 #[getter]
245 #[pyo3(name = "min_price")]
246 fn py_min_price(&self) -> Option<Price> {
247 self.min_price
248 }
249
250 #[getter]
251 #[pyo3(name = "margin_init")]
252 fn py_margin_init(&self) -> Decimal {
253 self.margin_init
254 }
255
256 #[getter]
257 #[pyo3(name = "margin_maint")]
258 fn py_margin_maint(&self) -> Decimal {
259 self.margin_maint
260 }
261
262 #[getter]
263 #[pyo3(name = "maker_fee")]
264 fn py_maker_fee(&self) -> Decimal {
265 self.maker_fee
266 }
267
268 #[getter]
269 #[pyo3(name = "taker_fee")]
270 fn py_taker_fee(&self) -> Decimal {
271 self.taker_fee
272 }
273
274 #[getter]
275 #[pyo3(name = "info")]
276 fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
277 if let Some(ref info_map) = self.info {
279 let py_dict = PyDict::new(py);
280
281 for (key, value) in info_map {
282 let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
284 let py_value =
285 PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
286 py_dict.set_item(key, py_value)?;
287 }
288 Ok(py_dict.unbind())
289 } else {
290 Ok(PyDict::new(py).unbind())
291 }
292 }
293
294 #[getter]
295 #[pyo3(name = "ts_event")]
296 fn py_ts_event(&self) -> u64 {
297 self.ts_event.as_u64()
298 }
299
300 #[getter]
301 #[pyo3(name = "ts_init")]
302 fn py_ts_init(&self) -> u64 {
303 self.ts_init.as_u64()
304 }
305
306 #[staticmethod]
307 #[pyo3(name = "from_dict")]
308 fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
309 crate::python::instruments::from_dict_instrument_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!(BinaryOption))?;
316 dict.set_item("id", self.id.to_string())?;
317 dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
318 dict.set_item("asset_class", self.asset_class.to_string())?;
319 dict.set_item("currency", self.currency.code.to_string())?;
320 dict.set_item("activation_ns", self.activation_ns.as_u64())?;
321 dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
322 dict.set_item("price_precision", self.price_precision)?;
323 dict.set_item("size_precision", self.size_precision)?;
324 dict.set_item("price_increment", self.price_increment.to_string())?;
325 dict.set_item("size_increment", self.size_increment.to_string())?;
326 dict.set_item("margin_init", self.margin_init.to_string())?;
327 dict.set_item("margin_maint", self.margin_maint.to_string())?;
328 dict.set_item("maker_fee", self.maker_fee.to_string())?;
329 dict.set_item("taker_fee", self.taker_fee.to_string())?;
330 dict.set_item("ts_event", self.ts_event.as_u64())?;
331 dict.set_item("ts_init", self.ts_init.as_u64())?;
332 if let Some(ref info_map) = self.info {
334 let info_dict = PyDict::new(py);
335
336 for (key, value) in info_map {
337 let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
338 let py_value =
339 PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
340 info_dict.set_item(key, py_value)?;
341 }
342 dict.set_item("info", info_dict)?;
343 } else {
344 dict.set_item("info", PyDict::new(py))?;
345 }
346
347 dict.set_item("event_id", self.event_id.map(|value| value.to_string()))?;
348
349 match &self.outcome {
350 Some(value) => dict.set_item("outcome", value.to_string())?,
351 None => dict.set_item("outcome", py.None())?,
352 }
353
354 match &self.description {
355 Some(value) => dict.set_item("description", value.to_string())?,
356 None => dict.set_item("description", py.None())?,
357 }
358
359 match self.max_quantity {
360 Some(value) => dict.set_item("max_quantity", value.to_string())?,
361 None => dict.set_item("max_quantity", py.None())?,
362 }
363
364 match self.min_quantity {
365 Some(value) => dict.set_item("min_quantity", value.to_string())?,
366 None => dict.set_item("min_quantity", py.None())?,
367 }
368
369 match self.max_notional {
370 Some(value) => dict.set_item("max_notional", value.to_string())?,
371 None => dict.set_item("max_notional", py.None())?,
372 }
373
374 match self.min_notional {
375 Some(value) => dict.set_item("min_notional", value.to_string())?,
376 None => dict.set_item("min_notional", py.None())?,
377 }
378
379 match self.max_price {
380 Some(value) => dict.set_item("max_price", value.to_string())?,
381 None => dict.set_item("max_price", py.None())?,
382 }
383
384 match self.min_price {
385 Some(value) => dict.set_item("min_price", value.to_string())?,
386 None => dict.set_item("min_price", py.None())?,
387 }
388 dict.set_item(
389 "tick_scheme",
390 crate::python::instruments::tick_scheme_to_py(self),
391 )?;
392 Ok(dict.into())
393 }
394}
395
396#[cfg(test)]
397mod tests {
398 use pyo3::{prelude::*, types::PyDict};
399 use rstest::rstest;
400
401 use crate::instruments::{BinaryOption, stubs::*};
402
403 #[rstest]
404 #[case(None)]
405 #[case(Some("event-123"))]
406 fn test_python_constructor_event_id(
407 binary_option: BinaryOption,
408 #[case] event_id: Option<&str>,
409 ) {
410 Python::initialize();
411 Python::attach(|py| {
412 let kwargs = PyDict::new(py);
413 kwargs.set_item("instrument_id", binary_option.id).unwrap();
414 kwargs
415 .set_item("raw_symbol", binary_option.raw_symbol)
416 .unwrap();
417 kwargs
418 .set_item("asset_class", binary_option.asset_class)
419 .unwrap();
420 kwargs.set_item("currency", binary_option.currency).unwrap();
421 kwargs
422 .set_item("activation_ns", binary_option.activation_ns.as_u64())
423 .unwrap();
424 kwargs
425 .set_item("expiration_ns", binary_option.expiration_ns.as_u64())
426 .unwrap();
427 kwargs
428 .set_item("price_precision", binary_option.price_precision)
429 .unwrap();
430 kwargs
431 .set_item("size_precision", binary_option.size_precision)
432 .unwrap();
433 kwargs
434 .set_item("price_increment", binary_option.price_increment)
435 .unwrap();
436 kwargs
437 .set_item("size_increment", binary_option.size_increment)
438 .unwrap();
439 kwargs.set_item("ts_event", 1_u64).unwrap();
440 kwargs.set_item("ts_init", 2_u64).unwrap();
441 if let Some(event_id) = event_id {
442 kwargs.set_item("event_id", event_id).unwrap();
443 }
444
445 let instance = py
446 .get_type::<BinaryOption>()
447 .call((), Some(&kwargs))
448 .unwrap();
449 assert_eq!(
450 instance
451 .getattr("event_id")
452 .unwrap()
453 .extract::<Option<String>>()
454 .unwrap()
455 .as_deref(),
456 event_id
457 );
458 let constructed = instance.extract::<BinaryOption>().unwrap();
459 assert_eq!(constructed.event_id.map(|id| id.as_str()), event_id);
460 assert_eq!(constructed.ts_event.as_u64(), 1);
461 assert_eq!(constructed.ts_init.as_u64(), 2);
462 });
463 }
464
465 #[rstest]
466 fn test_dict_round_trip(mut binary_option: BinaryOption) {
467 binary_option.event_id = Some("event-123".into());
468 let mut info = nautilus_core::Params::new();
469 info.insert(
470 "gamma_market".to_string(),
471 "0.1234567890123456789012345678".into(),
472 );
473 binary_option.info = Some(info);
474 Python::initialize();
475 Python::attach(|py| {
476 let values = binary_option.py_to_dict(py).unwrap();
477 let values: Py<PyDict> = values.extract(py).unwrap();
478 let new_binary_option = BinaryOption::py_from_dict(py, values).unwrap();
479 assert_eq!(new_binary_option.event_id, Some("event-123".into()));
480 assert_eq!(
481 serde_json::to_value(&binary_option).unwrap(),
482 serde_json::to_value(&new_binary_option).unwrap(),
483 );
484 });
485 }
486}