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, maker_fee=None, taker_fee=None, tick_scheme=None, info=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    ) -> PyResult<Self> {
71        // Convert Python dict to Params
72        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            asset_class,
82            currency,
83            activation_ns.into(),
84            expiration_ns.into(),
85            price_precision,
86            size_precision,
87            price_increment,
88            size_increment,
89            outcome.map(|x| Ustr::from(&x)),
90            description.map(|x| Ustr::from(&x)),
91            max_quantity,
92            min_quantity,
93            max_notional,
94            min_notional,
95            max_price,
96            min_price,
97            margin_init,
98            margin_maint,
99            maker_fee,
100            taker_fee,
101            tick_scheme.map(|name| ustr::Ustr::from(name.as_str())),
102            info_map,
103            ts_event.into(),
104            ts_init.into(),
105        )
106        .map_err(to_pyvalue_err)
107    }
108
109    fn __hash__(&self) -> isize {
110        let mut hasher = DefaultHasher::new();
111        self.hash(&mut hasher);
112        hasher.finish() as isize
113    }
114
115    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
116        match op {
117            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
118            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
119            _ => py.NotImplemented(),
120        }
121    }
122
123    #[getter]
124    fn type_name(&self) -> &'static str {
125        stringify!(BinaryOption)
126    }
127
128    #[getter]
129    #[pyo3(name = "id")]
130    fn py_id(&self) -> InstrumentId {
131        self.id
132    }
133
134    #[getter]
135    #[pyo3(name = "raw_symbol")]
136    fn py_raw_symbol(&self) -> Symbol {
137        self.raw_symbol
138    }
139
140    #[getter]
141    #[pyo3(name = "asset_class")]
142    fn py_asset_class(&self) -> AssetClass {
143        self.asset_class
144    }
145
146    #[getter]
147    #[pyo3(name = "currency")]
148    fn py_currency(&self) -> Currency {
149        self.currency
150    }
151
152    #[getter]
153    #[pyo3(name = "activation_ns")]
154    fn py_activation_ns(&self) -> u64 {
155        self.activation_ns.as_u64()
156    }
157
158    #[getter]
159    #[pyo3(name = "expiration_ns")]
160    fn py_expiration_ns(&self) -> u64 {
161        self.expiration_ns.as_u64()
162    }
163
164    #[getter]
165    #[pyo3(name = "price_precision")]
166    fn py_price_precision(&self) -> u8 {
167        self.price_precision
168    }
169
170    #[getter]
171    #[pyo3(name = "size_precision")]
172    fn py_size_precision(&self) -> u8 {
173        self.size_precision
174    }
175
176    #[getter]
177    #[pyo3(name = "price_increment")]
178    fn py_price_increment(&self) -> Price {
179        self.price_increment
180    }
181
182    #[getter]
183    #[pyo3(name = "size_increment")]
184    fn py_size_increment(&self) -> Quantity {
185        self.size_increment
186    }
187
188    #[getter]
189    #[pyo3(name = "outcome")]
190    fn py_outcome(&self) -> Option<&str> {
191        match self.outcome {
192            Some(outcome) => Some(outcome.as_str()),
193            None => None,
194        }
195    }
196
197    #[getter]
198    #[pyo3(name = "description")]
199    fn py_description(&self) -> Option<&str> {
200        match self.description {
201            Some(description) => Some(description.as_str()),
202            None => None,
203        }
204    }
205
206    #[getter]
207    #[pyo3(name = "max_quantity")]
208    fn py_max_quantity(&self) -> Option<Quantity> {
209        self.max_quantity
210    }
211
212    #[getter]
213    #[pyo3(name = "min_quantity")]
214    fn py_min_quantity(&self) -> Option<Quantity> {
215        self.min_quantity
216    }
217
218    #[getter]
219    #[pyo3(name = "max_notional")]
220    fn py_max_notional(&self) -> Option<Money> {
221        self.max_notional
222    }
223
224    #[getter]
225    #[pyo3(name = "min_notional")]
226    fn py_min_notional(&self) -> Option<Money> {
227        self.min_notional
228    }
229
230    #[getter]
231    #[pyo3(name = "max_price")]
232    fn py_max_price(&self) -> Option<Price> {
233        self.max_price
234    }
235
236    #[getter]
237    #[pyo3(name = "min_price")]
238    fn py_min_price(&self) -> Option<Price> {
239        self.min_price
240    }
241
242    #[getter]
243    #[pyo3(name = "margin_init")]
244    fn py_margin_init(&self) -> Decimal {
245        self.margin_init
246    }
247
248    #[getter]
249    #[pyo3(name = "margin_maint")]
250    fn py_margin_maint(&self) -> Decimal {
251        self.margin_maint
252    }
253
254    #[getter]
255    #[pyo3(name = "maker_fee")]
256    fn py_maker_fee(&self) -> Decimal {
257        self.maker_fee
258    }
259
260    #[getter]
261    #[pyo3(name = "taker_fee")]
262    fn py_taker_fee(&self) -> Decimal {
263        self.taker_fee
264    }
265
266    #[getter]
267    #[pyo3(name = "info")]
268    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
269        // Convert HashMap<String, serde_json::Value> back to Python dict
270        if let Some(ref info_map) = self.info {
271            let py_dict = PyDict::new(py);
272
273            for (key, value) in info_map {
274                // Convert serde_json::Value back to Python object via JSON
275                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
276                let py_value =
277                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
278                py_dict.set_item(key, py_value)?;
279            }
280            Ok(py_dict.unbind())
281        } else {
282            Ok(PyDict::new(py).unbind())
283        }
284    }
285
286    #[getter]
287    #[pyo3(name = "ts_event")]
288    fn py_ts_event(&self) -> u64 {
289        self.ts_event.as_u64()
290    }
291
292    #[getter]
293    #[pyo3(name = "ts_init")]
294    fn py_ts_init(&self) -> u64 {
295        self.ts_init.as_u64()
296    }
297
298    #[staticmethod]
299    #[pyo3(name = "from_dict")]
300    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
301        crate::python::instruments::from_dict_instrument_pyo3(py, values)
302    }
303
304    #[pyo3(name = "to_dict")]
305    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
306        let dict = PyDict::new(py);
307        dict.set_item("type", stringify!(BinaryOption))?;
308        dict.set_item("id", self.id.to_string())?;
309        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
310        dict.set_item("asset_class", self.asset_class.to_string())?;
311        dict.set_item("currency", self.currency.code.to_string())?;
312        dict.set_item("activation_ns", self.activation_ns.as_u64())?;
313        dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
314        dict.set_item("price_precision", self.price_precision)?;
315        dict.set_item("size_precision", self.size_precision)?;
316        dict.set_item("price_increment", self.price_increment.to_string())?;
317        dict.set_item("size_increment", self.size_increment.to_string())?;
318        dict.set_item("margin_init", self.margin_init.to_string())?;
319        dict.set_item("margin_maint", self.margin_maint.to_string())?;
320        dict.set_item("maker_fee", self.maker_fee.to_string())?;
321        dict.set_item("taker_fee", self.taker_fee.to_string())?;
322        dict.set_item("ts_event", self.ts_event.as_u64())?;
323        dict.set_item("ts_init", self.ts_init.as_u64())?;
324        // Serialize info dict
325        if let Some(ref info_map) = self.info {
326            let info_dict = PyDict::new(py);
327
328            for (key, value) in info_map {
329                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
330                let py_value =
331                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
332                info_dict.set_item(key, py_value)?;
333            }
334            dict.set_item("info", info_dict)?;
335        } else {
336            dict.set_item("info", PyDict::new(py))?;
337        }
338
339        match &self.outcome {
340            Some(value) => dict.set_item("outcome", value.to_string())?,
341            None => dict.set_item("outcome", py.None())?,
342        }
343
344        match &self.description {
345            Some(value) => dict.set_item("description", value.to_string())?,
346            None => dict.set_item("description", py.None())?,
347        }
348
349        match self.max_quantity {
350            Some(value) => dict.set_item("max_quantity", value.to_string())?,
351            None => dict.set_item("max_quantity", py.None())?,
352        }
353
354        match self.min_quantity {
355            Some(value) => dict.set_item("min_quantity", value.to_string())?,
356            None => dict.set_item("min_quantity", py.None())?,
357        }
358
359        match self.max_notional {
360            Some(value) => dict.set_item("max_notional", value.to_string())?,
361            None => dict.set_item("max_notional", py.None())?,
362        }
363
364        match self.min_notional {
365            Some(value) => dict.set_item("min_notional", value.to_string())?,
366            None => dict.set_item("min_notional", py.None())?,
367        }
368
369        match self.max_price {
370            Some(value) => dict.set_item("max_price", value.to_string())?,
371            None => dict.set_item("max_price", py.None())?,
372        }
373
374        match self.min_price {
375            Some(value) => dict.set_item("min_price", value.to_string())?,
376            None => dict.set_item("min_price", py.None())?,
377        }
378        dict.set_item(
379            "tick_scheme",
380            crate::python::instruments::tick_scheme_to_py(self),
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::instruments::{BinaryOption, stubs::*};
392
393    #[rstest]
394    fn test_dict_round_trip(binary_option: BinaryOption) {
395        Python::initialize();
396        Python::attach(|py| {
397            let values = binary_option.py_to_dict(py).unwrap();
398            let values: Py<PyDict> = values.extract(py).unwrap();
399            let new_binary_option = BinaryOption::py_from_dict(py, values).unwrap();
400            assert_eq!(binary_option, new_binary_option);
401        });
402    }
403}