Skip to main content

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::HashMap;
17use nautilus_core::python::to_pyvalue_err;
18use nautilus_model::enums::PriceType;
19use pyo3::prelude::*;
20use ustr::Ustr;
21
22use crate::xrate::get_exchange_rate;
23
24/// Calculates the exchange rate between two currencies using provided bid and ask quotes.
25///
26/// This function builds a graph of direct conversion rates from the quotes and uses a DFS to
27/// accumulate the conversion rate along a valid conversion path. While a full Floyd–Warshall
28/// algorithm could compute all-pairs conversion rates, the DFS approach here provides a quick
29/// solution for a single conversion query.
30#[pyfunction]
31#[pyo3_stub_gen::derive::gen_stub_pyfunction(module = "nautilus_trader.common")]
32#[pyo3(name = "get_exchange_rate")]
33#[pyo3(signature = (from_currency, to_currency, price_type, quotes_bid, quotes_ask))]
34pub fn py_get_exchange_rate(
35    from_currency: &str,
36    to_currency: &str,
37    price_type: PriceType,
38    quotes_bid: HashMap<String, f64>,
39    quotes_ask: HashMap<String, f64>,
40) -> PyResult<Option<f64>> {
41    get_exchange_rate(
42        Ustr::from(from_currency),
43        Ustr::from(to_currency),
44        price_type,
45        quotes_bid.into_iter().collect(),
46        quotes_ask.into_iter().collect(),
47    )
48    .map_err(to_pyvalue_err)
49}