nautilus_common/python/xrate.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 ahash::{AHashMap, HashMap};
17use nautilus_core::python::to_pyvalue_err;
18use nautilus_model::enums::PriceType;
19use pyo3::prelude::*;
20use rust_decimal::{Decimal, prelude::FromPrimitive};
21use ustr::Ustr;
22
23use crate::xrate::get_exchange_rate;
24
25/// Calculates the exchange rate between two currencies using provided bid and ask quotes.
26///
27/// This function builds a graph of direct conversion rates from the quotes and searches for a
28/// conversion path whose accumulated rate is representable as a positive `Decimal`.
29/// If a path calculation is unrepresentable, the search may examine every simple path. In the
30/// worst case, this takes exponential time in dense graphs, even when a valid route exists.
31///
32/// Identical `from_currency` and `to_currency` return a rate of one without inspecting the quotes.
33/// Returns `Ok(None)` when no path is found and all quote and path calculations are representable.
34///
35/// # Errors
36///
37/// Returns an error if:
38/// - `quotes_bid` or `quotes_ask` is empty.
39/// - `quotes_bid` and `quotes_ask` lengths are not equal.
40/// - `price_type` is equal to `Last` or `Mark` (cannot calculate from quotes).
41/// - The bid or ask side of a pair is missing.
42/// - No rate is found, and a calculation for any supplied pair or searched path overflows or
43/// underflows to zero.
44#[pyfunction]
45#[pyo3_stub_gen::derive::gen_stub_pyfunction(module = "nautilus_trader.common")]
46#[pyo3(name = "get_exchange_rate")]
47#[pyo3(signature = (from_currency, to_currency, price_type, quotes_bid, quotes_ask))]
48pub fn py_get_exchange_rate(
49 from_currency: &str,
50 to_currency: &str,
51 price_type: PriceType,
52 quotes_bid: HashMap<String, f64>,
53 quotes_ask: HashMap<String, f64>,
54) -> PyResult<Option<Decimal>> {
55 let quotes_bid = f64_quotes_to_decimal(quotes_bid).map_err(to_pyvalue_err)?;
56 let quotes_ask = f64_quotes_to_decimal(quotes_ask).map_err(to_pyvalue_err)?;
57
58 get_exchange_rate(
59 Ustr::from(from_currency),
60 Ustr::from(to_currency),
61 price_type,
62 quotes_bid,
63 quotes_ask,
64 )
65 .map_err(to_pyvalue_err)
66}
67
68fn f64_quotes_to_decimal(quotes: HashMap<String, f64>) -> anyhow::Result<AHashMap<Ustr, Decimal>> {
69 quotes
70 .into_iter()
71 .map(|(pair, value)| {
72 let rate = Decimal::from_f64(value).ok_or_else(|| {
73 anyhow::anyhow!("Invalid quote rate for pair {pair}, was {value}")
74 })?;
75 Ok((Ustr::from(&pair), rate))
76 })
77 .collect()
78}