Skip to main content

df_hyperliquid_core/live/
market.rs

1//! The websocket's own market frames: the best bid and offer, one dex's mids, and the `l2` book's
2//! snapshot and diffs. Books, trades, candles and asset contexts come in the shapes the `/info`
3//! reads answer, the [`crate::markets`] types. Every price and size is an exact [`Dec`] read from the venue's string; a number written
4//! as a float is refused, never rounded.
5
6use std::cmp::Ordering;
7
8use crate::markets::{Book, Level};
9use crate::utils::Dec;
10use serde::Deserialize;
11
12/// `bbo`: the best bid and offer, sent only when one of them moves. A side with nothing
13/// resting is `None`.
14#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
15#[serde(from = "RawBbo")]
16#[non_exhaustive]
17pub struct Bbo {
18    /// The coin.
19    pub coin: String,
20    /// Milliseconds.
21    pub time: u64,
22    /// The best bid; `None` when no bid is resting.
23    pub bid: Option<Level>,
24    /// The best ask; `None` when no ask is resting.
25    pub ask: Option<Level>,
26}
27
28#[derive(Deserialize)]
29struct RawBbo {
30    coin: String,
31    time: u64,
32    bbo: (Option<Level>, Option<Level>),
33}
34
35impl From<RawBbo> for Bbo {
36    fn from(raw: RawBbo) -> Self {
37        let (bid, ask) = raw.bbo;
38        Bbo { coin: raw.coin, time: raw.time, bid, ask }
39    }
40}
41
42/// `allMids`: every coin's mid on one perp dex, in the order sent. The first dex's (`dex` empty)
43/// also carries spot pairs (`@107`, `PURR/USDC`) and outcome sides (`#14720`).
44#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
45#[non_exhaustive]
46pub struct Mids {
47    /// The dex, `""` for the first perp dex and when not sent.
48    #[serde(default)]
49    pub dex: String,
50    /// The map `allMids` answers.
51    pub mids: crate::markets::mids::Mids,
52}
53
54impl Mids {
55    /// A coin's mid, the coin spelled as the venue spells it.
56    #[must_use]
57    pub fn get(&self, coin: &str) -> Option<Dec> {
58        self.mids.get(coin)
59    }
60}
61
62/// One `l2` frame: the book's snapshot first, then each change as a diff. A diff comes either as
63/// it is (`u`) or as base64 of raw DEFLATE (RFC 1951) over its JSON (`c`), kept as sent: inflating
64/// it needs a decompressor this crate does not carry. The inflated text reads as an [`L2Diff`].
65#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
66#[non_exhaustive]
67pub enum L2 {
68    /// `s`: up to twenty levels a side, as `l2Book` sends them.
69    #[serde(rename = "s")]
70    Snapshot(Book),
71    /// `u`: a diff as it is.
72    #[serde(rename = "u")]
73    Diff(L2Diff),
74    /// `c`: a diff, base64 of raw DEFLATE over its JSON.
75    #[serde(rename = "c")]
76    Compressed(String),
77}
78
79/// One level an `l2` diff adds or changes: a price and the size now resting there. Diffs carry no
80/// order count.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
82pub struct L2Level {
83    /// `p`: the price.
84    #[serde(rename = "p")]
85    pub px: Dec,
86    /// `s`: the size now resting at the price, in the coin's units.
87    #[serde(rename = "s")]
88    pub sz: Dec,
89}
90
91/// What changed in an `l2` book since the frame before. To apply it, the levels at the indexes in
92/// `removed_bids` and `removed_asks` (positions in the book before) go first, then each level in
93/// `bids` and `asks` is added or replaced by price; [`L2Diff::apply`] does both.
94#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
95#[serde(from = "RawL2Diff")]
96#[non_exhaustive]
97pub struct L2Diff {
98    /// `c`: the coin.
99    pub coin: String,
100    /// Milliseconds.
101    pub time: u64,
102    /// Bid levels added or changed.
103    pub bids: Vec<L2Level>,
104    /// Ask levels added or changed.
105    pub asks: Vec<L2Level>,
106    /// Positions of the bids removed, in the book before this diff.
107    pub removed_bids: Vec<usize>,
108    /// Positions of the asks removed, in the book before this diff.
109    pub removed_asks: Vec<usize>,
110    /// Sent with a bucketed book (`s` on the subscription), as `l2Book`'s `spread` is.
111    pub spread: Option<Dec>,
112}
113
114/// `{"c","t","l":[bids,asks],"r":[bids,asks],"s"}` on the wire.
115#[derive(Deserialize)]
116struct RawL2Diff {
117    c: String,
118    t: u64,
119    l: (Vec<L2Level>, Vec<L2Level>),
120    r: (Vec<usize>, Vec<usize>),
121    #[serde(default)]
122    s: Option<Dec>,
123}
124
125impl From<RawL2Diff> for L2Diff {
126    fn from(raw: RawL2Diff) -> Self {
127        let ((bids, asks), (removed_bids, removed_asks)) = (raw.l, raw.r);
128        L2Diff { coin: raw.c, time: raw.t, bids, asks, removed_bids, removed_asks, spread: raw.s }
129    }
130}
131
132/// An `l2` diff that does not fit the book it was applied to.
133#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
134#[non_exhaustive]
135pub enum BadDiff {
136    /// The diff is for another coin than the book.
137    #[error("a diff for {diff} applied to the book of {book}")]
138    Coin {
139        /// The book's coin.
140        book: String,
141        /// The diff's coin.
142        diff: String,
143    },
144    /// The diff removes a level past the end of a side: a frame was missed.
145    #[error("a diff removes level {index} of a side that has {levels}: a frame was missed")]
146    Index {
147        /// The position the diff removes.
148        index: usize,
149        /// The levels the side has.
150        levels: usize,
151    },
152}
153
154impl L2Diff {
155    /// Applies the diff to `book`, the book as of the frame before: the removed levels go, then
156    /// each level in the diff replaces the one at its price or is added in place, each side kept
157    /// best first. A level the diff adds or changes has `n` 0, since diffs carry no order count.
158    /// The time and spread become the diff's. A diff for another coin, or one that removes a level
159    /// the book does not have, is refused and the book is left as it was.
160    pub fn apply(&self, book: &mut Book) -> Result<(), BadDiff> {
161        if book.coin != self.coin {
162            return Err(BadDiff::Coin { book: book.coin.clone(), diff: self.coin.clone() });
163        }
164        let bids = changed(&book.bids, &self.removed_bids, &self.bids, |a, b| b.cmp(a))?;
165        let asks = changed(&book.asks, &self.removed_asks, &self.asks, Ord::cmp)?;
166        book.bids = bids;
167        book.asks = asks;
168        book.time = self.time;
169        book.spread = self.spread;
170        Ok(())
171    }
172}
173
174/// One side after a diff, sorted best first by `best`.
175fn changed(
176    side: &[Level],
177    removed: &[usize],
178    levels: &[L2Level],
179    best: fn(&Dec, &Dec) -> Ordering,
180) -> Result<Vec<Level>, BadDiff> {
181    if let Some(&index) = removed.iter().find(|&&index| index >= side.len()) {
182        return Err(BadDiff::Index { index, levels: side.len() });
183    }
184    let mut kept: Vec<Level> =
185        side.iter().enumerate().filter(|(index, _)| !removed.contains(index)).map(|(_, level)| *level).collect();
186    for level in levels {
187        let now = Level { px: level.px, sz: level.sz, n: 0 };
188        match kept.binary_search_by(|resting| best(&resting.px, &level.px)) {
189            Ok(at) => kept[at] = now,
190            Err(at) => kept.insert(at, now),
191        }
192    }
193    Ok(kept)
194}
195
196#[cfg(test)]
197#[path = "tests/market.rs"]
198mod tests;