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        match &self.info {
262            Some(info) => info.to_pydict(py),
263            None => Ok(PyDict::new(py).unbind()),
264        }
265    }
266
267    #[getter]
268    #[pyo3(name = "ts_event")]
269    fn py_ts_event(&self) -> u64 {
270        self.ts_event.as_u64()
271    }
272
273    #[getter]
274    #[pyo3(name = "ts_init")]
275    fn py_ts_init(&self) -> u64 {
276        self.ts_init.as_u64()
277    }
278
279    #[staticmethod]
280    #[pyo3(name = "from_dict")]
281    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
282        crate::python::instruments::from_dict_instrument_pyo3(py, values)
283    }
284
285    #[pyo3(name = "to_dict")]
286    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
287        let dict = PyDict::new(py);
288        dict.set_item("type", stringify!(BinaryOption))?;
289        dict.set_item("id", self.id.to_string())?;
290        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
291        dict.set_item("asset_class", self.asset_class.to_string())?;
292        dict.set_item("currency", self.currency.code.to_string())?;
293        dict.set_item("activation_ns", self.activation_ns.as_u64())?;
294        dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
295        dict.set_item("price_precision", self.price_precision)?;
296        dict.set_item("size_precision", self.size_precision)?;
297        dict.set_item("price_increment", self.price_increment.to_string())?;
298        dict.set_item("size_increment", self.size_increment.to_string())?;
299        dict.set_item("margin_init", self.margin_init.to_string())?;
300        dict.set_item("margin_maint", self.margin_maint.to_string())?;
301        dict.set_item("ts_event", self.ts_event.as_u64())?;
302        dict.set_item("ts_init", self.ts_init.as_u64())?;
303        dict.set_item("info", self.py_info(py)?)?;
304        dict.set_item("event_id", self.event_id.map(|value| value.to_string()))?;
305
306        match &self.outcome {
307            Some(value) => dict.set_item("outcome", value.to_string())?,
308            None => dict.set_item("outcome", py.None())?,
309        }
310
311        match &self.description {
312            Some(value) => dict.set_item("description", value.to_string())?,
313            None => dict.set_item("description", py.None())?,
314        }
315
316        match self.max_quantity {
317            Some(value) => dict.set_item("max_quantity", value.to_string())?,
318            None => dict.set_item("max_quantity", py.None())?,
319        }
320
321        match self.min_quantity {
322            Some(value) => dict.set_item("min_quantity", value.to_string())?,
323            None => dict.set_item("min_quantity", py.None())?,
324        }
325
326        match self.max_notional {
327            Some(value) => dict.set_item("max_notional", value.to_string())?,
328            None => dict.set_item("max_notional", py.None())?,
329        }
330
331        match self.min_notional {
332            Some(value) => dict.set_item("min_notional", value.to_string())?,
333            None => dict.set_item("min_notional", py.None())?,
334        }
335
336        match self.max_price {
337            Some(value) => dict.set_item("max_price", value.to_string())?,
338            None => dict.set_item("max_price", py.None())?,
339        }
340
341        match self.min_price {
342            Some(value) => dict.set_item("min_price", value.to_string())?,
343            None => dict.set_item("min_price", py.None())?,
344        }
345        dict.set_item(
346            "tick_scheme",
347            crate::python::instruments::tick_scheme_to_py(self),
348        )?;
349        Ok(dict.into())
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use std::sync::Arc;
356
357    use pyo3::{prelude::*, types::PyDict};
358    use rstest::rstest;
359
360    use crate::instruments::{BinaryOption, stubs::*};
361
362    #[rstest]
363    #[case(None)]
364    #[case(Some("event-123"))]
365    fn test_python_constructor_event_id(
366        binary_option: BinaryOption,
367        #[case] event_id: Option<&str>,
368    ) {
369        Python::initialize();
370        Python::attach(|py| {
371            let kwargs = PyDict::new(py);
372            kwargs.set_item("instrument_id", binary_option.id).unwrap();
373            kwargs
374                .set_item("raw_symbol", binary_option.raw_symbol)
375                .unwrap();
376            kwargs
377                .set_item("asset_class", binary_option.asset_class)
378                .unwrap();
379            kwargs.set_item("currency", binary_option.currency).unwrap();
380            kwargs
381                .set_item("activation_ns", binary_option.activation_ns.as_u64())
382                .unwrap();
383            kwargs
384                .set_item("expiration_ns", binary_option.expiration_ns.as_u64())
385                .unwrap();
386            kwargs
387                .set_item("price_precision", binary_option.price_precision)
388                .unwrap();
389            kwargs
390                .set_item("size_precision", binary_option.size_precision)
391                .unwrap();
392            kwargs
393                .set_item("price_increment", binary_option.price_increment)
394                .unwrap();
395            kwargs
396                .set_item("size_increment", binary_option.size_increment)
397                .unwrap();
398            kwargs.set_item("ts_event", 1_u64).unwrap();
399            kwargs.set_item("ts_init", 2_u64).unwrap();
400            if let Some(event_id) = event_id {
401                kwargs.set_item("event_id", event_id).unwrap();
402            }
403
404            let instance = py
405                .get_type::<BinaryOption>()
406                .call((), Some(&kwargs))
407                .unwrap();
408            assert_eq!(
409                instance
410                    .getattr("event_id")
411                    .unwrap()
412                    .extract::<Option<String>>()
413                    .unwrap()
414                    .as_deref(),
415                event_id
416            );
417            let constructed = instance.extract::<BinaryOption>().unwrap();
418            assert_eq!(constructed.event_id.map(|id| id.as_str()), event_id);
419            assert_eq!(constructed.ts_event.as_u64(), 1);
420            assert_eq!(constructed.ts_init.as_u64(), 2);
421        });
422    }
423
424    #[rstest]
425    fn test_dict_round_trip(mut binary_option: BinaryOption) {
426        binary_option.event_id = Some("event-123".into());
427
428        let info = nautilus_core::Params::new(
429            [(
430                "gamma_market".to_string(),
431                "0.1234567890123456789012345678".into(),
432            )]
433            .into(),
434        );
435        let mut info = info.to_shared_map();
436
437        let event = Arc::new(
438            serde_json::json!({"markets": ["first", "second"]})
439                .to_string()
440                .into(),
441        );
442        info.insert("gamma_event".to_string(), Arc::clone(&event));
443        let info = nautilus_core::Params::from_shared(info);
444        let retained = info.estimated_heap_size();
445        binary_option.info = Some(info);
446        Python::initialize();
447        Python::attach(|py| {
448            let info = binary_option.py_info(py).unwrap();
449            assert_eq!(
450                info.bind(py)
451                    .get_item("gamma_event")
452                    .unwrap()
453                    .unwrap()
454                    .extract::<String>()
455                    .unwrap(),
456                event.as_str().unwrap()
457            );
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        assert_eq!(
469            binary_option.info.as_ref().unwrap().estimated_heap_size(),
470            retained
471        );
472    }
473}