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 { .. }
268        | OrderKind::TrailingStopFixedLimit { .. } => Err(WireOrderError::UnsupportedKind),
269    }
270}
271
272#[cfg(test)]
273// Test code: panics on bad input are acceptable
274#[allow(clippy::unwrap_used)]
275mod tests {
276    use super::*;
277    use rust_decimal_macros::dec;
278
279    fn violation(field: OrderField, value: Decimal, limit: PrecisionLimit) -> PrecisionViolation {
280        PrecisionViolation {
281            field,
282            value,
283            limit,
284        }
285    }
286
287    #[test]
288    fn a_quantity_may_have_at_most_sz_decimals_places() {
289        let three = OrderPrecision::perp(3);
290        assert_eq!(three.check_quantity(dec!(1.001)), Ok(()));
291        assert_eq!(
292            three.check_quantity(dec!(1.00100)),
293            Ok(()),
294            "trailing zeros do not count"
295        );
296        assert_eq!(
297            three.check_quantity(dec!(1.0001)),
298            Err(violation(
299                OrderField::Quantity,
300                dec!(1.0001),
301                PrecisionLimit::DecimalPlaces { max: 3 }
302            ))
303        );
304
305        let zero = OrderPrecision::perp(0);
306        assert_eq!(
307            zero.check_quantity(dec!(123456)),
308            Ok(()),
309            "an integer quantity is not rounded to significant figures"
310        );
311        assert!(zero.check_quantity(dec!(1.5)).is_err());
312    }
313
314    #[test]
315    fn an_integer_price_is_valid_whatever_its_significant_figures() {
316        let perp = OrderPrecision::perp(5);
317        assert_eq!(perp.check_price(dec!(123456)), Ok(()));
318        assert_eq!(perp.check_price(dec!(123456.0)), Ok(()));
319        assert_eq!(
320            perp.check_price(dec!(12345.6)),
321            Err(violation(
322                OrderField::Price,
323                dec!(12345.6),
324                PrecisionLimit::SignificantFigures { max: 5 }
325            ))
326        );
327    }
328
329    /// The examples in Hyperliquid's tick and lot size documentation.
330    #[test]
331    fn a_price_follows_the_documented_examples() {
332        let perp = OrderPrecision::perp(0);
333        assert_eq!(perp.check_price(dec!(1234.5)), Ok(()));
334        assert_eq!(
335            perp.check_price(dec!(1234.56)),
336            Err(violation(
337                OrderField::Price,
338                dec!(1234.56),
339                PrecisionLimit::SignificantFigures { max: 5 }
340            ))
341        );
342        assert_eq!(perp.check_price(dec!(0.001234)), Ok(()));
343        assert_eq!(
344            perp.check_price(dec!(0.0012345)),
345            Err(violation(
346                OrderField::Price,
347                dec!(0.0012345),
348                PrecisionLimit::DecimalPlaces { max: 6 }
349            ))
350        );
351
352        let perp_one = OrderPrecision::perp(1);
353        assert_eq!(perp_one.check_price(dec!(0.01234)), Ok(()));
354        assert_eq!(
355            perp_one.check_price(dec!(0.012345)),
356            Err(violation(
357                OrderField::Price,
358                dec!(0.012345),
359                PrecisionLimit::DecimalPlaces { max: 5 }
360            ))
361        );
362
363        // 0.0001234 is valid on spot with szDecimals 0 or 1, and not above 2.
364        assert_eq!(OrderPrecision::spot(0).check_price(dec!(0.0001234)), Ok(()));
365        assert_eq!(OrderPrecision::spot(1).check_price(dec!(0.0001234)), Ok(()));
366        assert!(
367            OrderPrecision::spot(3)
368                .check_price(dec!(0.0001234))
369                .is_err()
370        );
371    }
372
373    #[test]
374    fn a_value_that_is_not_positive_is_refused() {
375        let perp = OrderPrecision::perp(2);
376        for value in [dec!(0), dec!(0.00), dec!(-1), dec!(-0.5)] {
377            assert_eq!(
378                perp.check_quantity(value),
379                Err(violation(
380                    OrderField::Quantity,
381                    value,
382                    PrecisionLimit::NotPositive
383                ))
384            );
385            assert_eq!(
386                perp.check_price(value),
387                Err(violation(
388                    OrderField::Price,
389                    value,
390                    PrecisionLimit::NotPositive
391                ))
392            );
393            assert_eq!(
394                perp.check_trigger_price(value),
395                Err(violation(
396                    OrderField::TriggerPrice,
397                    value,
398                    PrecisionLimit::NotPositive
399                ))
400            );
401        }
402    }
403
404    #[test]
405    fn a_value_rounded_to_zero_is_refused() {
406        let quantity =
407            OrderPrecision::perp(2).round_quantity(dec!(0.004), RoundingStrategy::ToZero);
408        assert_eq!(quantity, Decimal::ZERO);
409        assert!(OrderPrecision::perp(2).check_quantity(quantity).is_err());
410
411        // A perpetual with szDecimals 6 allows no decimal places in a price.
412        let precision = OrderPrecision::perp(6);
413        let price = precision.round_price(dec!(0.4), RoundingStrategy::ToZero);
414        assert_eq!(price, Decimal::ZERO);
415        assert_eq!(
416            precision.check_price(price),
417            Err(violation(
418                OrderField::Price,
419                price,
420                PrecisionLimit::NotPositive
421            ))
422        );
423    }
424
425    #[test]
426    fn a_trigger_price_follows_the_price_rules_under_its_own_name() {
427        let perp = OrderPrecision::perp(0);
428        assert_eq!(perp.check_trigger_price(dec!(1234.5)), Ok(()));
429        assert_eq!(
430            perp.check_trigger_price(dec!(1234.56)),
431            Err(violation(
432                OrderField::TriggerPrice,
433                dec!(1234.56),
434                PrecisionLimit::SignificantFigures { max: 5 }
435            ))
436        );
437    }
438
439    #[test]
440    fn the_price_cap_never_goes_below_zero_decimal_places() {
441        let precision = OrderPrecision::perp(8);
442        assert_eq!(precision.price_decimals(), 0);
443        assert_eq!(precision.check_price(dec!(42)), Ok(()));
444        assert!(precision.check_price(dec!(42.5)).is_err());
445    }
446
447    #[test]
448    fn rounding_meets_the_rules_in_the_direction_asked() {
449        let perp = OrderPrecision::perp(2);
450        assert_eq!(
451            perp.round_quantity(dec!(1.239), RoundingStrategy::ToZero),
452            dec!(1.23)
453        );
454        assert_eq!(
455            perp.round_quantity(dec!(1.231), RoundingStrategy::AwayFromZero),
456            dec!(1.24)
457        );
458
459        // Significant figures bind: 5 of them leave 1 decimal place.
460        assert_eq!(
461            perp.round_price(dec!(1234.56), RoundingStrategy::ToZero),
462            dec!(1234.5)
463        );
464        // Decimal places bind: perp with szDecimals 2 allows 4.
465        assert_eq!(
466            perp.round_price(dec!(0.0012345), RoundingStrategy::MidpointNearestEven),
467            dec!(0.0012)
468        );
469        assert_eq!(
470            perp.round_price(dec!(123456.7), RoundingStrategy::ToZero),
471            dec!(123456)
472        );
473        assert_eq!(
474            perp.round_price(dec!(123456), RoundingStrategy::ToZero),
475            dec!(123456),
476            "an integer price is returned unchanged"
477        );
478        assert_eq!(
479            perp.round_price(dec!(9.99999), RoundingStrategy::AwayFromZero),
480            dec!(10)
481        );
482
483        for value in [
484            dec!(1234.56),
485            dec!(0.0012345),
486            dec!(9.99999),
487            dec!(0.123456789),
488        ] {
489            for strategy in [RoundingStrategy::ToZero, RoundingStrategy::AwayFromZero] {
490                let rounded = perp.round_price(value, strategy);
491                assert_eq!(perp.check_price(rounded), Ok(()), "{value} -> {rounded}");
492            }
493        }
494    }
495
496    #[test]
497    fn a_value_the_sdk_would_change_is_not_representable() {
498        // Valid by the rules (an integer), but past what an f64 holds exactly.
499        let huge = dec!(12345678901234567890123);
500        assert_eq!(
501            OrderPrecision::perp(0).check_price(huge),
502            Err(violation(
503                OrderField::Price,
504                huge,
505                PrecisionLimit::NotRepresentable
506            ))
507        );
508        // Within the decimal places allowed, but with more digits than an f64 holds.
509        let long = dec!(12345678901234.12345678);
510        assert_eq!(
511            OrderPrecision::spot(8).check_quantity(long),
512            Err(violation(
513                OrderField::Quantity,
514                long,
515                PrecisionLimit::NotRepresentable
516            ))
517        );
518        assert_eq!(to_wire(dec!(0.00000001)), Some(0.00000001));
519        assert_eq!(to_wire(dec!(123456.12345678)), Some(123456.12345678));
520    }
521
522    #[test]
523    fn a_wire_order_carries_the_values_unchanged() {
524        let precision = OrderPrecision::perp(2);
525        let order = wire_order(
526            &precision,
527            OrderKind::StopLimit {
528                trigger_price: dec!(95),
529            },
530            "Gtc".to_owned(),
531            Some(dec!(94.5)),
532            dec!(1.25),
533        )
534        .unwrap();
535        assert_eq!((order.limit_px, order.sz), (94.5, 1.25));
536        let ClientOrder::Trigger(trigger) = order.order_type else {
537            panic!("expected a trigger order, got {:?}", order.order_type);
538        };
539        assert_eq!(
540            (trigger.trigger_px, trigger.is_market, trigger.tpsl.as_str()),
541            (95.0, false, "sl")
542        );
543
544        let market_trigger = wire_order(
545            &precision,
546            OrderKind::TakeProfit {
547                trigger_price: dec!(120),
548            },
549            "Gtc".to_owned(),
550            None,
551            dec!(1),
552        )
553        .unwrap();
554        assert_eq!(
555            market_trigger.limit_px, 120.0,
556            "a market trigger's limit price is its trigger price"
557        );
558    }
559
560    #[test]
561    fn a_wire_order_refuses_each_value_that_breaks_the_rules() {
562        let precision = OrderPrecision::perp(2);
563        let refused = |kind, price, quantity| {
564            wire_order(&precision, kind, "Gtc".to_owned(), price, quantity).unwrap_err()
565        };
566
567        assert_eq!(
568            refused(OrderKind::Limit, Some(dec!(100)), dec!(1.234)),
569            WireOrderError::Precision(violation(
570                OrderField::Quantity,
571                dec!(1.234),
572                PrecisionLimit::DecimalPlaces { max: 2 }
573            ))
574        );
575        assert_eq!(
576            refused(OrderKind::Limit, Some(dec!(100.123456)), dec!(1)),
577            WireOrderError::Precision(violation(
578                OrderField::Price,
579                dec!(100.123456),
580                PrecisionLimit::DecimalPlaces { max: 4 }
581            ))
582        );
583        assert_eq!(
584            refused(
585                OrderKind::Stop {
586                    trigger_price: dec!(1234.56)
587                },
588                None,
589                dec!(1)
590            ),
591            WireOrderError::Precision(violation(
592                OrderField::TriggerPrice,
593                dec!(1234.56),
594                PrecisionLimit::SignificantFigures { max: 5 }
595            ))
596        );
597        assert_eq!(
598            refused(OrderKind::Limit, None, dec!(1)),
599            WireOrderError::MissingPrice
600        );
601        assert_eq!(
602            refused(OrderKind::Market, None, dec!(1)),
603            WireOrderError::UnsupportedKind
604        );
605        assert_eq!(
606            refused(
607                OrderKind::TrailingStopFixedLimit {
608                    offset: dec!(1),
609                    offset_type: crate::order::TrailingOffsetType::Percentage,
610                    activation_price: None,
611                },
612                Some(dec!(100)),
613                dec!(1)
614            ),
615            WireOrderError::UnsupportedKind
616        );
617    }
618}