df_hyperliquid_core/live/subscription/mod.rs
1//! Every subscription the venue serves (the docs' list, plus `assetCtxs`, `spotAssetCtxs` and
2//! `userHistoricalOrders`), as the object a subscribe or unsubscribe frame carries. `webData2` is
3//! gone: the venue refuses it.
4
5mod parse;
6mod wire;
7
8use crate::markets::Interval;
9use crate::utils::Address;
10
11/// One feed. A coin is spelled as the venue spells it: `BTC`, `xyz:SP500` (HIP-3), `@107` or
12/// `PURR/USDC` (spot), `#14720` (an outcome side). A `dex` of `""` is the first perp dex.
13#[derive(Debug, Clone, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum Subscription {
16 /// Every coin's mid on one perp dex. The first dex's also carries spot and outcome mids.
17 AllMids {
18 /// The dex, `""` for the first.
19 dex: String,
20 },
21 /// Short texts for the account: fills, liquidations.
22 Notification {
23 /// The account.
24 user: Address,
25 },
26 /// The account as Hyperliquid's own frontend reads it.
27 WebData3 {
28 /// The account.
29 user: Address,
30 },
31 /// The account's running TWAPs on one dex, on the channel `twapStates`.
32 TwapStates {
33 /// The account.
34 user: Address,
35 /// The dex, `""` for the first.
36 dex: String,
37 },
38 /// The account's clearinghouse on one dex, on the channel `clearinghouseState`.
39 ClearinghouseState {
40 /// The account.
41 user: Address,
42 /// The dex, `""` for the first.
43 dex: String,
44 },
45 /// The account's resting orders on one dex, on the channel `openOrders`.
46 OpenOrders {
47 /// The account.
48 user: Address,
49 /// The dex, `""` for the first.
50 dex: String,
51 },
52 /// One coin's candles at one interval, on the channel `candle`.
53 Candle {
54 /// The coin.
55 coin: String,
56 /// The candle interval.
57 interval: Interval,
58 },
59 /// `n_sig_figs` groups levels to 2 to 5 significant figures; `mantissa` (1, 2 or 5) groups
60 /// further, with 5 figures only. `fast` gives 5 levels a side more often, not 20.
61 ///
62 /// How often a book comes matters more than the venue's docs suggest. They say a book is sent
63 /// at most every 0.5 s, but on mainnet in November 2026 a BTC book without `fast` came about
64 /// every 7 s, so a program that waits for it holds a stale book. With `fast` it came about
65 /// twice a second, 5 levels a side. For the best bid and ask alone, [`Subscription::Bbo`] is
66 /// sent on every block where they change (about ten times a second for BTC).
67 ///
68 /// For both speed and depth, subscribe twice on one feed: `bbo` or a fast book for the top of
69 /// the book, and a book without `fast` for the twenty levels a side.
70 ///
71 /// ```
72 /// use df_hyperliquid_core::live::Subscription;
73 ///
74 /// let coin = || "BTC".to_owned();
75 /// let top = Subscription::L2Book { coin: coin(), n_sig_figs: None, mantissa: None, fast: true };
76 /// let depth = Subscription::L2Book { coin: coin(), n_sig_figs: None, mantissa: None, fast: false };
77 /// let touch = Subscription::Bbo { coin: coin() };
78 /// # let _ = (top, depth, touch);
79 /// ```
80 L2Book {
81 /// The coin.
82 coin: String,
83 /// `nSigFigs`: 2 to 5 significant figures; `None` for full precision.
84 n_sig_figs: Option<u8>,
85 /// `mantissa`: 1, 2 or 5, with `n_sig_figs` 5 only; `None` when not grouped further.
86 mantissa: Option<u8>,
87 /// `fast`: whether to get 5 levels a side more often instead of 20; sent only when true.
88 fast: bool,
89 },
90 /// One coin's prints, on the channel `trades`.
91 Trades {
92 /// The coin.
93 coin: String,
94 },
95 /// Status changes of the account's orders, on the channel `orderUpdates`.
96 OrderUpdates {
97 /// The account.
98 user: Address,
99 },
100 /// Its data comes on the channel `user`.
101 UserEvents {
102 /// The account.
103 user: Address,
104 },
105 /// `aggregate_by_time` merges the partial fills of one crossing order.
106 UserFills {
107 /// The account.
108 user: Address,
109 /// `aggregateByTime`: whether to merge the partial fills of one crossing order; sent only when true.
110 aggregate_by_time: bool,
111 },
112 /// The account's funding payments, on the channel `userFundings`.
113 UserFundings {
114 /// The account.
115 user: Address,
116 },
117 /// The account's ledger rows other than funding, on the channel `userNonFundingLedgerUpdates`.
118 UserNonFundingLedgerUpdates {
119 /// The account.
120 user: Address,
121 },
122 /// A perp's context; a spot pair's or an outcome side's comes on `activeSpotAssetCtx`.
123 ActiveAssetCtx {
124 /// The coin.
125 coin: String,
126 },
127 /// What the account may trade on a perp. Perps only.
128 ActiveAssetData {
129 /// The account.
130 user: Address,
131 /// The perp's coin.
132 coin: String,
133 },
134 /// Fills of the account's TWAP slices, on the channel `userTwapSliceFills`.
135 UserTwapSliceFills {
136 /// The account.
137 user: Address,
138 },
139 /// The account's TWAP events, on the channel `userTwapHistory`.
140 UserTwapHistory {
141 /// The account.
142 user: Address,
143 },
144 /// The best bid and offer, sent only when one of them moves.
145 Bbo {
146 /// The coin.
147 coin: String,
148 },
149 /// The docs name the option `isPortfolioMargin`; the venue ignores that and echoes
150 /// `ignorePortfolioMargin`, which is what it reads.
151 SpotState {
152 /// The account.
153 user: Address,
154 /// `ignorePortfolioMargin`, the option the venue reads; sent only when true.
155 ignore_portfolio_margin: bool,
156 },
157 /// The account's clearinghouse on every dex, on the channel `allDexsClearinghouseState`.
158 AllDexsClearinghouseState {
159 /// The account.
160 user: Address,
161 },
162 /// Every perp dex's contexts in one frame.
163 AllDexsAssetCtxs,
164 /// Changes to `outcomeMeta`, sent only when something changes.
165 OutcomeMetaUpdates,
166 /// Mark and mid changes, base64 of raw DEFLATE.
167 FastAssetCtxs,
168 /// One perp dex's contexts. In `@nktkas/hyperliquid`, not on the docs' list.
169 AssetCtxs {
170 /// The dex, `""` for the first.
171 dex: String,
172 },
173 /// Every spot and outcome context. In `@nktkas/hyperliquid`, not on the docs' list.
174 SpotAssetCtxs,
175 /// Orders and what became of them. In `@nktkas/hyperliquid`, not on the docs' list.
176 UserHistoricalOrders {
177 /// The account.
178 user: Address,
179 },
180 /// The book as a snapshot of up to twenty levels a side, then diffs. `n_sig_figs` and
181 /// `mantissa` group levels as on [`Subscription::L2Book`]; on the wire they are `s` and `m`, and
182 /// the coin is `c`.
183 L2 {
184 /// `c`: the coin.
185 coin: String,
186 /// `s`: 2 to 5 significant figures; `None` for full precision.
187 n_sig_figs: Option<u8>,
188 /// `m`: 1, 2 or 5, with `n_sig_figs` 5 only; `None` when not grouped further.
189 mantissa: Option<u8>,
190 },
191 /// Every perp dex's contexts, base64 of raw DEFLATE: a snapshot, then only what changed.
192 Pac,
193 /// Every spot pair's and outcome side's context by coin, base64 of raw DEFLATE: a snapshot,
194 /// then only what changed.
195 Sac,
196}
197
198/// Why an object is not a subscription, or a subscription is not one the venue would take.
199#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
200#[non_exhaustive]
201pub enum BadSubscription {
202 /// The value is not a JSON object.
203 #[error("a subscription is an object")]
204 NotAnObject,
205 /// The `type` names no subscription the venue serves; the `type` as written.
206 #[error("`{0}` is not a subscription the venue serves")]
207 UnknownType(String),
208 /// A field the subscription needs is not there.
209 #[error("`{kind}` needs `{field}`")]
210 Missing {
211 /// The subscription's `type`, or `subscription` when the `type` itself is at fault.
212 kind: &'static str,
213 /// The missing field's wire name.
214 field: &'static str,
215 },
216 /// A field is there but of the wrong JSON type.
217 #[error("`{field}` of `{kind}` must be {expected}")]
218 Wrong {
219 /// The subscription's `type`, or `subscription` when the `type` itself is at fault.
220 kind: &'static str,
221 /// The field's wire name.
222 field: &'static str,
223 /// What the field must be, in words.
224 expected: &'static str,
225 },
226 /// The coin is `""`.
227 #[error("a coin is never an empty string")]
228 EmptyCoin,
229 /// `nSigFigs` is not 2, 3, 4 or 5; the value given.
230 #[error("nSigFigs is 2, 3, 4 or 5, not {0}")]
231 SigFigs(u8),
232 /// `mantissa` is not 1, 2 or 5, or comes without `nSigFigs` 5; the value given.
233 #[error("mantissa is 1, 2 or 5, and only with nSigFigs 5; {0} is refused here")]
234 Mantissa(u8),
235}
236
237impl Subscription {
238 /// Its `type`.
239 #[must_use]
240 pub const fn kind(&self) -> &'static str {
241 match self {
242 Subscription::AllMids { .. } => "allMids",
243 Subscription::Notification { .. } => "notification",
244 Subscription::WebData3 { .. } => "webData3",
245 Subscription::TwapStates { .. } => "twapStates",
246 Subscription::ClearinghouseState { .. } => "clearinghouseState",
247 Subscription::OpenOrders { .. } => "openOrders",
248 Subscription::Candle { .. } => "candle",
249 Subscription::L2Book { .. } => "l2Book",
250 Subscription::Trades { .. } => "trades",
251 Subscription::OrderUpdates { .. } => "orderUpdates",
252 Subscription::UserEvents { .. } => "userEvents",
253 Subscription::UserFills { .. } => "userFills",
254 Subscription::UserFundings { .. } => "userFundings",
255 Subscription::UserNonFundingLedgerUpdates { .. } => "userNonFundingLedgerUpdates",
256 Subscription::ActiveAssetCtx { .. } => "activeAssetCtx",
257 Subscription::ActiveAssetData { .. } => "activeAssetData",
258 Subscription::UserTwapSliceFills { .. } => "userTwapSliceFills",
259 Subscription::UserTwapHistory { .. } => "userTwapHistory",
260 Subscription::Bbo { .. } => "bbo",
261 Subscription::SpotState { .. } => "spotState",
262 Subscription::AllDexsClearinghouseState { .. } => "allDexsClearinghouseState",
263 Subscription::AllDexsAssetCtxs => "allDexsAssetCtxs",
264 Subscription::OutcomeMetaUpdates => "outcomeMetaUpdates",
265 Subscription::FastAssetCtxs => "fastAssetCtxs",
266 Subscription::AssetCtxs { .. } => "assetCtxs",
267 Subscription::SpotAssetCtxs => "spotAssetCtxs",
268 Subscription::UserHistoricalOrders { .. } => "userHistoricalOrders",
269 Subscription::L2 { .. } => "l2",
270 Subscription::Pac => "pac",
271 Subscription::Sac => "sac",
272 }
273 }
274
275 /// The channel its data comes on: its `type`, except `userEvents` (on `user`) and a spot or
276 /// outcome coin's `activeAssetCtx` (on `activeSpotAssetCtx`), so matching on the name sent
277 /// would never fire.
278 #[must_use]
279 pub fn channel(&self) -> &'static str {
280 match self {
281 Subscription::UserEvents { .. } => "user",
282 Subscription::ActiveAssetCtx { coin } if is_spot(coin) => "activeSpotAssetCtx",
283 other => other.kind(),
284 }
285 }
286
287 /// The account a user subscription follows. The venue allows ten across an IP's
288 /// subscriptions.
289 #[must_use]
290 pub const fn user(&self) -> Option<Address> {
291 match self {
292 Subscription::Notification { user }
293 | Subscription::WebData3 { user }
294 | Subscription::TwapStates { user, .. }
295 | Subscription::ClearinghouseState { user, .. }
296 | Subscription::OpenOrders { user, .. }
297 | Subscription::OrderUpdates { user }
298 | Subscription::UserEvents { user }
299 | Subscription::UserFills { user, .. }
300 | Subscription::UserFundings { user }
301 | Subscription::UserNonFundingLedgerUpdates { user }
302 | Subscription::ActiveAssetData { user, .. }
303 | Subscription::UserTwapSliceFills { user }
304 | Subscription::UserTwapHistory { user }
305 | Subscription::SpotState { user, .. }
306 | Subscription::AllDexsClearinghouseState { user }
307 | Subscription::UserHistoricalOrders { user } => Some(*user),
308 _ => None,
309 }
310 }
311
312 /// The coin it follows, for the subscriptions that follow one.
313 #[must_use]
314 pub fn coin(&self) -> Option<&str> {
315 match self {
316 Subscription::Candle { coin, .. }
317 | Subscription::L2Book { coin, .. }
318 | Subscription::L2 { coin, .. }
319 | Subscription::Trades { coin }
320 | Subscription::ActiveAssetCtx { coin }
321 | Subscription::ActiveAssetData { coin, .. }
322 | Subscription::Bbo { coin } => Some(coin),
323 _ => None,
324 }
325 }
326
327 /// Whether the venue would take it: a coin is named, and a book's grouping is one the info
328 /// docs allow. The venue drops the whole socket for some subscriptions it cannot serve (a
329 /// `bbo` of an unknown coin), so a coin should come from the venue's own lists.
330 pub fn check(&self) -> Result<(), BadSubscription> {
331 if self.coin().is_some_and(str::is_empty) {
332 return Err(BadSubscription::EmptyCoin);
333 }
334 if let Subscription::L2Book { n_sig_figs, mantissa, .. } | Subscription::L2 { n_sig_figs, mantissa, .. } = self
335 {
336 if let Some(figures) = n_sig_figs.filter(|figures| !(2..=5).contains(figures)) {
337 return Err(BadSubscription::SigFigs(figures));
338 }
339 if let Some(mantissa) = mantissa.filter(|mantissa| *n_sig_figs != Some(5) || ![1, 2, 5].contains(mantissa))
340 {
341 return Err(BadSubscription::Mantissa(mantissa));
342 }
343 }
344 Ok(())
345 }
346}
347
348/// A spot pair (`@107`, `PURR/USDC`) or an outcome side (`#14720`, `+14720`), by its spelling.
349fn is_spot(coin: &str) -> bool {
350 coin.starts_with(['@', '#', '+']) || coin.contains('/')
351}
352
353#[cfg(test)]
354#[path = "tests/fixtures.rs"]
355mod fixtures;
356
357#[cfg(test)]
358#[path = "tests/subscription.rs"]
359mod tests;