nautilus_model/python/instruments/
binary_option.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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::python::{
22    IntoPyObjectNautilusExt, serialization::from_dict_pyo3, to_pyvalue_err,
23};
24use pyo3::{basic::CompareOp, prelude::*, types::PyDict};
25use rust_decimal::Decimal;
26use ustr::Ustr;
27
28use crate::{
29    enums::AssetClass,
30    identifiers::{InstrumentId, Symbol},
31    instruments::BinaryOption,
32    types::{Currency, Money, Price, Quantity},
33};
34
35#[pymethods]
36impl BinaryOption {
37    #[allow(clippy::too_many_arguments)]
38    #[new]
39    #[pyo3(signature = (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))]
40    fn py_new(
41        id: InstrumentId,
42        raw_symbol: Symbol,
43        asset_class: AssetClass,
44        currency: Currency,
45        activation_ns: u64,
46        expiration_ns: u64,
47        price_precision: u8,
48        size_precision: u8,
49        price_increment: Price,
50        size_increment: Quantity,
51        ts_event: u64,
52        ts_init: u64,
53        outcome: Option<String>,
54        description: Option<String>,
55        max_quantity: Option<Quantity>,
56        min_quantity: Option<Quantity>,
57        max_notional: Option<Money>,
58        min_notional: Option<Money>,
59        max_price: Option<Price>,
60        min_price: Option<Price>,
61        margin_init: Option<Decimal>,
62        margin_maint: Option<Decimal>,
63        maker_fee: Option<Decimal>,
64        taker_fee: Option<Decimal>,
65    ) -> PyResult<Self> {
66        Self::new_checked(
67            id,
68            raw_symbol,
69            asset_class,
70            currency,
71            activation_ns.into(),
72            expiration_ns.into(),
73            price_precision,
74            size_precision,
75            price_increment,
76            size_increment,
77            outcome.map(|x| Ustr::from(&x)),
78            description.map(|x| Ustr::from(&x)),
79            max_quantity,
80            min_quantity,
81            max_notional,
82            min_notional,
83            max_price,
84            min_price,
85            margin_init,
86            margin_maint,
87            maker_fee,
88            taker_fee,
89            ts_event.into(),
90            ts_init.into(),
91        )
92        .map_err(to_pyvalue_err)
93    }
94
95    fn __hash__(&self) -> isize {
96        let mut hasher = DefaultHasher::new();
97        self.hash(&mut hasher);
98        hasher.finish() as isize
99    }
100
101    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
102        match op {
103            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
104            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
105            _ => py.NotImplemented(),
106        }
107    }
108
109    #[getter]
110    fn type_str(&self) -> &str {
111        stringify!(BinaryOption)
112    }
113
114    #[getter]
115    #[pyo3(name = "id")]
116    fn py_id(&self) -> InstrumentId {
117        self.id
118    }
119
120    #[getter]
121    #[pyo3(name = "raw_symbol")]
122    fn py_raw_symbol(&self) -> Symbol {
123        self.raw_symbol
124    }
125
126    #[getter]
127    #[pyo3(name = "asset_class")]
128    fn py_asset_class(&self) -> AssetClass {
129        self.asset_class
130    }
131
132    #[getter]
133    #[pyo3(name = "currency")]
134    fn py_currency(&self) -> Currency {
135        self.currency
136    }
137
138    #[getter]
139    #[pyo3(name = "activation_ns")]
140    fn py_activation_ns(&self) -> u64 {
141        self.activation_ns.as_u64()
142    }
143
144    #[getter]
145    #[pyo3(name = "expiration_ns")]
146    fn py_expiration_ns(&self) -> u64 {
147        self.expiration_ns.as_u64()
148    }
149
150    #[getter]
151    #[pyo3(name = "price_precision")]
152    fn py_price_precision(&self) -> u8 {
153        self.price_precision
154    }
155
156    #[getter]
157    #[pyo3(name = "size_precision")]
158    fn py_size_precision(&self) -> u8 {
159        self.size_precision
160    }
161
162    #[getter]
163    #[pyo3(name = "price_increment")]
164    fn py_price_increment(&self) -> Price {
165        self.price_increment
166    }
167
168    #[getter]
169    #[pyo3(name = "size_increment")]
170    fn py_size_increment(&self) -> Quantity {
171        self.size_increment
172    }
173
174    #[getter]
175    #[pyo3(name = "outcome")]
176    fn py_outcome(&self) -> Option<&str> {
177        match self.outcome {
178            Some(outcome) => Some(outcome.as_str()),
179            None => None,
180        }
181    }
182
183    #[getter]
184    #[pyo3(name = "description")]
185    fn py_description(&self) -> Option<&str> {
186        match self.description {
187            Some(description) => Some(description.as_str()),
188            None => None,
189        }
190    }
191
192    #[getter]
193    #[pyo3(name = "max_quantity")]
194    fn py_max_quantity(&self) -> Option<Quantity> {
195        self.max_quantity
196    }
197
198    #[getter]
199    #[pyo3(name = "min_quantity")]
200    fn py_min_quantity(&self) -> Option<Quantity> {
201        self.min_quantity
202    }
203
204    #[getter]
205    #[pyo3(name = "max_notional")]
206    fn py_max_notional(&self) -> Option<Money> {
207        self.max_notional
208    }
209
210    #[getter]
211    #[pyo3(name = "min_notional")]
212    fn py_min_notional(&self) -> Option<Money> {
213        self.min_notional
214    }
215
216    #[getter]
217    #[pyo3(name = "max_price")]
218    fn py_max_price(&self) -> Option<Price> {
219        self.max_price
220    }
221
222    #[getter]
223    #[pyo3(name = "min_price")]
224    fn py_min_price(&self) -> Option<Price> {
225        self.min_price
226    }
227
228    #[getter]
229    #[pyo3(name = "margin_init")]
230    fn py_margin_init(&self) -> Decimal {
231        self.margin_init
232    }
233
234    #[getter]
235    #[pyo3(name = "margin_maint")]
236    fn py_margin_maint(&self) -> Decimal {
237        self.margin_maint
238    }
239
240    #[getter]
241    #[pyo3(name = "maker_fee")]
242    fn py_maker_fee(&self) -> Decimal {
243        self.maker_fee
244    }
245
246    #[getter]
247    #[pyo3(name = "taker_fee")]
248    fn py_taker_fee(&self) -> Decimal {
249        self.taker_fee
250    }
251
252    #[getter]
253    #[pyo3(name = "info")]
254    fn py_info(&self, py: Python<'_>) -> PyResult<PyObject> {
255        Ok(PyDict::new(py).into())
256    }
257
258    #[getter]
259    #[pyo3(name = "ts_event")]
260    fn py_ts_event(&self) -> u64 {
261        self.ts_event.as_u64()
262    }
263
264    #[getter]
265    #[pyo3(name = "ts_init")]
266    fn py_ts_init(&self) -> u64 {
267        self.ts_init.as_u64()
268    }
269
270    #[staticmethod]
271    #[pyo3(name = "from_dict")]
272    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
273        from_dict_pyo3(py, values)
274    }
275
276    #[pyo3(name = "to_dict")]
277    fn py_to_dict(&self, py: Python<'_>) -> PyResult<PyObject> {
278        let dict = PyDict::new(py);
279        dict.set_item("type", stringify!(BinaryOption))?;
280        dict.set_item("id", self.id.to_string())?;
281        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
282        dict.set_item("asset_class", self.asset_class.to_string())?;
283        dict.set_item("currency", self.currency.code.to_string())?;
284        dict.set_item("activation_ns", self.activation_ns.as_u64())?;
285        dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
286        dict.set_item("price_precision", self.price_precision)?;
287        dict.set_item("size_precision", self.size_precision)?;
288        dict.set_item("price_increment", self.price_increment.to_string())?;
289        dict.set_item("size_increment", self.size_increment.to_string())?;
290        dict.set_item("margin_init", self.margin_init.to_string())?;
291        dict.set_item("margin_maint", self.margin_maint.to_string())?;
292        dict.set_item("maker_fee", self.maker_fee.to_string())?;
293        dict.set_item("taker_fee", self.taker_fee.to_string())?;
294        dict.set_item("ts_event", self.ts_event.as_u64())?;
295        dict.set_item("ts_init", self.ts_init.as_u64())?;
296        dict.set_item("info", PyDict::new(py))?;
297        match &self.outcome {
298            Some(value) => dict.set_item("outcome", value.to_string())?,
299            None => dict.set_item("outcome", py.None())?,
300        }
301        match &self.description {
302            Some(value) => dict.set_item("description", value.to_string())?,
303            None => dict.set_item("description", py.None())?,
304        }
305        match self.max_quantity {
306            Some(value) => dict.set_item("max_quantity", value.to_string())?,
307            None => dict.set_item("max_quantity", py.None())?,
308        }
309        match self.min_quantity {
310            Some(value) => dict.set_item("min_quantity", value.to_string())?,
311            None => dict.set_item("min_quantity", py.None())?,
312        }
313        match self.max_notional {
314            Some(value) => dict.set_item("max_notional", value.to_string())?,
315            None => dict.set_item("max_notional", py.None())?,
316        }
317        match self.min_notional {
318            Some(value) => dict.set_item("min_notional", value.to_string())?,
319            None => dict.set_item("min_notional", py.None())?,
320        }
321        match self.max_price {
322            Some(value) => dict.set_item("max_price", value.to_string())?,
323            None => dict.set_item("max_price", py.None())?,
324        }
325        match self.min_price {
326            Some(value) => dict.set_item("min_price", value.to_string())?,
327            None => dict.set_item("min_price", py.None())?,
328        }
329        Ok(dict.into())
330    }
331}
332
333////////////////////////////////////////////////////////////////////////////////
334// Tests
335////////////////////////////////////////////////////////////////////////////////
336#[cfg(test)]
337mod tests {
338    use pyo3::{prelude::*, prepare_freethreaded_python, types::PyDict};
339    use rstest::rstest;
340
341    use crate::instruments::{BinaryOption, stubs::*};
342
343    #[rstest]
344    fn test_dict_round_trip(binary_option: BinaryOption) {
345        prepare_freethreaded_python();
346        Python::with_gil(|py| {
347            let values = binary_option.py_to_dict(py).unwrap();
348            let values: Py<PyDict> = values.extract(py).unwrap();
349            let new_binary_option = BinaryOption::py_from_dict(py, values).unwrap();
350            assert_eq!(binary_option, new_binary_option);
351        })
352    }
353}