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