Skip to main content

digdigdig3_core/core/websocket/
stream_kind.rs

1//! StreamKind — typed enumeration of all known WebSocket stream kinds.
2
3use serde::{Deserialize, Serialize};
4
5/// Typed kline interval.  Inner string is the exchange-canonical form after formatting
6/// (e.g. "1m", "1h", "1D").  Equality is by the inner str.
7#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
8pub struct KlineInterval(pub String);
9
10impl KlineInterval {
11    pub fn new(s: impl Into<String>) -> Self {
12        Self(s.into())
13    }
14
15    pub fn as_str(&self) -> &str {
16        &self.0
17    }
18}
19
20impl std::fmt::Display for KlineInterval {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        f.write_str(&self.0)
23    }
24}
25
26/// Full enumeration of all known WebSocket stream kinds across all supported exchanges.
27///
28/// Variants with `{ interval: KlineInterval }` carry a parameter.
29/// All other variants are unit variants (no parameters).
30///
31/// Partitioned into groups for documentation; the enum itself is flat.
32#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
33pub enum StreamKind {
34    // ── Market (price / ticker) ───────────────────────────────────────────────
35    /// Full 24-h rolling ticker (OHLCV + last price + volume)
36    Ticker,
37    /// Index price feed (spot → perpetual fair value)
38    IndexPrice,
39    /// Mark price feed (settlement-reference price)
40    MarkPrice,
41    /// Composite index price (constructed from multiple underlying sources)
42    CompositeIndex,
43
44    // ── OrderBook ────────────────────────────────────────────────────────────
45    /// Level-2 full-depth snapshot
46    Orderbook,
47    /// Level-2 incremental delta stream
48    OrderbookDelta,
49    /// Level-3 per-order (L3) full orderbook
50    OrderbookL3,
51
52    // ── Trade ────────────────────────────────────────────────────────────────
53    /// Individual public trades (time-and-sales)
54    Trade,
55    /// Aggregated trades (multiple fills at same price collapsed)
56    AggTrade,
57    /// Block trade / RFQ event (large off-book transactions)
58    BlockTrade,
59
60    // ── Kline (all carry KlineInterval parameter) ─────────────────────────
61    /// Standard OHLCV candlestick
62    Kline { interval: KlineInterval },
63    /// Mark-price candlestick (futures)
64    MarkPriceKline { interval: KlineInterval },
65    /// Index-price candlestick (futures)
66    IndexPriceKline { interval: KlineInterval },
67    /// Premium-index candlestick (futures; basis ≈ mark−index)
68    PremiumIndexKline { interval: KlineInterval },
69
70    // ── Funding ──────────────────────────────────────────────────────────────
71    /// Live funding rate (updates intraperiod)
72    FundingRate,
73    /// Predicted funding rate before settlement window opens
74    PredictedFunding,
75    /// Actual funding settlement event (rate + charged amount)
76    FundingSettlement,
77
78    // ── Risk / Open Interest / Sentiment ─────────────────────────────────
79    /// Open interest snapshot / update
80    OpenInterest,
81    /// Long/short ratio (market sentiment)
82    LongShortRatio,
83    /// Insurance fund balance update
84    InsuranceFund,
85    /// Risk limit tier update (margin tiers)
86    RiskLimit,
87    /// Basis stream (futures price − spot price)
88    Basis,
89    /// Forced-liquidation event (public)
90    Liquidation,
91
92    // ── Options-specific ─────────────────────────────────────────────────
93    /// Option greeks: delta/gamma/vega/theta/rho + IV
94    OptionGreeks,
95    /// Volatility index (e.g. DVOL on Deribit)
96    VolatilityIndex,
97    /// Historical realized volatility feed
98    HistoricalVolatility,
99
100    // ── Lifecycle / Market Events ─────────────────────────────────────────
101    /// Settlement / expiry delivery event
102    SettlementEvent,
103    /// Auction event (indicative price, crossing state)
104    AuctionEvent,
105    /// Market warning / trading halt notification
106    MarketWarning,
107
108    // ── Private streams (auth-required) ──────────────────────────────────
109    /// Order lifecycle events (create/fill/cancel/expire)
110    OrderUpdate,
111    /// Account balance changes
112    BalanceUpdate,
113    /// Futures position changes
114    PositionUpdate,
115}
116
117impl StreamKind {
118    /// Returns true if this stream kind requires authentication.
119    pub fn is_private(&self) -> bool {
120        matches!(self, Self::OrderUpdate | Self::BalanceUpdate | Self::PositionUpdate)
121    }
122
123    /// Returns true if this variant carries a kline interval parameter.
124    pub fn is_kline(&self) -> bool {
125        matches!(
126            self,
127            Self::Kline { .. }
128                | Self::MarkPriceKline { .. }
129                | Self::IndexPriceKline { .. }
130                | Self::PremiumIndexKline { .. }
131        )
132    }
133}