Skip to main content

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