Skip to main content

nautilus_model/python/instruments/
binary_option.rs

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