architect_api/utils/
price.rs

1//! Utility functions for working with prices.
2
3use crate::Dir;
4use rust_decimal::Decimal;
5
6/// Return true if the first price is more aggressive than the
7/// second for the specified direction.
8///
9/// e.g. is_more_agg_then(dec!(3), dec!(2), Dir::Sell) -> false
10/// e.g. is_more_agg_then(dec!(3), dec!(2), Dir::Buy) -> true
11pub fn is_more_agg_than(price: Decimal, than: Decimal, dir: Dir) -> bool {
12    match dir {
13        Dir::Buy => price > than,
14        Dir::Sell => price < than,
15    }
16}
17
18pub fn is_equal_or_more_agg_than(price: Decimal, than: Decimal, dir: Dir) -> bool {
19    match dir {
20        Dir::Buy => price >= than,
21        Dir::Sell => price <= than,
22    }
23}
24
25pub fn is_less_agg_than(price: Decimal, than: Decimal, dir: Dir) -> bool {
26    match dir {
27        Dir::Buy => price < than,
28        Dir::Sell => price > than,
29    }
30}
31
32pub fn is_equal_or_less_agg_than(price: Decimal, than: Decimal, dir: Dir) -> bool {
33    match dir {
34        Dir::Buy => price <= than,
35        Dir::Sell => price >= than,
36    }
37}
38
39pub fn more_agg_by(price: Decimal, by: Decimal, dir: Dir) -> Decimal {
40    match dir {
41        Dir::Buy => price + by,
42        Dir::Sell => price - by,
43    }
44}
45
46pub fn less_agg_by(price: Decimal, by: Decimal, dir: Dir) -> Decimal {
47    match dir {
48        Dir::Buy => price - by,
49        Dir::Sell => price + by,
50    }
51}
52
53pub fn least_agg(p1: Decimal, p2: Decimal, dir: Dir) -> Decimal {
54    match dir {
55        Dir::Buy => p1.min(p2),
56        Dir::Sell => p1.max(p2),
57    }
58}
59
60pub fn most_agg(p1: Decimal, p2: Decimal, dir: Dir) -> Decimal {
61    match dir {
62        Dir::Buy => p1.max(p2),
63        Dir::Sell => p1.min(p2),
64    }
65}
66
67/// Round the decimal to the nearest multiple of increment in the
68/// direction of zero
69pub fn alias_to_step_size(x: Decimal, step_size: Option<Decimal>) -> Decimal {
70    if let Some(step_size) = step_size {
71        if x.is_sign_positive() || x.is_zero() {
72            (x / step_size).floor() * step_size
73        } else {
74            (x / step_size).ceil() * step_size
75        }
76    } else {
77        x
78    }
79}
80
81pub fn tick_size_round_less_agg(x: Decimal, dir: Dir, tick_size: Decimal) -> Decimal {
82    match dir {
83        Dir::Buy => (x / tick_size).floor() * tick_size,
84        Dir::Sell => (x / tick_size).ceil() * tick_size,
85    }
86}