Skip to main content

nautilus_model/python/instruments/
tokenized_asset.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    enums::AssetClass,
30    identifiers::{InstrumentId, Symbol},
31    instruments::TokenizedAsset,
32    types::{Currency, Money, Price, Quantity},
33};
34
35#[pymethods]
36#[pyo3_stub_gen::derive::gen_stub_pymethods]
37impl TokenizedAsset {
38    /// Represents a tokenized real-world asset traded as a pair on a crypto venue.
39    ///
40    /// Covers tokenized equities, ETFs, commodities, and other asset classes where the
41    /// underlying is represented as a base token traded against a quote currency.
42    /// The `asset_class` field identifies the underlying asset type.
43    #[expect(clippy::too_many_arguments)]
44    #[new]
45    #[pyo3(signature = (instrument_id, raw_symbol, asset_class, base_currency, quote_currency, price_precision, size_precision, price_increment, size_increment, ts_event, ts_init, isin=None, 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))]
46    fn py_new(
47        instrument_id: InstrumentId,
48        raw_symbol: Symbol,
49        asset_class: AssetClass,
50        base_currency: Currency,
51        quote_currency: Currency,
52        price_precision: u8,
53        size_precision: u8,
54        price_increment: Price,
55        size_increment: Quantity,
56        ts_event: u64,
57        ts_init: u64,
58        isin: Option<String>,
59        multiplier: Option<Quantity>,
60        lot_size: Option<Quantity>,
61        max_quantity: Option<Quantity>,
62        min_quantity: Option<Quantity>,
63        max_notional: Option<Money>,
64        min_notional: Option<Money>,
65        max_price: Option<Price>,
66        min_price: Option<Price>,
67        margin_init: Option<Decimal>,
68        margin_maint: Option<Decimal>,
69        tick_scheme: Option<String>,
70        info: Option<Py<PyDict>>,
71    ) -> PyResult<Self> {
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::builder()
79            .instrument_id(instrument_id)
80            .raw_symbol(raw_symbol)
81            .asset_class(asset_class)
82            .base_currency(base_currency)
83            .quote_currency(quote_currency)
84            .maybe_isin(isin.map(|s| ustr::Ustr::from(&s)))
85            .price_precision(price_precision)
86            .size_precision(size_precision)
87            .price_increment(price_increment)
88            .size_increment(size_increment)
89            .maybe_multiplier(multiplier)
90            .maybe_lot_size(lot_size)
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 __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
108        match op {
109            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
110            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
111            _ => py.NotImplemented(),
112        }
113    }
114
115    fn __hash__(&self) -> isize {
116        let mut hasher = DefaultHasher::new();
117        self.hash(&mut hasher);
118        hasher.finish() as isize
119    }
120
121    #[getter]
122    fn type_name(&self) -> &'static str {
123        stringify!(TokenizedAsset)
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 = "base_currency")]
146    fn py_base_currency(&self) -> Currency {
147        self.base_currency
148    }
149
150    #[getter]
151    #[pyo3(name = "quote_currency")]
152    fn py_quote_currency(&self) -> Currency {
153        self.quote_currency
154    }
155
156    #[getter]
157    #[pyo3(name = "isin")]
158    fn py_isin(&self) -> Option<String> {
159        self.isin.map(|u| u.to_string())
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 = "multiplier")]
188    fn py_multiplier(&self) -> Quantity {
189        self.multiplier
190    }
191
192    #[getter]
193    #[pyo3(name = "lot_size")]
194    fn py_lot_size(&self) -> Option<Quantity> {
195        self.lot_size
196    }
197
198    #[getter]
199    #[pyo3(name = "max_quantity")]
200    fn py_max_quantity(&self) -> Option<Quantity> {
201        self.max_quantity
202    }
203
204    #[getter]
205    #[pyo3(name = "min_quantity")]
206    fn py_min_quantity(&self) -> Option<Quantity> {
207        self.min_quantity
208    }
209
210    #[getter]
211    #[pyo3(name = "max_notional")]
212    fn py_max_notional(&self) -> Option<Money> {
213        self.max_notional
214    }
215
216    #[getter]
217    #[pyo3(name = "min_notional")]
218    fn py_min_notional(&self) -> Option<Money> {
219        self.min_notional
220    }
221
222    #[getter]
223    #[pyo3(name = "max_price")]
224    fn py_max_price(&self) -> Option<Price> {
225        self.max_price
226    }
227
228    #[getter]
229    #[pyo3(name = "min_price")]
230    fn py_min_price(&self) -> Option<Price> {
231        self.min_price
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 = "margin_init")]
242    fn py_margin_init(&self) -> Decimal {
243        self.margin_init
244    }
245
246    #[getter]
247    #[pyo3(name = "ts_event")]
248    fn py_ts_event(&self) -> u64 {
249        self.ts_event.as_u64()
250    }
251
252    #[getter]
253    #[pyo3(name = "ts_init")]
254    fn py_ts_init(&self) -> u64 {
255        self.ts_init.as_u64()
256    }
257
258    #[getter]
259    #[pyo3(name = "info")]
260    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
261        if let Some(ref info_map) = self.info {
262            let py_dict = PyDict::new(py);
263
264            for (key, value) in info_map {
265                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
266                let py_value =
267                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
268                py_dict.set_item(key, py_value)?;
269            }
270            Ok(py_dict.unbind())
271        } else {
272            Ok(PyDict::new(py).unbind())
273        }
274    }
275
276    #[staticmethod]
277    #[pyo3(name = "from_dict")]
278    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
279        crate::python::instruments::from_dict_instrument_pyo3(py, values)
280    }
281
282    #[pyo3(name = "to_dict")]
283    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
284        let dict = PyDict::new(py);
285        dict.set_item("type", stringify!(TokenizedAsset))?;
286        dict.set_item("id", self.id.to_string())?;
287        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
288        dict.set_item("asset_class", self.asset_class.to_string())?;
289        dict.set_item("base_currency", self.base_currency.code.to_string())?;
290        dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
291        match self.isin {
292            Some(value) => dict.set_item("isin", value.to_string())?,
293            None => dict.set_item("isin", py.None())?,
294        }
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("multiplier", self.multiplier.to_string())?;
300        dict.set_item("margin_init", self.margin_init.to_string())?;
301        dict.set_item("margin_maint", self.margin_maint.to_string())?;
302
303        if let Some(ref info_map) = self.info {
304            let info_dict = PyDict::new(py);
305
306            for (key, value) in info_map {
307                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
308                let py_value =
309                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
310                info_dict.set_item(key, py_value)?;
311            }
312            dict.set_item("info", info_dict)?;
313        } else {
314            dict.set_item("info", PyDict::new(py))?;
315        }
316        dict.set_item("ts_event", self.ts_event.as_u64())?;
317        dict.set_item("ts_init", self.ts_init.as_u64())?;
318        match self.lot_size {
319            Some(value) => dict.set_item("lot_size", value.to_string())?,
320            None => dict.set_item("lot_size", py.None())?,
321        }
322
323        match self.max_quantity {
324            Some(value) => dict.set_item("max_quantity", value.to_string())?,
325            None => dict.set_item("max_quantity", py.None())?,
326        }
327
328        match self.min_quantity {
329            Some(value) => dict.set_item("min_quantity", value.to_string())?,
330            None => dict.set_item("min_quantity", py.None())?,
331        }
332
333        match self.max_notional {
334            Some(value) => dict.set_item("max_notional", value.to_string())?,
335            None => dict.set_item("max_notional", py.None())?,
336        }
337
338        match self.min_notional {
339            Some(value) => dict.set_item("min_notional", value.to_string())?,
340            None => dict.set_item("min_notional", py.None())?,
341        }
342
343        match self.max_price {
344            Some(value) => dict.set_item("max_price", value.to_string())?,
345            None => dict.set_item("max_price", py.None())?,
346        }
347
348        match self.min_price {
349            Some(value) => dict.set_item("min_price", value.to_string())?,
350            None => dict.set_item("min_price", py.None())?,
351        }
352        dict.set_item(
353            "tick_scheme",
354            crate::python::instruments::tick_scheme_to_py(self),
355        )?;
356        Ok(dict.into())
357    }
358}