Skip to main content

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