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)]
60pub struct Level {
61    /// The price.
62    pub px: Dec,
63    /// The size resting at the price, in the base asset.
64    pub sz: Dec,
65    /// Number of orders at this price, not an amount.
66    pub n: u32,
67}
68
69/// `l2Book`: at most twenty levels a side, best first. There is no sequence number; each read
70/// or frame replaces the last.
71#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
72#[serde(from = "Raw")]
73pub struct Book {
74    /// The coin, as asked for.
75    pub coin: String,
76    /// Milliseconds.
77    pub time: u64,
78    /// Highest first.
79    pub bids: Vec<Level>,
80    /// Lowest first.
81    pub asks: Vec<Level>,
82    /// Sent with a bucketed book (`nSigFigs`): the gap between the best levels.
83    pub spread: Option<Dec>,
84}
85
86/// `levels` on the wire: bids, then asks.
87#[derive(Deserialize)]
88struct Raw {
89    coin: String,
90    time: u64,
91    levels: (Vec<Level>, Vec<Level>),
92    #[serde(default)]
93    spread: Option<Dec>,
94}
95
96impl From<Raw> for Book {
97    fn from(raw: Raw) -> Self {
98        let (bids, asks) = raw.levels;
99        Book { coin: raw.coin, time: raw.time, bids, asks, spread: raw.spread }
100    }
101}
102
103impl Book {
104    /// The best bid and the best ask.
105    #[must_use]
106    pub fn touch(&self) -> (Option<Dec>, Option<Dec>) {
107        (self.bids.first().map(|level| level.px), self.asks.first().map(|level| level.px))
108    }
109
110    /// Exactly halfway between the best bid and ask, one place finer than either. `None` when a
111    /// side is empty.
112    #[must_use]
113    pub fn mid(&self) -> Option<Dec> {
114        let (Some(bid), Some(ask)) = self.touch() else { return None };
115        halfway(bid, ask)
116    }
117}
118
119/// Exactly halfway between two prices, one place finer than either.
120fn halfway(bid: Dec, ask: Dec) -> Option<Dec> {
121    let places = bid.places().max(ask.places()).saturating_add(1);
122    bid.checked_add(ask)?.checked_div(Dec::from_int(2), places, Round::Down)
123}
124
125#[cfg(test)]
126#[path = "tests/book.rs"]
127mod tests;