Skip to main content

df_hyperliquid_core/markets/
book.rs

1//! `l2Book`: a market's visible book, the same shape from `/info` and from the socket, and the
2//! precision it is asked at. Prices and sizes are exact [`Dec`] values read from the venue's strings.
3
4use serde::Deserialize;
5
6use crate::client::{ApiError, Transport, info, info_request};
7use crate::utils::Json;
8use crate::utils::dec::{Dec, Round};
9
10/// How finely a book's levels are bucketed: full precision, or 2 to 5
11/// significant figures, and at 5 figures a step of 1, 2 or 5 in the last.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub struct Precision {
14    figures: Option<u32>,
15    step: Option<u32>,
16}
17
18impl Precision {
19    /// Full precision: no `nSigFigs`, no `mantissa`.
20    pub const FULL: Precision = Precision { figures: None, step: None };
21
22    /// `nSigFigs`: 2, 3, 4 or 5.
23    #[must_use]
24    pub const fn figures(figures: u32) -> Option<Precision> {
25        match figures {
26            2..=5 => Some(Precision { figures: Some(figures), step: None }),
27            _ => None,
28        }
29    }
30
31    /// `mantissa`: 1, 2 or 5, and only at five figures.
32    #[must_use]
33    pub const fn step(self, step: u32) -> Option<Precision> {
34        match (self.figures, step) {
35            (Some(5), 1 | 2 | 5) => Some(Precision { figures: Some(5), step: Some(step) }),
36            _ => None,
37        }
38    }
39}
40
41/// `{"type":"l2Book","coin":..,"nSigFigs"?,"mantissa"?}`. A coin is `BTC`, `xyz:XYZ100` on a HIP-3
42/// dex, `@107` or `PURR/USDC` for a pair, `#14730` for an outcome side.
43#[must_use]
44pub fn l2_book_request(coin: &str, precision: Precision) -> String {
45    let number = |value: u32| Json::Number(value.to_string());
46    let figures = precision.figures.map(|figures| ("nSigFigs", number(figures)));
47    let step = precision.step.map(|step| ("mantissa", number(step)));
48    let fields: Vec<(&str, Json)> =
49        [Some(("coin", Json::String(coin.to_owned()))), figures, step].into_iter().flatten().collect();
50    info_request("l2Book", &fields)
51}
52
53/// The book of `coin` at `precision`.
54pub async fn l2_book(transport: &impl Transport, coin: &str, precision: Precision) -> Result<Book, ApiError> {
55    info(transport, l2_book_request(coin, precision)).await
56}
57
58/// One price level: `n` orders resting at `px` for `sz` in all.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
60#[non_exhaustive]
61pub struct Level {
62    /// The price.
63    pub px: Dec,
64    /// The size resting at the price, in the base asset.
65    pub sz: Dec,
66    /// Number of orders at this price, not an amount.
67    pub n: u32,
68}
69
70/// `l2Book`: at most twenty levels a side, best first. There is no sequence number; each read
71/// or frame replaces the last.
72#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
73#[serde(from = "Raw")]
74#[non_exhaustive]
75pub struct Book {
76    /// The coin, as asked for.
77    pub coin: String,
78    /// Milliseconds.
79    pub time: u64,
80    /// Highest first.
81    pub bids: Vec<Level>,
82    /// Lowest first.
83    pub asks: Vec<Level>,
84    /// Sent with a bucketed book (`nSigFigs`): the gap between the best levels.
85    pub spread: Option<Dec>,
86}
87
88/// `levels` on the wire: bids, then asks.
89#[derive(Deserialize)]
90struct Raw {
91    coin: String,
92    time: u64,
93    levels: (Vec<Level>, Vec<Level>),
94    #[serde(default)]
95    spread: Option<Dec>,
96}
97
98impl From<Raw> for Book {
99    fn from(raw: Raw) -> Self {
100        let (bids, asks) = raw.levels;
101        Book { coin: raw.coin, time: raw.time, bids, asks, spread: raw.spread }
102    }
103}
104
105impl Book {
106    /// The best bid and the best ask.
107    #[must_use]
108    pub fn touch(&self) -> (Option<Dec>, Option<Dec>) {
109        (self.bids.first().map(|level| level.px), self.asks.first().map(|level| level.px))
110    }
111
112    /// Exactly halfway between the best bid and ask, one place finer than either. `None` when a
113    /// side is empty.
114    #[must_use]
115    pub fn mid(&self) -> Option<Dec> {
116        let (Some(bid), Some(ask)) = self.touch() else { return None };
117        halfway(bid, ask)
118    }
119}
120
121/// Exactly halfway between two prices, one place finer than either.
122fn halfway(bid: Dec, ask: Dec) -> Option<Dec> {
123    let places = bid.places().max(ask.places()).saturating_add(1);
124    bid.checked_add(ask)?.checked_div(Dec::from_int(2), places, Round::Down)
125}
126
127#[cfg(test)]
128#[path = "tests/book.rs"]
129mod tests;