Skip to main content

rustrade_execution/client/hyperliquid/
precision.rs

1//! Hyperliquid's precision rules for order sizes and prices, and the check an order passes before
2//! it is sent.
3//!
4//! From Hyperliquid's [tick and lot size rules]:
5//! - A **size** has at most the asset's `szDecimals` decimal places.
6//! - A **price** has at most 5 significant figures, and at most `MAX_DECIMALS - szDecimals`
7//!   decimal places, where `MAX_DECIMALS` is 6 for perpetuals and 8 for spot. An integer price is
8//!   always valid, whatever its number of significant figures.
9//!
10//! A spot pair's `szDecimals` is its base token's.
11//!
12//! [tick and lot size rules]: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size
13
14use crate::{
15    error::{OrderField, PrecisionLimit, PrecisionViolation},
16    order::OrderKind,
17};
18use hyperliquid_rust_sdk::{ClientLimit, ClientOrder, ClientTrigger};
19use rust_decimal::{Decimal, RoundingStrategy, prelude::ToPrimitive};
20use std::str::FromStr;
21
22/// The most decimal places a perpetual's price may have, before its `szDecimals` are taken off.
23const PERP_MAX_DECIMALS: u32 = 6;
24
25/// The most decimal places a spot pair's price may have, before its `szDecimals` are taken off.
26const SPOT_MAX_DECIMALS: u32 = 8;
27
28/// The decimal places Hyperliquid's SDK writes a number to before trimming trailing zeros. It
29/// takes every size and price as an `f64`, so a value is sent exactly only if formatting that
30/// `f64` to this many places gives the value back.
31const SDK_WIRE_DECIMALS: usize = 8;
32
33/// Hyperliquid's precision rules for one market's orders. See the [module docs](self).
34///
35/// Read it from [`HyperliquidClient::order_precision`](super::HyperliquidClient::order_precision)
36/// or [`HyperliquidSpotClient::order_precision`](super::spot::HyperliquidSpotClient::order_precision),
37/// or build it from metadata with [`perp`](Self::perp) or [`spot`](Self::spot).
38///
39/// The clients refuse an order whose quantity, price or trigger price breaks these rules with
40/// [`OrderError::InvalidPrecision`](crate::error::OrderError::InvalidPrecision), and never round
41/// it themselves. Round with [`round_quantity`](Self::round_quantity) and
42/// [`round_price`](Self::round_price) first, in the direction your strategy needs.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub struct OrderPrecision {
45    sz_decimals: u32,
46    max_decimals: u32,
47}
48
49impl OrderPrecision {
50    /// The most significant figures a price that is not an integer may have.
51    pub const MAX_SIGNIFICANT_FIGURES: u32 = 5;
52
53    /// The rules for a perpetual whose `szDecimals` is `sz_decimals`.
54    pub const fn perp(sz_decimals: u32) -> Self {
55        Self {
56            sz_decimals,
57            max_decimals: PERP_MAX_DECIMALS,
58        }
59    }
60
61    /// The rules for a spot pair whose base token's `szDecimals` is `base_sz_decimals`.
62    pub const fn spot(base_sz_decimals: u32) -> Self {
63        Self {
64            sz_decimals: base_sz_decimals,
65            max_decimals: SPOT_MAX_DECIMALS,
66        }
67    }
68
69    /// The most decimal places a quantity may have: the asset's `szDecimals`.
70    pub const fn quantity_decimals(&self) -> u32 {
71        self.sz_decimals
72    }
73
74    /// The most decimal places a price may have: `MAX_DECIMALS - szDecimals`, and never fewer
75    /// than zero.
76    pub const fn price_decimals(&self) -> u32 {
77        self.max_decimals.saturating_sub(self.sz_decimals)
78    }
79
80    /// Check that `quantity` is positive, meets the rules, and can be sent exactly.
81    ///
82    /// # Errors
83    ///
84    /// The rule `quantity` breaks, as a [`PrecisionViolation`] naming
85    /// [`OrderField::Quantity`].
86    pub fn check_quantity(&self, quantity: Decimal) -> Result<(), PrecisionViolation> {
87        self.wire_quantity(quantity).map(drop)
88    }
89
90    /// Check that the limit price `price` is positive, meets the rules, and can be sent exactly.
91    ///
92    /// # Errors
93    ///
94    /// The rule `price` breaks, as a [`PrecisionViolation`] naming [`OrderField::Price`].
95    pub fn check_price(&self, price: Decimal) -> Result<(), PrecisionViolation> {
96        self.wire_price(OrderField::Price, price).map(drop)
97    }
98
99    /// Check a stop or take-profit order's `trigger_price` as [`check_price`](Self::check_price)
100    /// checks a limit price: it follows the same rules.
101    ///
102    /// # Errors
103    ///
104    /// The rule `trigger_price` breaks, as a [`PrecisionViolation`] naming
105    /// [`OrderField::TriggerPrice`].
106    pub fn check_trigger_price(&self, trigger_price: Decimal) -> Result<(), PrecisionViolation> {
107        self.wire_price(OrderField::TriggerPrice, trigger_price)
108            .map(drop)
109    }
110
111    /// `quantity` rounded to the decimal places the rules allow, by `strategy`.
112    ///
113    /// A quantity smaller than the smallest step can round to zero, which
114    /// [`check_quantity`](Self::check_quantity) refuses.
115    pub fn round_quantity(&self, quantity: Decimal, strategy: RoundingStrategy) -> Decimal {
116        quantity
117            .round_dp_with_strategy(self.quantity_decimals(), strategy)
118            .normalize()
119    }
120
121    /// `price` rounded by `strategy` to the decimal places and significant figures the rules
122    /// allow. An integer price is returned unchanged.
123    ///
124    /// A price smaller than the smallest step the decimal places allow can round to zero, which
125    /// [`check_price`](Self::check_price) refuses.
126    pub fn round_price(&self, price: Decimal, strategy: RoundingStrategy) -> Decimal {
127        let price = price.normalize();
128        if price.scale() == 0 {
129            return price;
130        }
131        // The decimal places that keep `MAX_SIGNIFICANT_FIGURES`: a value with `digits` digits
132        // and `scale` decimal places has `digits - scale` digits before the point.
133        let significant = (price.scale() + Self::MAX_SIGNIFICANT_FIGURES)
134            .saturating_sub(significant_digits(price));
135        price
136            .round_dp_with_strategy(significant.min(self.price_decimals()), strategy)
137            .normalize()
138    }
139
140    /// `quantity` as the `f64` the SDK takes, once checked.
141    fn wire_quantity(&self, quantity: Decimal) -> Result<f64, PrecisionViolation> {
142        let violation = |limit| PrecisionViolation::new(OrderField::Quantity, quantity, limit);
143        if quantity <= Decimal::ZERO {
144            return Err(violation(PrecisionLimit::NotPositive));
145        }
146        if quantity.normalize().scale() > self.quantity_decimals() {
147            return Err(violation(PrecisionLimit::DecimalPlaces {
148                max: self.quantity_decimals(),
149            }));
150        }
151        to_wire(quantity).ok_or_else(|| violation(PrecisionLimit::NotRepresentable))
152    }
153
154    /// `price`, the request's `field`, as the `f64` the SDK takes, once checked.
155    fn wire_price(&self, field: OrderField, price: Decimal) -> Result<f64, PrecisionViolation> {
156        let violation = |limit| PrecisionViolation::new(field, price, limit);
157        if price <= Decimal::ZERO {
158            return Err(violation(PrecisionLimit::NotPositive));
159        }
160        let normalized = price.normalize();
161        if normalized.scale() > 0 {
162            if normalized.scale() > self.price_decimals() {
163                return Err(violation(PrecisionLimit::DecimalPlaces {
164                    max: self.price_decimals(),
165                }));
166            }
167            if significant_digits(normalized) > Self::MAX_SIGNIFICANT_FIGURES {
168                return Err(violation(PrecisionLimit::SignificantFigures {
169                    max: Self::MAX_SIGNIFICANT_FIGURES,
170                }));
171            }
172        }
173        to_wire(price).ok_or_else(|| violation(PrecisionLimit::NotRepresentable))
174    }
175}
176
177/// The digits of `value`'s mantissa: its significant figures once normalized, for a value that
178/// is not an integer.
179fn significant_digits(value: Decimal) -> u32 {
180    value
181        .mantissa()
182        .unsigned_abs()
183        .checked_ilog10()
184        .map_or(1, |log| log + 1)
185}
186
187/// `value` as an `f64`, if the SDK would send it unchanged.
188fn to_wire(value: Decimal) -> Option<f64> {
189    let float = value.to_f64()?;
190    let sent = Decimal::from_str(&format!("{float:.SDK_WIRE_DECIMALS$}")).ok()?;
191    (sent == value).then_some(float)
192}
193
194/// An order's values in the form the SDK places it in.
195#[derive(Debug)]
196pub(super) struct WireOrder {
197    pub(super) limit_px: f64,
198    pub(super) sz: f64,
199    pub(super) order_type: ClientOrder,
200}
201
202/// Why an order cannot be put in the form the SDK places it in.
203#[derive(Debug, PartialEq)]
204pub(super) enum WireOrderError {
205    /// A limit order, or a limit order a trigger places, with no limit price.
206    MissingPrice,
207    /// A kind Hyperliquid does not support. The clients refuse these before building the order.
208    UnsupportedKind,
209    /// A value breaks the market's precision rules.
210    Precision(PrecisionViolation),
211}
212
213impl From<PrecisionViolation> for WireOrderError {
214    fn from(violation: PrecisionViolation) -> Self {
215        Self::Precision(violation)
216    }
217}
218
219/// Check an order's values against `precision`, and put them in the form the SDK places them
220/// in, unchanged.
221///
222/// A trigger order that places a market order (`Stop`, `TakeProfit`) sends its trigger price as
223/// its limit price, as the SDK requires.
224pub(super) fn wire_order(
225    precision: &OrderPrecision,
226    kind: OrderKind,
227    tif: String,
228    price: Option<Decimal>,
229    quantity: Decimal,
230) -> Result<WireOrder, WireOrderError> {
231    let sz = precision.wire_quantity(quantity)?;
232    let limit_price = || -> Result<f64, WireOrderError> {
233        let price = price.ok_or(WireOrderError::MissingPrice)?;
234        Ok(precision.wire_price(OrderField::Price, price)?)
235    };
236    let trigger = |trigger_price, is_market, tpsl: &str| -> Result<_, WireOrderError> {
237        let trigger_px = precision.wire_price(OrderField::TriggerPrice, trigger_price)?;
238        let order_type = ClientOrder::Trigger(ClientTrigger {
239            is_market,
240            trigger_px,
241            tpsl: tpsl.to_owned(),
242        });
243        let limit_px = if is_market {
244            trigger_px
245        } else {
246            limit_price()?
247        };
248        Ok(WireOrder {
249            limit_px,
250            sz,
251            order_type,
252        })
253    };
254
255    match kind {
256        OrderKind::Limit => Ok(WireOrder {
257            limit_px: limit_price()?,
258            sz,
259            order_type: ClientOrder::Limit(ClientLimit { tif }),
260        }),
261        OrderKind::Stop { trigger_price } => trigger(trigger_price, true, "sl"),
262        OrderKind::StopLimit { trigger_price } => trigger(trigger_price, false, "sl"),
263        OrderKind::TakeProfit { trigger_price } => trigger(trigger_price, true, "tp"),
264        OrderKind::TakeProfitLimit { trigger_price } => trigger(trigger_price, false, "tp"),
265        OrderKind::Market
266        | OrderKind::TrailingStop { .. }
267        | OrderKind::TrailingStopLimit { .. } => Err(WireOrderError::UnsupportedKind),
268    }
269}
270
271#[cfg(test)]
272// Test code: panics on bad input are acceptable
273#[allow(clippy::unwrap_used)]
274mod tests {
275    use super::*;
276    use rust_decimal_macros::dec;
277
278    fn violation(field: OrderField, value: Decimal, limit: PrecisionLimit) -> PrecisionViolation {
279        PrecisionViolation {
280            field,
281            value,
282            limit,
283        }
284    }
285
286    #[test]
287    fn a_quantity_may_have_at_most_sz_decimals_places() {
288        let three = OrderPrecision::perp(3);
289        assert_eq!(three.check_quantity(dec!(1.001)), Ok(()));
290        assert_eq!(
291            three.check_quantity(dec!(1.00100)),
292            Ok(()),
293            "trailing zeros do not count"
294        );
295        assert_eq!(
296            three.check_quantity(dec!(1.0001)),
297            Err(violation(
298                OrderField::Quantity,
299                dec!(1.0001),
300                PrecisionLimit::DecimalPlaces { max: 3 }
301            ))
302        );
303
304        let zero = OrderPrecision::perp(0);
305        assert_eq!(
306            zero.check_quantity(dec!(123456)),
307            Ok(()),
308            "an integer quantity is not rounded to significant figures"
309        );
310        assert!(zero.check_quantity(dec!(1.5)).is_err());
311    }
312
313    #[test]
314    fn an_integer_price_is_valid_whatever_its_significant_figures() {
315        let perp = OrderPrecision::perp(5);
316        assert_eq!(perp.check_price(dec!(123456)), Ok(()));
317        assert_eq!(perp.check_price(dec!(123456.0)), Ok(()));
318        assert_eq!(
319            perp.check_price(dec!(12345.6)),
320            Err(violation(
321                OrderField::Price,
322                dec!(12345.6),
323                PrecisionLimit::SignificantFigures { max: 5 }
324            ))
325        );
326    }
327
328    /// The examples in Hyperliquid's tick and lot size documentation.
329    #[test]
330    fn a_price_follows_the_documented_examples() {
331        let perp = OrderPrecision::perp(0);
332        assert_eq!(perp.check_price(dec!(1234.5)), Ok(()));
333        assert_eq!(
334            perp.check_price(dec!(1234.56)),
335            Err(violation(
336                OrderField::Price,
337                dec!(1234.56),
338                PrecisionLimit::SignificantFigures { max: 5 }
339            ))
340        );
341        assert_eq!(perp.check_price(dec!(0.001234)), Ok(()));
342        assert_eq!(
343            perp.check_price(dec!(0.0012345)),
344            Err(violation(
345                OrderField::Price,
346                dec!(0.0012345),
347                PrecisionLimit::DecimalPlaces { max: 6 }
348            ))
349        );
350
351        let perp_one = OrderPrecision::perp(1);
352        assert_eq!(perp_one.check_price(dec!(0.01234)), Ok(()));
353        assert_eq!(
354            perp_one.check_price(dec!(0.012345)),
355            Err(violation(
356                OrderField::Price,
357                dec!(0.012345),
358                PrecisionLimit::DecimalPlaces { max: 5 }
359            ))
360        );
361
362        // 0.0001234 is valid on spot with szDecimals 0 or 1, and not above 2.
363        assert_eq!(OrderPrecision::spot(0).check_price(dec!(0.0001234)), Ok(()));
364        assert_eq!(OrderPrecision::spot(1).check_price(dec!(0.0001234)), Ok(()));
365        assert!(
366            OrderPrecision::spot(3)
367                .check_price(dec!(0.0001234))
368                .is_err()
369        );
370    }
371
372    #[test]
373    fn a_value_that_is_not_positive_is_refused() {
374        let perp = OrderPrecision::perp(2);
375        for value in [dec!(0), dec!(0.00), dec!(-1), dec!(-0.5)] {
376            assert_eq!(
377                perp.check_quantity(value),
378                Err(violation(
379                    OrderField::Quantity,
380                    value,
381                    PrecisionLimit::NotPositive
382                ))
383            );
384            assert_eq!(
385                perp.check_price(value),
386                Err(violation(
387                    OrderField::Price,
388                    value,
389                    PrecisionLimit::NotPositive
390                ))
391            );
392            assert_eq!(
393                perp.check_trigger_price(value),
394                Err(violation(
395                    OrderField::TriggerPrice,
396                    value,
397                    PrecisionLimit::NotPositive
398                ))
399            );
400        }
401    }
402
403    #[test]
404    fn a_value_rounded_to_zero_is_refused() {
405        let quantity =
406            OrderPrecision::perp(2).round_quantity(dec!(0.004), RoundingStrategy::ToZero);
407        assert_eq!(quantity, Decimal::ZERO);
408        assert!(OrderPrecision::perp(2).check_quantity(quantity).is_err());
409
410        // A perpetual with szDecimals 6 allows no decimal places in a price.
411        let precision = OrderPrecision::perp(6);
412        let price = precision.round_price(dec!(0.4), RoundingStrategy::ToZero);
413        assert_eq!(price, Decimal::ZERO);
414        assert_eq!(
415            precision.check_price(price),
416            Err(violation(
417                OrderField::Price,
418                price,
419                PrecisionLimit::NotPositive
420            ))
421        );
422    }
423
424    #[test]
425    fn a_trigger_price_follows_the_price_rules_under_its_own_name() {
426        let perp = OrderPrecision::perp(0);
427        assert_eq!(perp.check_trigger_price(dec!(1234.5)), Ok(()));
428        assert_eq!(
429            perp.check_trigger_price(dec!(1234.56)),
430            Err(violation(
431                OrderField::TriggerPrice,
432                dec!(1234.56),
433                PrecisionLimit::SignificantFigures { max: 5 }
434            ))
435        );
436    }
437
438    #[test]
439    fn the_price_cap_never_goes_below_zero_decimal_places() {
440        let precision = OrderPrecision::perp(8);
441        assert_eq!(precision.price_decimals(), 0);
442        assert_eq!(precision.check_price(dec!(42)), Ok(()));
443        assert!(precision.check_price(dec!(42.5)).is_err());
444    }
445
446    #[test]
447    fn rounding_meets_the_rules_in_the_direction_asked() {
448        let perp = OrderPrecision::perp(2);
449        assert_eq!(
450            perp.round_quantity(dec!(1.239), RoundingStrategy::ToZero),
451            dec!(1.23)
452        );
453        assert_eq!(
454            perp.round_quantity(dec!(1.231), RoundingStrategy::AwayFromZero),
455            dec!(1.24)
456        );
457
458        // Significant figures bind: 5 of them leave 1 decimal place.
459        assert_eq!(
460            perp.round_price(dec!(1234.56), RoundingStrategy::ToZero),
461            dec!(1234.5)
462        );
463        // Decimal places bind: perp with szDecimals 2 allows 4.
464        assert_eq!(
465            perp.round_price(dec!(0.0012345), RoundingStrategy::MidpointNearestEven),
466            dec!(0.0012)
467        );
468        assert_eq!(
469            perp.round_price(dec!(123456.7), RoundingStrategy::ToZero),
470            dec!(123456)
471        );
472        assert_eq!(
473            perp.round_price(dec!(123456), RoundingStrategy::ToZero),
474            dec!(123456),
475            "an integer price is returned unchanged"
476        );
477        assert_eq!(
478            perp.round_price(dec!(9.99999), RoundingStrategy::AwayFromZero),
479            dec!(10)
480        );
481
482        for value in [
483            dec!(1234.56),
484            dec!(0.0012345),
485            dec!(9.99999),
486            dec!(0.123456789),
487        ] {
488            for strategy in [RoundingStrategy::ToZero, RoundingStrategy::AwayFromZero] {
489                let rounded = perp.round_price(value, strategy);
490                assert_eq!(perp.check_price(rounded), Ok(()), "{value} -> {rounded}");
491            }
492        }
493    }
494
495    #[test]
496    fn a_value_the_sdk_would_change_is_not_representable() {
497        // Valid by the rules (an integer), but past what an f64 holds exactly.
498        let huge = dec!(12345678901234567890123);
499        assert_eq!(
500            OrderPrecision::perp(0).check_price(huge),
501            Err(violation(
502                OrderField::Price,
503                huge,
504                PrecisionLimit::NotRepresentable
505            ))
506        );
507        // Within the decimal places allowed, but with more digits than an f64 holds.
508        let long = dec!(12345678901234.12345678);
509        assert_eq!(
510            OrderPrecision::spot(8).check_quantity(long),
511            Err(violation(
512                OrderField::Quantity,
513                long,
514                PrecisionLimit::NotRepresentable
515            ))
516        );
517        assert_eq!(to_wire(dec!(0.00000001)), Some(0.00000001));
518        assert_eq!(to_wire(dec!(123456.12345678)), Some(123456.12345678));
519    }
520
521    #[test]
522    fn a_wire_order_carries_the_values_unchanged() {
523        let precision = OrderPrecision::perp(2);
524        let order = wire_order(
525            &precision,
526            OrderKind::StopLimit {
527                trigger_price: dec!(95),
528            },
529            "Gtc".to_owned(),
530            Some(dec!(94.5)),
531            dec!(1.25),
532        )
533        .unwrap();
534        assert_eq!((order.limit_px, order.sz), (94.5, 1.25));
535        let ClientOrder::Trigger(trigger) = order.order_type else {
536            panic!("expected a trigger order, got {:?}", order.order_type);
537        };
538        assert_eq!(
539            (trigger.trigger_px, trigger.is_market, trigger.tpsl.as_str()),
540            (95.0, false, "sl")
541        );
542
543        let market_trigger = wire_order(
544            &precision,
545            OrderKind::TakeProfit {
546                trigger_price: dec!(120),
547            },
548            "Gtc".to_owned(),
549            None,
550            dec!(1),
551        )
552        .unwrap();
553        assert_eq!(
554            market_trigger.limit_px, 120.0,
555            "a market trigger's limit price is its trigger price"
556        );
557    }
558
559    #[test]
560    fn a_wire_order_refuses_each_value_that_breaks_the_rules() {
561        let precision = OrderPrecision::perp(2);
562        let refused = |kind, price, quantity| {
563            wire_order(&precision, kind, "Gtc".to_owned(), price, quantity).unwrap_err()
564        };
565
566        assert_eq!(
567            refused(OrderKind::Limit, Some(dec!(100)), dec!(1.234)),
568            WireOrderError::Precision(violation(
569                OrderField::Quantity,
570                dec!(1.234),
571                PrecisionLimit::DecimalPlaces { max: 2 }
572            ))
573        );
574        assert_eq!(
575            refused(OrderKind::Limit, Some(dec!(100.123456)), dec!(1)),
576            WireOrderError::Precision(violation(
577                OrderField::Price,
578                dec!(100.123456),
579                PrecisionLimit::DecimalPlaces { max: 4 }
580            ))
581        );
582        assert_eq!(
583            refused(
584                OrderKind::Stop {
585                    trigger_price: dec!(1234.56)
586                },
587                None,
588                dec!(1)
589            ),
590            WireOrderError::Precision(violation(
591                OrderField::TriggerPrice,
592                dec!(1234.56),
593                PrecisionLimit::SignificantFigures { max: 5 }
594            ))
595        );
596        assert_eq!(
597            refused(OrderKind::Limit, None, dec!(1)),
598            WireOrderError::MissingPrice
599        );
600        assert_eq!(
601            refused(OrderKind::Market, None, dec!(1)),
602            WireOrderError::UnsupportedKind
603        );
604    }
605}