Skip to main content

nautilus_common/
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
16//! Exchange rate calculations between currencies.
17//!
18//! An exchange rate is the value of one asset versus that of another.
19
20use ahash::{AHashMap, AHashSet};
21use nautilus_model::enums::PriceType;
22use rust_decimal::Decimal;
23use ustr::Ustr;
24
25type RateGraph = AHashMap<Ustr, Vec<(Ustr, Decimal)>>;
26
27/// Calculates the exchange rate between two currencies using provided bid and ask quotes.
28///
29/// This function builds a graph of direct conversion rates from the quotes and searches for a
30/// conversion path whose accumulated rate is representable as a positive `Decimal`.
31/// If a path calculation is unrepresentable, the search may examine every simple path. In the
32/// worst case, this takes exponential time in dense graphs, even when a valid route exists.
33///
34/// Identical `from_currency` and `to_currency` return a rate of one without inspecting the quotes.
35/// Returns `Ok(None)` when no path is found and all quote and path calculations are representable.
36///
37/// # Errors
38///
39/// Returns an error if:
40/// - `quotes_bid` or `quotes_ask` is empty.
41/// - `quotes_bid` and `quotes_ask` lengths are not equal.
42/// - `price_type` is equal to `Last` or `Mark` (cannot calculate from quotes).
43/// - The bid or ask side of a pair is missing.
44/// - No rate is found, and a calculation for any supplied pair or searched path overflows or
45///   underflows to zero.
46pub fn get_exchange_rate(
47    from_currency: Ustr,
48    to_currency: Ustr,
49    price_type: PriceType,
50    quotes_bid: AHashMap<Ustr, Decimal>,
51    quotes_ask: AHashMap<Ustr, Decimal>,
52) -> anyhow::Result<Option<Decimal>> {
53    if from_currency == to_currency {
54        // When the source and target currencies are identical,
55        // no conversion is needed; return an exchange rate of one.
56        return Ok(Some(Decimal::ONE));
57    }
58
59    if quotes_bid.is_empty() || quotes_ask.is_empty() {
60        anyhow::bail!("Quote maps must not be empty");
61    }
62
63    if quotes_bid.len() != quotes_ask.len() {
64        anyhow::bail!("Quote maps must have equal lengths");
65    }
66
67    // Validated here, in the same position as the price-type match this replaced, so the
68    // identical-currency shortcut and the quote-map errors keep their original precedence.
69    if !matches!(price_type, PriceType::Bid | PriceType::Ask | PriceType::Mid) {
70        anyhow::bail!("Invalid `price_type`, was '{price_type}'");
71    }
72
73    let (graph, unrepresentable) = build_rate_graph(quotes_bid, quotes_ask, price_type)?;
74    find_representable_rate(&graph, from_currency, to_currency, unrepresentable)
75}
76
77pub(crate) fn get_exchange_rate_with_alternates(
78    from_currency: Ustr,
79    to_currency: Ustr,
80    price_type: PriceType,
81    quotes_bid: &AHashMap<Ustr, Decimal>,
82    quotes_ask: &AHashMap<Ustr, Decimal>,
83    alternates: &[(Ustr, Decimal, Decimal)],
84) -> anyhow::Result<Option<Decimal>> {
85    let preferred = get_exchange_rate(
86        from_currency,
87        to_currency,
88        price_type,
89        quotes_bid.clone(),
90        quotes_ask.clone(),
91    );
92
93    if matches!(preferred, Ok(Some(_))) || alternates.is_empty() {
94        return preferred;
95    }
96
97    if !matches!(price_type, PriceType::Bid | PriceType::Ask | PriceType::Mid) {
98        return preferred;
99    }
100
101    let (mut graph, mut unrepresentable) =
102        build_rate_graph(quotes_bid.clone(), quotes_ask.clone(), price_type)?;
103    for &(pair, bid, ask) in alternates {
104        add_pair_rates(&mut graph, pair, bid, ask, price_type, &mut unrepresentable);
105    }
106
107    if !is_connected(&graph, from_currency, to_currency) {
108        return preferred;
109    }
110
111    sort_rate_graph(&mut graph);
112    let available = find_representable_rate(&graph, from_currency, to_currency, unrepresentable);
113    if !matches!(available, Ok(Some(_))) {
114        return available;
115    }
116
117    if let Some(rate) = find_rate_with_quote_choices(
118        from_currency,
119        to_currency,
120        price_type,
121        quotes_bid,
122        quotes_ask,
123        alternates,
124    ) {
125        return Ok(Some(rate));
126    }
127
128    available
129}
130
131fn build_rate_graph(
132    quotes_bid: AHashMap<Ustr, Decimal>,
133    mut quotes_ask: AHashMap<Ustr, Decimal>,
134    price_type: PriceType,
135) -> anyhow::Result<(RateGraph, bool)> {
136    // Construct a graph: each currency maps to its neighbors and corresponding conversion rate
137    let mut graph = RateGraph::new();
138    let mut unrepresentable = false;
139
140    for (pair, bid) in quotes_bid {
141        let ask = quotes_ask
142            .remove(&pair)
143            .ok_or_else(|| anyhow::anyhow!("Missing ask quote for pair {pair}"))?;
144        add_pair_rates(&mut graph, pair, bid, ask, price_type, &mut unrepresentable);
145    }
146
147    sort_rate_graph(&mut graph);
148
149    Ok((graph, unrepresentable))
150}
151
152fn find_rate_with_quote_choices(
153    from_currency: Ustr,
154    to_currency: Ustr,
155    price_type: PriceType,
156    quotes_bid: &AHashMap<Ustr, Decimal>,
157    quotes_ask: &AHashMap<Ustr, Decimal>,
158    alternates: &[(Ustr, Decimal, Decimal)],
159) -> Option<Decimal> {
160    for count in 1..=alternates.len() {
161        let mut indices: Vec<usize> = (0..count).collect();
162
163        loop {
164            let mut bid = quotes_bid.clone();
165            let mut ask = quotes_ask.clone();
166
167            for &index in &indices {
168                let (pair, alternate_bid, alternate_ask) = alternates[index];
169                bid.insert(pair, alternate_bid);
170                ask.insert(pair, alternate_ask);
171            }
172
173            if let Ok(Some(rate)) =
174                get_exchange_rate(from_currency, to_currency, price_type, bid, ask)
175            {
176                return Some(rate);
177            }
178
179            let mut position = count;
180            while position > 0 && indices[position - 1] == alternates.len() - count + position - 1 {
181                position -= 1;
182            }
183
184            if position == 0 {
185                break;
186            }
187
188            indices[position - 1] += 1;
189            for index in position..count {
190                indices[index] = indices[index - 1] + 1;
191            }
192        }
193    }
194
195    None
196}
197
198fn add_pair_rates(
199    graph: &mut RateGraph,
200    pair: Ustr,
201    bid: Decimal,
202    ask: Decimal,
203    price_type: PriceType,
204    unrepresentable: &mut bool,
205) {
206    let mut parts = pair.split('/');
207
208    let (Some(base), Some(quote), None) = (parts.next(), parts.next(), parts.next()) else {
209        log::warn!("Skipping invalid pair string: {pair}");
210        return;
211    };
212
213    if bid <= Decimal::ZERO || ask <= Decimal::ZERO {
214        // Both sides are required to build valid forward and reverse edges.
215        log::warn!("Skipping pair with non-positive bid or ask rate: {pair}");
216        return;
217    }
218
219    let base = Ustr::from(base);
220    let quote = Ustr::from(quote);
221    let (forward_rate, reverse_rate) = directional_rates(bid, ask, price_type);
222
223    if let Some(rate) = forward_rate {
224        graph.entry(base).or_default().push((quote, rate));
225    } else {
226        *unrepresentable = true;
227    }
228
229    if let Some(rate) = reverse_rate {
230        graph.entry(quote).or_default().push((base, rate));
231    } else {
232        *unrepresentable = true;
233    }
234}
235
236fn sort_rate_graph(graph: &mut RateGraph) {
237    // The LIFO fast search visits smaller neighbors first and favors higher parallel rates.
238    for neighbors in graph.values_mut() {
239        neighbors.sort_unstable_by(|left, right| right.cmp(left));
240    }
241}
242
243fn find_representable_rate(
244    graph: &RateGraph,
245    from_currency: Ustr,
246    to_currency: Ustr,
247    unrepresentable: bool,
248) -> anyhow::Result<Option<Decimal>> {
249    let (rate, path_unrepresentable) =
250        find_rate_without_backtracking(graph, from_currency, to_currency);
251
252    if rate.is_some() {
253        return Ok(rate);
254    }
255
256    if path_unrepresentable
257        && is_connected(graph, from_currency, to_currency)
258        && let Some(rate) = find_rate_with_backtracking(graph, from_currency, to_currency)
259    {
260        return Ok(Some(rate));
261    }
262
263    if unrepresentable || path_unrepresentable {
264        anyhow::bail!("No representable exchange rate from {from_currency} to {to_currency}");
265    }
266
267    Ok(None)
268}
269
270fn find_rate_without_backtracking(
271    graph: &RateGraph,
272    from_currency: Ustr,
273    to_currency: Ustr,
274) -> (Option<Decimal>, bool) {
275    let mut stack = vec![(from_currency, Decimal::ONE)];
276    let mut visited: AHashSet<Ustr> = AHashSet::new();
277    visited.insert(from_currency);
278    let mut path_unrepresentable = false;
279
280    while let Some((current, current_rate)) = stack.pop() {
281        if current == to_currency {
282            return (Some(current_rate), path_unrepresentable);
283        }
284
285        let neighbors = graph.get(&current).map_or(&[][..], Vec::as_slice);
286        for (neighbor, rate) in neighbors {
287            if visited.contains(neighbor) {
288                continue;
289            }
290
291            if let Some(next_rate) = current_rate
292                .checked_mul(*rate)
293                .filter(|rate| !rate.is_zero())
294            {
295                visited.insert(*neighbor);
296                stack.push((*neighbor, next_rate));
297            } else {
298                path_unrepresentable = true;
299            }
300        }
301    }
302
303    (None, path_unrepresentable)
304}
305
306fn is_connected(graph: &RateGraph, from_currency: Ustr, to_currency: Ustr) -> bool {
307    let mut stack = vec![from_currency];
308    let mut visited = AHashSet::from_iter([from_currency]);
309
310    while let Some(current) = stack.pop() {
311        if current == to_currency {
312            return true;
313        }
314
315        if let Some(neighbors) = graph.get(&current) {
316            for (neighbor, _) in neighbors {
317                if visited.insert(*neighbor) {
318                    stack.push(*neighbor);
319                }
320            }
321        }
322    }
323
324    false
325}
326
327fn find_rate_with_backtracking(
328    graph: &RateGraph,
329    from_currency: Ustr,
330    to_currency: Ustr,
331) -> Option<Decimal> {
332    let mut stack = vec![(from_currency, Decimal::ONE, 0)];
333    let mut visited: AHashSet<Ustr> = AHashSet::new();
334    visited.insert(from_currency);
335
336    while let Some((current, current_rate, next_index)) = stack.last_mut() {
337        if *current == to_currency {
338            return Some(*current_rate);
339        }
340
341        let neighbors = graph.get(current).map_or(&[][..], Vec::as_slice);
342        if *next_index == neighbors.len() {
343            visited.remove(current);
344            stack.pop();
345            continue;
346        }
347
348        let (neighbor, rate) = neighbors[neighbors.len() - 1 - *next_index];
349        *next_index += 1;
350
351        if visited.contains(&neighbor) {
352            continue;
353        }
354
355        if let Some(next_rate) = current_rate
356            .checked_mul(rate)
357            .filter(|rate| !rate.is_zero())
358        {
359            visited.insert(neighbor);
360            stack.push((neighbor, next_rate, 0));
361        }
362    }
363
364    None
365}
366
367fn directional_rates(
368    bid: Decimal,
369    ask: Decimal,
370    price_type: PriceType,
371) -> (Option<Decimal>, Option<Decimal>) {
372    let (forward_rate, reverse_divisor) = match price_type {
373        PriceType::Bid => (Some(bid), Some(ask)),
374        PriceType::Ask => (Some(ask), Some(bid)),
375        PriceType::Mid => {
376            let mid = bid
377                .checked_add(ask)
378                .and_then(|sum| sum.checked_div(Decimal::TWO))
379                .or_else(|| {
380                    let (low, high) = if bid < ask { (bid, ask) } else { (ask, bid) };
381                    high.checked_sub(low)
382                        .and_then(|difference| difference.checked_div(Decimal::TWO))
383                        .and_then(|half| low.checked_add(half))
384                });
385
386            (mid, mid)
387        }
388        _ => unreachable!("Price type was validated before graph construction"),
389    };
390
391    let reverse_rate = reverse_divisor
392        .and_then(|divisor| Decimal::ONE.checked_div(divisor))
393        .filter(|rate| !rate.is_zero());
394
395    (forward_rate.filter(|rate| !rate.is_zero()), reverse_rate)
396}
397
398#[cfg(test)]
399mod tests {
400    use ahash::{AHashMap, RandomState};
401    use rstest::rstest;
402    use rust_decimal::Decimal;
403    use rust_decimal_macros::dec;
404    use ustr::Ustr;
405
406    use super::*;
407
408    fn setup_test_quotes() -> (AHashMap<Ustr, Decimal>, AHashMap<Ustr, Decimal>) {
409        let mut quotes_bid = AHashMap::new();
410        let mut quotes_ask = AHashMap::new();
411
412        // Direct pairs
413        quotes_bid.insert(Ustr::from("EUR/USD"), dec!(1.1000));
414        quotes_ask.insert(Ustr::from("EUR/USD"), dec!(1.1002));
415
416        quotes_bid.insert(Ustr::from("GBP/USD"), dec!(1.3000));
417        quotes_ask.insert(Ustr::from("GBP/USD"), dec!(1.3002));
418
419        quotes_bid.insert(Ustr::from("USD/JPY"), dec!(110.00));
420        quotes_ask.insert(Ustr::from("USD/JPY"), dec!(110.02));
421
422        quotes_bid.insert(Ustr::from("AUD/USD"), dec!(0.7500));
423        quotes_ask.insert(Ustr::from("AUD/USD"), dec!(0.7502));
424
425        (quotes_bid, quotes_ask)
426    }
427
428    #[rstest]
429    #[case("EURUSD")]
430    #[case("EUR/USD/JPY")]
431    #[case("EUR/USD/")]
432    #[case("EUR//USD")]
433    #[case("/EUR/USD")]
434    fn test_invalid_pair_string(#[case] pair: &str) {
435        let mut quotes_bid = AHashMap::new();
436        let mut quotes_ask = AHashMap::new();
437        quotes_bid.insert(Ustr::from(pair), dec!(2));
438        quotes_ask.insert(Ustr::from(pair), dec!(2));
439        // Valid pair string
440        quotes_bid.insert(Ustr::from("EUR/USD"), dec!(1.1000));
441        quotes_ask.insert(Ustr::from("EUR/USD"), dec!(1.1002));
442
443        let rate = get_exchange_rate(
444            Ustr::from("EUR"),
445            Ustr::from("USD"),
446            PriceType::Mid,
447            quotes_bid,
448            quotes_ask,
449        )
450        .unwrap();
451
452        assert_eq!(rate, Some(dec!(1.1001)));
453    }
454
455    #[rstest]
456    #[case("/USD", "", "USD")]
457    #[case("EUR/", "EUR", "")]
458    fn test_pair_with_empty_currency_field(
459        #[case] pair: &str,
460        #[case] from_currency: &str,
461        #[case] to_currency: &str,
462    ) {
463        let quotes_bid = AHashMap::from([(Ustr::from(pair), dec!(2))]);
464        let quotes_ask = AHashMap::from([(Ustr::from(pair), dec!(4))]);
465
466        let rate = get_exchange_rate(
467            Ustr::from(from_currency),
468            Ustr::from(to_currency),
469            PriceType::Mid,
470            quotes_bid,
471            quotes_ask,
472        )
473        .unwrap();
474
475        assert_eq!(rate, Some(dec!(3)));
476    }
477
478    #[rstest]
479    fn test_same_currency() {
480        let (quotes_bid, quotes_ask) = setup_test_quotes();
481        let rate = get_exchange_rate(
482            Ustr::from("USD"),
483            Ustr::from("USD"),
484            PriceType::Mid,
485            quotes_bid,
486            quotes_ask,
487        )
488        .unwrap();
489        assert_eq!(rate, Some(Decimal::ONE));
490    }
491
492    #[rstest(
493        price_type,
494        expected,
495        case(PriceType::Bid, dec!(1.1000)),
496        case(PriceType::Ask, dec!(1.1002)),
497        case(PriceType::Mid, dec!(1.1001))
498    )]
499    fn test_direct_pair(price_type: PriceType, expected: Decimal) {
500        let (quotes_bid, quotes_ask) = setup_test_quotes();
501
502        let rate = get_exchange_rate(
503            Ustr::from("EUR"),
504            Ustr::from("USD"),
505            price_type,
506            quotes_bid,
507            quotes_ask,
508        )
509        .unwrap();
510
511        let rate = rate.unwrap_or_else(|| panic!("Expected a conversion rate for {price_type}"));
512        assert_eq!(rate, expected);
513    }
514
515    #[rstest]
516    fn test_inverse_pair() {
517        let (quotes_bid, quotes_ask) = setup_test_quotes();
518
519        let rate_eur_usd = get_exchange_rate(
520            Ustr::from("EUR"),
521            Ustr::from("USD"),
522            PriceType::Mid,
523            quotes_bid.clone(),
524            quotes_ask.clone(),
525        )
526        .unwrap();
527        let rate_usd_eur = get_exchange_rate(
528            Ustr::from("USD"),
529            Ustr::from("EUR"),
530            PriceType::Mid,
531            quotes_bid,
532            quotes_ask,
533        )
534        .unwrap();
535
536        if let (Some(eur_usd), Some(usd_eur)) = (rate_eur_usd, rate_usd_eur) {
537            // Inverse-edge rounding makes the round-trip near one, not exactly one
538            assert!((eur_usd * usd_eur - Decimal::ONE).abs() < dec!(0.0001));
539        } else {
540            panic!("Expected valid conversion rates for inverse conversion");
541        }
542    }
543
544    #[rstest(
545        price_type,
546        expected,
547        case(PriceType::Bid, Decimal::ONE / dec!(1.1002)),
548        case(PriceType::Ask, Decimal::ONE / dec!(1.1000)),
549        case(PriceType::Mid, Decimal::ONE / dec!(1.1001))
550    )]
551    fn test_inverse_pair_uses_opposite_spread_side(price_type: PriceType, expected: Decimal) {
552        let (quotes_bid, quotes_ask) = setup_test_quotes();
553
554        let rate = get_exchange_rate(
555            Ustr::from("USD"),
556            Ustr::from("EUR"),
557            price_type,
558            quotes_bid,
559            quotes_ask,
560        )
561        .unwrap();
562
563        assert_eq!(rate, Some(expected));
564    }
565
566    #[rstest]
567    fn test_indirect_route_is_deterministic_across_hash_seeds(
568        #[values(false, true)] reverse: bool,
569    ) {
570        let mut pairs = [
571            ("AAA/BBB", dec!(2)),
572            ("BBB/DDD", dec!(3)),
573            ("AAA/CCC", dec!(5)),
574            ("CCC/DDD", dec!(7)),
575        ];
576
577        if reverse {
578            pairs.reverse();
579        }
580
581        let seeds = [(0, 0, 0, 0), (1, 2, 3, 4), (5, 6, 7, 8), (10, 20, 30, 40)];
582
583        let rates = seeds.map(|(k0, k1, k2, k3)| {
584            let random_state = RandomState::with_seeds(k0, k1, k2, k3);
585            let mut quotes_bid = AHashMap::with_hasher(random_state.clone());
586            let mut quotes_ask = AHashMap::with_hasher(random_state);
587
588            for (pair, rate) in pairs {
589                quotes_bid.insert(Ustr::from(pair), rate);
590                quotes_ask.insert(Ustr::from(pair), rate);
591            }
592
593            get_exchange_rate(
594                Ustr::from("AAA"),
595                Ustr::from("DDD"),
596                PriceType::Bid,
597                quotes_bid,
598                quotes_ask,
599            )
600            .unwrap()
601        });
602
603        assert_eq!(rates, [Some(dec!(6)); 4]);
604    }
605
606    #[rstest]
607    fn test_cross_pair_through_usd() {
608        let (quotes_bid, quotes_ask) = setup_test_quotes();
609        let rate = get_exchange_rate(
610            Ustr::from("EUR"),
611            Ustr::from("JPY"),
612            PriceType::Mid,
613            quotes_bid,
614            quotes_ask,
615        )
616        .unwrap();
617        // Expected rate: (EUR/USD mid) * (USD/JPY mid)
618        let expected = dec!(1.1001) * dec!(110.01);
619
620        assert_eq!(rate, Some(expected));
621    }
622
623    #[rstest]
624    fn test_midpoint_sum_overflow_uses_representable_rate() {
625        let quotes_bid = AHashMap::from([(Ustr::from("EUR/USD"), Decimal::MAX)]);
626        let quotes_ask = quotes_bid.clone();
627
628        let result = get_exchange_rate(
629            Ustr::from("EUR"),
630            Ustr::from("USD"),
631            PriceType::Mid,
632            quotes_bid,
633            quotes_ask,
634        );
635
636        assert_eq!(result.unwrap(), Some(Decimal::MAX));
637    }
638
639    #[rstest]
640    #[case(PriceType::Bid)]
641    #[case(PriceType::Ask)]
642    #[case(PriceType::Mid)]
643    fn test_path_overflow_returns_error(#[case] price_type: PriceType) {
644        let quotes_bid = AHashMap::from([
645            (Ustr::from("EUR/USD"), dec!(100000000000000000000)),
646            (Ustr::from("USD/JPY"), dec!(100000000000000000000)),
647        ]);
648        let quotes_ask = quotes_bid.clone();
649
650        let result = get_exchange_rate(
651            Ustr::from("EUR"),
652            Ustr::from("JPY"),
653            price_type,
654            quotes_bid,
655            quotes_ask,
656        );
657
658        assert_eq!(
659            result.unwrap_err().to_string(),
660            "No representable exchange rate from EUR to JPY"
661        );
662    }
663
664    #[rstest]
665    fn test_alternate_quotes_unrepresentable_route_returns_error() {
666        let quotes_bid = AHashMap::from([
667            (Ustr::from("EUR/USD"), dec!(100000000000000000000)),
668            (Ustr::from("USD/JPY"), dec!(100000000000000000000)),
669            (Ustr::from("BTC/USDT"), Decimal::ONE),
670        ]);
671        let quotes_ask = quotes_bid.clone();
672        let alternates = vec![(Ustr::from("BTC/USDT"), Decimal::ONE, Decimal::ONE); 30];
673
674        let result = get_exchange_rate_with_alternates(
675            Ustr::from("EUR"),
676            Ustr::from("JPY"),
677            PriceType::Bid,
678            &quotes_bid,
679            &quotes_ask,
680            &alternates,
681        );
682
683        assert_eq!(
684            result.unwrap_err().to_string(),
685            "No representable exchange rate from EUR to JPY"
686        );
687    }
688
689    #[rstest]
690    #[case(PriceType::Bid)]
691    #[case(PriceType::Ask)]
692    #[case(PriceType::Mid)]
693    fn test_path_overflow_uses_alternate_route(#[case] price_type: PriceType) {
694        let quotes_bid = AHashMap::from([
695            (Ustr::from("AAA/BBB"), dec!(1000000000)),
696            (Ustr::from("BBB/CCC"), dec!(1000000000)),
697            (Ustr::from("CCC/DDD"), dec!(1000000000)),
698            (Ustr::from("DDD/TTT"), dec!(1000000000)),
699            (Ustr::from("AAA/EEE"), dec!(2)),
700            (Ustr::from("EEE/TTT"), dec!(3)),
701        ]);
702        let quotes_ask = quotes_bid.clone();
703
704        let result = get_exchange_rate(
705            Ustr::from("AAA"),
706            Ustr::from("TTT"),
707            price_type,
708            quotes_bid,
709            quotes_ask,
710        );
711
712        assert_eq!(result.unwrap(), Some(dec!(6)));
713    }
714
715    #[rstest]
716    fn test_path_overflow_revisits_currency_at_representable_rate() {
717        let quotes_bid = AHashMap::from([
718            (Ustr::from("AAA/BBB"), dec!(100000000000000000000)),
719            (Ustr::from("AAA/CCC"), Decimal::ONE),
720            (Ustr::from("CCC/BBB"), dec!(0.00000000000000000001)),
721            (Ustr::from("BBB/TTT"), dec!(100000000000000000000)),
722        ]);
723        let quotes_ask = quotes_bid.clone();
724
725        let result = get_exchange_rate(
726            Ustr::from("AAA"),
727            Ustr::from("TTT"),
728            PriceType::Bid,
729            quotes_bid,
730            quotes_ask,
731        );
732
733        assert_eq!(result.unwrap(), Some(Decimal::ONE));
734    }
735
736    #[rstest]
737    fn test_path_underflow_uses_alternate_route() {
738        let quotes_bid = AHashMap::from([
739            (Ustr::from("AAA/BBB"), dec!(0.00000000000000000001)),
740            (Ustr::from("BBB/TTT"), dec!(0.00000000000000000001)),
741            (Ustr::from("AAA/CCC"), dec!(2)),
742            (Ustr::from("CCC/TTT"), dec!(3)),
743        ]);
744        let quotes_ask = quotes_bid.clone();
745
746        let result = get_exchange_rate(
747            Ustr::from("AAA"),
748            Ustr::from("TTT"),
749            PriceType::Bid,
750            quotes_bid,
751            quotes_ask,
752        );
753
754        assert_eq!(result.unwrap(), Some(dec!(6)));
755    }
756
757    #[rstest]
758    fn test_inverse_underflow_uses_alternate_route() {
759        let quotes_bid = AHashMap::from([
760            (Ustr::from("AAA/BBB"), Decimal::MAX),
761            (Ustr::from("BBB/CCC"), Decimal::ONE),
762            (Ustr::from("CCC/AAA"), Decimal::ONE),
763        ]);
764        let quotes_ask = quotes_bid.clone();
765
766        let result = get_exchange_rate(
767            Ustr::from("BBB"),
768            Ustr::from("AAA"),
769            PriceType::Bid,
770            quotes_bid,
771            quotes_ask,
772        );
773
774        assert_eq!(result.unwrap(), Some(Decimal::ONE));
775    }
776
777    #[rstest]
778    fn test_unrelated_inverse_underflow_does_not_mask_valid_route() {
779        let quotes_bid = AHashMap::from([
780            (Ustr::from("AAA/TTT"), dec!(6)),
781            (Ustr::from("XXX/YYY"), Decimal::MAX),
782        ]);
783        let quotes_ask = quotes_bid.clone();
784
785        let result = get_exchange_rate(
786            Ustr::from("AAA"),
787            Ustr::from("TTT"),
788            PriceType::Bid,
789            quotes_bid,
790            quotes_ask,
791        );
792
793        assert_eq!(result.unwrap(), Some(dec!(6)));
794    }
795
796    #[rstest]
797    #[case(PriceType::Bid)]
798    #[case(PriceType::Ask)]
799    fn test_direct_decimal_max_rate(#[case] price_type: PriceType) {
800        let quotes_bid = AHashMap::from([(Ustr::from("EUR/USD"), Decimal::MAX)]);
801        let quotes_ask = quotes_bid.clone();
802
803        let rate = get_exchange_rate(
804            Ustr::from("EUR"),
805            Ustr::from("USD"),
806            price_type,
807            quotes_bid,
808            quotes_ask,
809        )
810        .unwrap();
811
812        assert_eq!(rate, Some(Decimal::MAX));
813    }
814
815    #[rstest]
816    #[case(dec!(0))]
817    #[case(dec!(-1.1))]
818    fn test_non_positive_rate_is_skipped(#[case] rate: Decimal) {
819        let mut quotes_bid = AHashMap::new();
820        let mut quotes_ask = AHashMap::new();
821        quotes_bid.insert(Ustr::from("EUR/USD"), rate);
822        quotes_ask.insert(Ustr::from("EUR/USD"), rate);
823
824        let result = get_exchange_rate(
825            Ustr::from("EUR"),
826            Ustr::from("USD"),
827            PriceType::Mid,
828            quotes_bid,
829            quotes_ask,
830        );
831
832        assert_eq!(result.unwrap(), None);
833    }
834
835    #[rstest(
836        bid,
837        ask,
838        price_type,
839        case(dec!(1.1), Decimal::ZERO, PriceType::Bid),
840        case(Decimal::ZERO, dec!(1.1), PriceType::Ask)
841    )]
842    fn test_non_positive_opposite_side_is_skipped(
843        bid: Decimal,
844        ask: Decimal,
845        price_type: PriceType,
846    ) {
847        let mut quotes_bid = AHashMap::new();
848        let mut quotes_ask = AHashMap::new();
849        quotes_bid.insert(Ustr::from("EUR/USD"), bid);
850        quotes_ask.insert(Ustr::from("EUR/USD"), ask);
851
852        let result = get_exchange_rate(
853            Ustr::from("EUR"),
854            Ustr::from("USD"),
855            price_type,
856            quotes_bid,
857            quotes_ask,
858        );
859
860        assert_eq!(result.unwrap(), None);
861    }
862
863    #[rstest]
864    fn test_no_conversion_path() {
865        let mut quotes_bid = AHashMap::new();
866        let mut quotes_ask = AHashMap::new();
867
868        // Only one pair provided
869        quotes_bid.insert(Ustr::from("EUR/USD"), dec!(1.1000));
870        quotes_ask.insert(Ustr::from("EUR/USD"), dec!(1.1002));
871
872        // Attempt conversion from EUR to JPY should yield None
873        let rate = get_exchange_rate(
874            Ustr::from("EUR"),
875            Ustr::from("JPY"),
876            PriceType::Mid,
877            quotes_bid,
878            quotes_ask,
879        )
880        .unwrap();
881        assert_eq!(rate, None);
882    }
883
884    #[rstest]
885    fn test_empty_quotes() {
886        let quotes_bid: AHashMap<Ustr, Decimal> = AHashMap::new();
887        let quotes_ask: AHashMap<Ustr, Decimal> = AHashMap::new();
888        let result = get_exchange_rate(
889            Ustr::from("EUR"),
890            Ustr::from("USD"),
891            PriceType::Mid,
892            quotes_bid,
893            quotes_ask,
894        );
895        assert_eq!(
896            result.unwrap_err().to_string(),
897            "Quote maps must not be empty"
898        );
899    }
900
901    #[rstest]
902    fn test_unequal_quotes_length() {
903        let mut quotes_bid = AHashMap::new();
904        let mut quotes_ask = AHashMap::new();
905
906        quotes_bid.insert(Ustr::from("EUR/USD"), dec!(1.1000));
907        quotes_bid.insert(Ustr::from("GBP/USD"), dec!(1.3000));
908        quotes_ask.insert(Ustr::from("EUR/USD"), dec!(1.1002));
909        // Missing GBP/USD in ask quotes.
910
911        let result = get_exchange_rate(
912            Ustr::from("EUR"),
913            Ustr::from("USD"),
914            PriceType::Mid,
915            quotes_bid,
916            quotes_ask,
917        );
918        assert_eq!(
919            result.unwrap_err().to_string(),
920            "Quote maps must have equal lengths"
921        );
922    }
923
924    #[rstest]
925    fn test_equal_length_quotes_with_different_keys() {
926        let mut quotes_bid = AHashMap::new();
927        let mut quotes_ask = AHashMap::new();
928        quotes_bid.insert(Ustr::from("EUR/USD"), dec!(1.1000));
929        quotes_ask.insert(Ustr::from("GBP/USD"), dec!(1.3002));
930
931        let result = get_exchange_rate(
932            Ustr::from("EUR"),
933            Ustr::from("USD"),
934            PriceType::Bid,
935            quotes_bid,
936            quotes_ask,
937        );
938
939        assert_eq!(
940            result.unwrap_err().to_string(),
941            "Missing ask quote for pair EUR/USD"
942        );
943    }
944
945    #[rstest]
946    fn test_invalid_price_type() {
947        let (quotes_bid, quotes_ask) = setup_test_quotes();
948        // Using an invalid price type variant (assume PriceType::Last is unsupported)
949        let result = get_exchange_rate(
950            Ustr::from("EUR"),
951            Ustr::from("USD"),
952            PriceType::Last,
953            quotes_bid,
954            quotes_ask,
955        );
956        assert_eq!(
957            result.unwrap_err().to_string(),
958            "Invalid `price_type`, was 'LAST'"
959        );
960    }
961
962    #[rstest]
963    fn test_same_currency_shortcut_precedes_all_validation() {
964        // The identical-currency shortcut runs before any quote or price-type validation, so an
965        // unsupported price type and empty quote maps still yield a rate of one.
966        let result = get_exchange_rate(
967            Ustr::from("USD"),
968            Ustr::from("USD"),
969            PriceType::Last,
970            AHashMap::new(),
971            AHashMap::new(),
972        );
973
974        assert_eq!(result.unwrap(), Some(Decimal::ONE));
975    }
976
977    #[rstest]
978    fn test_quote_map_errors_precede_invalid_price_type() {
979        // Empty maps are reported before an unsupported price type for distinct currencies.
980        let empty = get_exchange_rate(
981            Ustr::from("EUR"),
982            Ustr::from("USD"),
983            PriceType::Last,
984            AHashMap::new(),
985            AHashMap::new(),
986        );
987
988        assert_eq!(
989            empty.unwrap_err().to_string(),
990            "Quote maps must not be empty"
991        );
992
993        let mut quotes_bid = AHashMap::new();
994        let mut quotes_ask = AHashMap::new();
995        quotes_bid.insert(Ustr::from("EUR/USD"), dec!(1.1000));
996        quotes_bid.insert(Ustr::from("GBP/USD"), dec!(1.3000));
997        quotes_ask.insert(Ustr::from("EUR/USD"), dec!(1.1002));
998
999        let unequal = get_exchange_rate(
1000            Ustr::from("EUR"),
1001            Ustr::from("USD"),
1002            PriceType::Last,
1003            quotes_bid,
1004            quotes_ask,
1005        );
1006
1007        assert_eq!(
1008            unequal.unwrap_err().to_string(),
1009            "Quote maps must have equal lengths"
1010        );
1011    }
1012
1013    #[rstest]
1014    fn test_cycle_handling() {
1015        let mut quotes_bid = AHashMap::new();
1016        let mut quotes_ask = AHashMap::new();
1017        // Create a cycle by including both EUR/USD and USD/EUR quotes
1018        quotes_bid.insert(Ustr::from("EUR/USD"), dec!(1.1));
1019        quotes_ask.insert(Ustr::from("EUR/USD"), dec!(1.1002));
1020        quotes_bid.insert(Ustr::from("USD/EUR"), dec!(0.909));
1021        quotes_ask.insert(Ustr::from("USD/EUR"), dec!(0.9091));
1022
1023        let rate = get_exchange_rate(
1024            Ustr::from("EUR"),
1025            Ustr::from("USD"),
1026            PriceType::Mid,
1027            quotes_bid,
1028            quotes_ask,
1029        )
1030        .unwrap();
1031
1032        // The total adjacency ordering encounters the higher parallel rate first.
1033        let expected = dec!(1.1001);
1034        assert_eq!(rate, Some(expected));
1035    }
1036
1037    #[rstest]
1038    fn test_multiple_paths() {
1039        let mut quotes_bid = AHashMap::new();
1040        let mut quotes_ask = AHashMap::new();
1041        // Direct conversion
1042        quotes_bid.insert(Ustr::from("EUR/USD"), dec!(1.1000));
1043        quotes_ask.insert(Ustr::from("EUR/USD"), dec!(1.1002));
1044        // Indirect path via GBP: EUR/GBP and GBP/USD
1045        quotes_bid.insert(Ustr::from("EUR/GBP"), dec!(0.8461));
1046        quotes_ask.insert(Ustr::from("EUR/GBP"), dec!(0.8463));
1047        quotes_bid.insert(Ustr::from("GBP/USD"), dec!(1.3000));
1048        quotes_ask.insert(Ustr::from("GBP/USD"), dec!(1.3002));
1049
1050        let rate = get_exchange_rate(
1051            Ustr::from("EUR"),
1052            Ustr::from("USD"),
1053            PriceType::Mid,
1054            quotes_bid,
1055            quotes_ask,
1056        )
1057        .unwrap();
1058
1059        assert_eq!(rate, Some(dec!(1.1001)));
1060    }
1061}