nautilus_common/python/xrate.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::collections::HashMap;
17
18use ahash::AHashMap;
19use nautilus_core::python::to_pyvalue_err;
20use nautilus_model::enums::PriceType;
21use pyo3::prelude::*;
22use ustr::Ustr;
23
24use crate::xrate::get_exchange_rate;
25
26/// Calculates the exchange rate between two currencies using provided bid and ask quotes.
27///
28/// # Errors
29///
30/// Returns an error if:
31/// - `price_type` is equal to `Last` or `Mark` (cannot calculate from quotes).
32/// - `quotes_bid` or `quotes_ask` is empty.
33/// - `quotes_bid` and `quotes_ask` lengths are not equal.
34/// - The bid or ask side of a pair is missing.
35#[pyfunction]
36#[pyo3(name = "get_exchange_rate")]
37#[pyo3(signature = (from_currency, to_currency, price_type, quotes_bid, quotes_ask))]
38pub fn py_get_exchange_rate(
39 from_currency: &str,
40 to_currency: &str,
41 price_type: PriceType,
42 quotes_bid: HashMap<String, f64>,
43 quotes_ask: HashMap<String, f64>,
44) -> PyResult<Option<f64>> {
45 get_exchange_rate(
46 Ustr::from(from_currency),
47 Ustr::from(to_currency),
48 price_type,
49 AHashMap::from_iter(quotes_bid),
50 AHashMap::from_iter(quotes_ask),
51 )
52 .map_err(to_pyvalue_err)
53}