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