Skip to main content

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