df_hyperliquid_core/utils/
rounding.rs1use crate::markets::Side;
7use crate::trade::error::TradeError;
8use crate::utils::{Dec, Round};
9
10pub const SIGNIFICANT_FIGURES: u32 = 5;
12
13pub const PERP_PRICE_PLACES: u32 = 6;
15
16pub const SPOT_PRICE_PLACES: u32 = 8;
18
19pub const MINIMUM_ORDER_VALUE: Dec = Dec::from_int(10);
21
22pub const MAX_SLIPPAGE: Dec = Dec::lit::<1>(5);
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub struct Grid {
29 sz_decimals: u32,
30 ceiling: u32,
31}
32
33impl Grid {
34 #[must_use]
36 pub const fn perp(sz_decimals: u32) -> Grid {
37 Grid { sz_decimals, ceiling: PERP_PRICE_PLACES }
38 }
39
40 #[must_use]
42 pub const fn spot(sz_decimals: u32) -> Grid {
43 Grid { sz_decimals, ceiling: SPOT_PRICE_PLACES }
44 }
45
46 #[must_use]
48 pub const fn sz_decimals(self) -> u32 {
49 self.sz_decimals
50 }
51
52 #[must_use]
55 pub const fn price_places(self) -> u32 {
56 self.ceiling.saturating_sub(self.sz_decimals)
57 }
58
59 #[must_use]
65 pub fn tick(self, price: Dec, round: Round) -> Option<Dec> {
66 if !price.is_positive() {
67 return None;
68 }
69 let places = self.price_places().min(price.sig_places(SIGNIFICANT_FIGURES));
70 let kept = price.round(places, round);
71 kept.is_positive().then_some(kept)
72 }
73
74 #[must_use]
77 pub fn price(self, price: Dec, side: Side) -> Option<Dec> {
78 self.tick(price, side.price_rounding())
79 }
80
81 #[must_use]
83 pub fn is_on_grid(self, price: Dec) -> bool {
84 self.tick(price, Round::Down) == Some(price)
85 }
86
87 #[must_use]
90 pub fn size(self, size: Dec) -> Option<Dec> {
91 if !size.is_positive() {
92 return None;
93 }
94 let kept = size.round(self.sz_decimals, Round::Down);
95 kept.is_positive().then_some(kept)
96 }
97
98 pub fn market_bound(self, reference: Dec, slippage: Dec, side: Side) -> Result<Dec, TradeError> {
102 if slippage.is_negative() || slippage > MAX_SLIPPAGE {
103 return Err(TradeError::Slippage(slippage));
104 }
105 let factor = match side {
106 Side::Buy => Dec::ONE.checked_add(slippage),
107 Side::Sell => Dec::ONE.checked_sub(slippage),
108 };
109 factor
110 .and_then(|factor| reference.checked_mul(factor))
111 .and_then(|moved| self.price(moved, side))
112 .ok_or(TradeError::NoPrice(reference))
113 }
114
115 #[must_use]
118 pub fn least_size(self, price: Dec) -> Option<Dec> {
119 let exact = MINIMUM_ORDER_VALUE.checked_div(price, 12, Round::Up)?;
120 let size = exact.round(self.sz_decimals, Round::Up);
121 size.is_positive().then_some(size)
122 }
123
124 #[must_use]
126 pub fn meets_minimum(price: Dec, size: Dec) -> bool {
127 price.checked_mul(size).is_some_and(|worth| worth >= MINIMUM_ORDER_VALUE)
128 }
129}
130
131#[cfg(test)]
132#[path = "tests/rounding.rs"]
133mod tests;