bullet-rust-sdk 0.0.35

Rust SDK for the Bullet trading platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Strongly-typed WebSocket subscription topics.
//!
//! This module provides type-safe topic builders for WebSocket subscriptions,
//! eliminating the need to remember string formats like `"BTC-USD@depth10"`.
//!
//! # Example
//!
//! ```no_run
//! use bullet_rust_sdk::types::RequestId;
//! use bullet_rust_sdk::ws::topics::{KlineInterval, OrderbookDepth, Topic};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let api = bullet_rust_sdk::Client::mainnet().await?;
//! # let mut ws = api.connect_ws().call().await?;
//! // Type-safe subscriptions
//! ws.subscribe(
//!     [
//!         Topic::agg_trade("BTC-USD"),
//!         Topic::depth("ETH-USD", OrderbookDepth::D10),
//!         Topic::book_ticker("SOL-USD"),
//!         Topic::kline("BTC-USD", KlineInterval::H1),
//!     ],
//!     Some(RequestId::new(1)),
//! )
//! .await?;
//! # Ok(())
//! # }
//! ```

use std::fmt;

/// Orderbook depth levels for depth subscriptions.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum OrderbookDepth {
    /// 5 levels
    D5,
    /// 10 levels (default)
    #[default]
    D10,
    /// 20 levels
    D20,
}

impl OrderbookDepth {
    fn as_str(&self) -> &'static str {
        match self {
            OrderbookDepth::D5 => "5",
            OrderbookDepth::D10 => "10",
            OrderbookDepth::D20 => "20",
        }
    }
}

/// Kline (candlestick) intervals.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KlineInterval {
    /// 1 minute
    M1,
    /// 5 minutes
    M5,
    /// 15 minutes
    M15,
    /// 30 minutes
    M30,
    /// 1 hour
    H1,
    /// 4 hours
    H4,
    /// 1 day
    D1,
}

impl KlineInterval {
    fn as_str(&self) -> &'static str {
        match self {
            KlineInterval::M1 => "1m",
            KlineInterval::M5 => "5m",
            KlineInterval::M15 => "15m",
            KlineInterval::M30 => "30m",
            KlineInterval::H1 => "1h",
            KlineInterval::H4 => "4h",
            KlineInterval::D1 => "1d",
        }
    }
}

/// A WebSocket subscription topic.
///
/// Topics are created using the static constructor methods and converted to
/// the wire format automatically when passed to [`subscribe()`](super::WebsocketHandle::subscribe).
///
/// # Available Topics
///
/// | Topic | Description |
/// |-------|-------------|
/// | [`Topic::agg_trade`] | Aggregated trade updates |
/// | [`Topic::depth`] | Order book depth snapshots |
/// | [`Topic::book_ticker`] | Best bid/ask prices |
/// | [`Topic::mark_price`] | Mark price updates |
/// | [`Topic::kline`] | Candlestick/kline data |
/// | [`Topic::force_order`] | Liquidation orders |
/// | [`Topic::user_orders`] | User order updates |
/// | [`Topic::all_tickers`] | All symbol mini tickers |
/// | [`Topic::all_mark_prices`] | All mark prices |
/// | [`Topic::all_book_tickers`] | All best bid/ask |
/// | [`Topic::all_force_orders`] | All liquidations |
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Topic {
    /// Aggregated trade stream for a symbol.
    AggTrade { symbol: String },

    /// Order book depth stream with configurable levels.
    Depth {
        symbol: String,
        depth: OrderbookDepth,
    },

    /// Best bid/ask stream for a symbol.
    BookTicker { symbol: String },

    /// Mark price stream for a symbol.
    MarkPrice { symbol: String },

    /// Kline/candlestick stream for a symbol at an interval.
    Kline {
        symbol: String,
        interval: KlineInterval,
    },

    /// Liquidation order stream for a symbol.
    ForceOrder { symbol: String },

    /// User order stream for an address.
    UserOrders { address: String },

    /// All symbols mini ticker stream.
    AllTickers,

    /// All symbols mark price stream.
    AllMarkPrices,

    /// All symbols book ticker stream.
    AllBookTickers,

    /// All symbols liquidation stream.
    AllForceOrders,
}

impl Topic {
    /// Subscribe to aggregated trades for a symbol.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::Topic;
    ///
    /// let topic = Topic::agg_trade("BTC-USD");
    /// assert_eq!(topic.to_string(), "BTC-USD@aggTrade");
    /// ```
    pub fn agg_trade(symbol: impl Into<String>) -> Self {
        Self::AggTrade {
            symbol: symbol.into(),
        }
    }

    /// Subscribe to order book depth for a symbol.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::{OrderbookDepth, Topic};
    ///
    /// let topic = Topic::depth("BTC-USD", OrderbookDepth::D10);
    /// assert_eq!(topic.to_string(), "BTC-USD@depth10");
    /// ```
    pub fn depth(symbol: impl Into<String>, depth: OrderbookDepth) -> Self {
        Self::Depth {
            symbol: symbol.into(),
            depth,
        }
    }

    /// Subscribe to best bid/ask for a symbol.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::Topic;
    ///
    /// let topic = Topic::book_ticker("BTC-USD");
    /// assert_eq!(topic.to_string(), "BTC-USD@bookTicker");
    /// ```
    pub fn book_ticker(symbol: impl Into<String>) -> Self {
        Self::BookTicker {
            symbol: symbol.into(),
        }
    }

    /// Subscribe to mark price updates for a symbol.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::Topic;
    ///
    /// let topic = Topic::mark_price("BTC-USD");
    /// assert_eq!(topic.to_string(), "BTC-USD@markPrice");
    /// ```
    pub fn mark_price(symbol: impl Into<String>) -> Self {
        Self::MarkPrice {
            symbol: symbol.into(),
        }
    }

    /// Subscribe to kline/candlestick data for a symbol.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::{KlineInterval, Topic};
    ///
    /// let topic = Topic::kline("BTC-USD", KlineInterval::H1);
    /// assert_eq!(topic.to_string(), "BTC-USD@kline_1h");
    /// ```
    pub fn kline(symbol: impl Into<String>, interval: KlineInterval) -> Self {
        Self::Kline {
            symbol: symbol.into(),
            interval,
        }
    }

    /// Subscribe to liquidation orders for a symbol.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::Topic;
    ///
    /// let topic = Topic::force_order("BTC-USD");
    /// assert_eq!(topic.to_string(), "BTC-USD@forceOrder");
    /// ```
    pub fn force_order(symbol: impl Into<String>) -> Self {
        Self::ForceOrder {
            symbol: symbol.into(),
        }
    }

    /// Subscribe to user order updates for an address.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::Topic;
    ///
    /// let topic = Topic::user_orders("0xabc");
    /// assert_eq!(topic.to_string(), "0xabc@user.orders");
    /// ```
    pub fn user_orders(address: impl Into<String>) -> Self {
        Self::UserOrders {
            address: address.into(),
        }
    }

    /// Subscribe to mini ticker updates for all symbols.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::Topic;
    ///
    /// let topic = Topic::all_tickers();
    /// assert_eq!(topic.to_string(), "!ticker@arr");
    /// ```
    pub fn all_tickers() -> Self {
        Self::AllTickers
    }

    /// Subscribe to mark price updates for all symbols.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::Topic;
    ///
    /// let topic = Topic::all_mark_prices();
    /// assert_eq!(topic.to_string(), "!markPrice@arr");
    /// ```
    pub fn all_mark_prices() -> Self {
        Self::AllMarkPrices
    }

    /// Subscribe to book ticker updates for all symbols.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::Topic;
    ///
    /// let topic = Topic::all_book_tickers();
    /// assert_eq!(topic.to_string(), "!bookTicker@arr");
    /// ```
    pub fn all_book_tickers() -> Self {
        Self::AllBookTickers
    }

    /// Subscribe to liquidation orders for all symbols.
    ///
    /// # Example
    ///
    /// ```
    /// use bullet_rust_sdk::ws::topics::Topic;
    ///
    /// let topic = Topic::all_force_orders();
    /// assert_eq!(topic.to_string(), "!forceOrder@arr");
    /// ```
    pub fn all_force_orders() -> Self {
        Self::AllForceOrders
    }
}

impl fmt::Display for Topic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Topic::AggTrade { symbol } => write!(f, "{symbol}@aggTrade"),
            Topic::Depth { symbol, depth } => write!(f, "{symbol}@depth{}", depth.as_str()),
            Topic::BookTicker { symbol } => write!(f, "{symbol}@bookTicker"),
            Topic::MarkPrice { symbol } => write!(f, "{symbol}@markPrice"),
            Topic::Kline { symbol, interval } => write!(f, "{symbol}@kline_{}", interval.as_str()),
            Topic::ForceOrder { symbol } => write!(f, "{symbol}@forceOrder"),
            Topic::UserOrders { address } => write!(f, "{address}@user.orders"),
            Topic::AllTickers => write!(f, "!ticker@arr"),
            Topic::AllMarkPrices => write!(f, "!markPrice@arr"),
            Topic::AllBookTickers => write!(f, "!bookTicker@arr"),
            Topic::AllForceOrders => write!(f, "!forceOrder@arr"),
        }
    }
}

impl From<Topic> for String {
    fn from(topic: Topic) -> Self {
        topic.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_agg_trade() {
        assert_eq!(Topic::agg_trade("BTC-USD").to_string(), "BTC-USD@aggTrade");
    }

    #[test]
    fn test_depth() {
        assert_eq!(
            Topic::depth("BTC-USD", OrderbookDepth::D5).to_string(),
            "BTC-USD@depth5"
        );
        assert_eq!(
            Topic::depth("BTC-USD", OrderbookDepth::D10).to_string(),
            "BTC-USD@depth10"
        );
        assert_eq!(
            Topic::depth("BTC-USD", OrderbookDepth::D20).to_string(),
            "BTC-USD@depth20"
        );
    }

    #[test]
    fn test_book_ticker() {
        assert_eq!(
            Topic::book_ticker("ETH-USD").to_string(),
            "ETH-USD@bookTicker"
        );
    }

    #[test]
    fn test_mark_price() {
        assert_eq!(
            Topic::mark_price("SOL-USD").to_string(),
            "SOL-USD@markPrice"
        );
    }

    #[test]
    fn test_kline() {
        assert_eq!(
            Topic::kline("BTC-USD", KlineInterval::M1).to_string(),
            "BTC-USD@kline_1m"
        );
        assert_eq!(
            Topic::kline("BTC-USD", KlineInterval::H4).to_string(),
            "BTC-USD@kline_4h"
        );
        assert_eq!(
            Topic::kline("BTC-USD", KlineInterval::D1).to_string(),
            "BTC-USD@kline_1d"
        );
    }

    #[test]
    fn test_force_order() {
        assert_eq!(
            Topic::force_order("BTC-USD").to_string(),
            "BTC-USD@forceOrder"
        );
    }

    #[test]
    fn test_user_orders() {
        assert_eq!(Topic::user_orders("0xabc").to_string(), "0xabc@user.orders");
    }

    #[test]
    fn test_all_streams() {
        assert_eq!(Topic::all_tickers().to_string(), "!ticker@arr");
        assert_eq!(Topic::all_mark_prices().to_string(), "!markPrice@arr");
        assert_eq!(Topic::all_book_tickers().to_string(), "!bookTicker@arr");
        assert_eq!(Topic::all_force_orders().to_string(), "!forceOrder@arr");
    }

    #[test]
    fn test_into_string() {
        let topic = Topic::agg_trade("BTC-USD");
        let s: String = topic.into();
        assert_eq!(s, "BTC-USD@aggTrade");
    }
}