Skip to main content

binance_sdk/alpha/websocket_streams/
mod.rs

1/*
2 * Alpha WebSocket Market Streams
3 *
4 * Access Alpha market streams over WebSocket.
5 *
6 * The version of the OpenAPI document: 1.0.0
7 *
8 *
9 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
10 * https://openapi-generator.tech
11 * Do not edit the class manually.
12 */
13
14#![allow(unused_imports)]
15use serde_json::Value;
16use std::sync::{Arc, atomic::Ordering};
17use tokio::spawn;
18
19use crate::common::config::ConfigurationWebsocketStreams;
20use crate::common::websocket::{
21    Subscription, WebsocketBase, WebsocketStream, WebsocketStreams as WebsocketStreamsBase,
22    create_stream_handler,
23};
24use crate::models::{StreamId, WebsocketEvent, WebsocketMode};
25
26mod apis;
27mod handle;
28mod models;
29
30pub use apis::*;
31pub use handle::*;
32pub use models::*;
33
34const HAS_TIME_UNIT: bool = false;
35
36pub struct WebsocketStreams {
37    websocket_streams_base: Arc<WebsocketStreamsBase>,
38    api_client: ApiClient,
39}
40
41impl WebsocketStreams {
42    pub(crate) async fn connect(
43        config: ConfigurationWebsocketStreams,
44        streams: Vec<String>,
45        mode: Option<WebsocketMode>,
46    ) -> anyhow::Result<Self> {
47        let mut cfg = config;
48        if let Some(m) = mode {
49            cfg.mode = m;
50        }
51
52        if !HAS_TIME_UNIT {
53            cfg.time_unit = None;
54        }
55
56        let websocket_streams_base = WebsocketStreamsBase::new(cfg, vec![], vec![]);
57        websocket_streams_base
58            .stream_id_is_strictly_number
59            .store(true, Ordering::Relaxed);
60        websocket_streams_base.clone().connect(streams).await?;
61
62        Ok(Self {
63            websocket_streams_base: websocket_streams_base.clone(),
64            api_client: ApiClient::new(websocket_streams_base.clone()),
65        })
66    }
67
68    /// Subscribes to WebSocket events with a provided callback function.
69    ///
70    /// # Arguments
71    ///
72    /// * `callback` - A mutable function that takes a `WebsocketEvent` and is `Send` and `'static`.
73    ///
74    /// # Returns
75    ///
76    /// A `Subscription` that can be used to manage the event subscription.
77    ///
78    /// # Examples
79    ///
80    ///
81    /// let subscription = `websocket_streams.subscribe_on_ws_events(|event`| {
82    ///     // Handle WebSocket event
83    /// });
84    ///
85    pub fn subscribe_on_ws_events<F>(&self, callback: F) -> Subscription
86    where
87        F: FnMut(WebsocketEvent) + Send + 'static,
88    {
89        let base = Arc::clone(&self.websocket_streams_base);
90        base.common.events.subscribe(callback)
91    }
92
93    /// Unsubscribes from WebSocket events for a given `Subscription`.
94    ///
95    /// # Arguments
96    ///
97    /// * `subscription` - The `Subscription` to unsubscribe from WebSocket events.
98    ///
99    /// # Examples
100    ///
101    ///
102    /// let subscription = `websocket_streams.subscribe_on_ws_events(|event`| {
103    ///     // Handle WebSocket event
104    /// });
105    /// `websocket_streams.unsubscribe_from_ws_events(subscription)`;
106    ///
107    pub fn unsubscribe_from_ws_events(&self, subscription: Subscription) {
108        subscription.unsubscribe();
109    }
110
111    /// Disconnects the WebSocket connection.
112    ///
113    /// # Returns
114    ///
115    /// A `Result` indicating whether the disconnection was successful.
116    /// Returns an error if the disconnection fails.
117    ///
118    /// # Errors
119    ///
120    /// Returns an [`anyhow::Error`] if the connection fails.
121    ///
122    /// # Examples
123    ///
124    ///
125    /// let `websocket_streams` = `WebSocketStreams::new`(...);
126    /// `websocket_streams.disconnect().await`?;
127    ///
128    pub async fn disconnect(&self) -> anyhow::Result<()> {
129        self.websocket_streams_base
130            .disconnect()
131            .await
132            .map_err(anyhow::Error::msg)
133    }
134
135    /// Checks if the WebSocket connection is currently active.
136    ///
137    /// # Returns
138    ///
139    /// A `bool` indicating whether the WebSocket connection is established and connected.
140    ///
141    /// # Examples
142    ///
143    ///
144    /// let `is_active` = `websocket_streams.is_connected().await`;
145    /// if `is_active` {
146    ///     // WebSocket connection is active
147    /// }
148    ///
149    pub async fn is_connected(&self) -> bool {
150        self.websocket_streams_base.is_connected().await
151    }
152
153    /// Sends a ping to the WebSocket server to maintain the connection.
154    ///
155    /// # Examples
156    ///
157    ///
158    /// `websocket_streams.ping_server().await`;
159    ///
160    ///
161    /// This method sends a ping request to the WebSocket server to keep the connection alive
162    /// and check the server's responsiveness.
163    pub async fn ping_server(&self) {
164        self.websocket_streams_base.ping_server().await;
165    }
166
167    /// Subscribes to specified WebSocket streams.
168    ///
169    /// # Arguments
170    ///
171    /// * `streams` - A vector of stream names to subscribe to
172    /// * `id` - An optional identifier for the subscription request
173    ///
174    /// # Examples
175    ///
176    ///
177    /// `websocket_streams.subscribe(vec`!["`btcusdt@trade".to_string()`], None);
178    ///
179    ///
180    /// This method initiates an asynchronous subscription to the specified WebSocket streams.
181    /// The subscription is performed in a separate task using `spawn`.
182    pub fn subscribe(&self, streams: Vec<String>, id: Option<u32>) {
183        let base = Arc::clone(&self.websocket_streams_base);
184        spawn(async move { base.subscribe(streams, id.map(StreamId::from), None).await });
185    }
186
187    /// Unsubscribes from specified WebSocket streams.
188    ///
189    /// # Arguments
190    ///
191    /// * `streams` - A vector of stream names to unsubscribe from
192    /// * `id` - An optional identifier for the unsubscription request
193    ///
194    /// # Examples
195    ///
196    ///
197    /// `websocket_streams.unsubscribe(vec`!["`btcusdt@trade".to_string()`], None);
198    ///
199    ///
200    /// This method initiates an asynchronous unsubscription from the specified WebSocket streams.
201    /// The unsubscription is performed in a separate task using `spawn`.
202    pub fn unsubscribe(&self, streams: Vec<String>, id: Option<u32>) {
203        let base = Arc::clone(&self.websocket_streams_base);
204        spawn(async move {
205            base.unsubscribe(streams, id.map(StreamId::from), None)
206                .await;
207        });
208    }
209
210    /// Checks if the current WebSocket stream is subscribed to a specific stream.
211    ///
212    /// # Arguments
213    ///
214    /// * `stream` - The name of the stream to check for subscription
215    ///
216    /// # Returns
217    ///
218    /// A boolean indicating whether the stream is currently subscribed
219    ///
220    /// # Examples
221    ///
222    ///
223    /// let `is_subscribed` = `websocket_streams.is_subscribed("btcusdt@trade").await`;
224    ///
225    ///
226    /// This method checks the subscription status of a specific WebSocket stream.
227    pub async fn is_subscribed(&self, stream: &str) -> bool {
228        self.websocket_streams_base.is_subscribed(stream).await
229    }
230
231    /// Aggregate Trade Stream
232    ///
233    /// Pushes aggregate trade updates for a symbol.
234    ///
235    /// # Arguments
236    ///
237    /// - `params`: [`AggregateTradeStreamParams`]
238    ///   The parameters for this operation.
239    ///
240    /// # Returns
241    ///
242    /// [`Arc<WebsocketStream<models::AggregateTradeStreamResponse>>`] on success.
243    ///
244    /// # Errors
245    ///
246    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
247    ///
248    ///
249    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#aggregate-trade-stream).
250    ///
251    pub async fn aggregate_trade_stream(
252        &self,
253        params: AggregateTradeStreamParams,
254    ) -> anyhow::Result<Arc<WebsocketStream<models::AggregateTradeStreamResponse>>> {
255        self.api_client.aggregate_trade_stream(params).await
256    }
257
258    /// All Book Ticker Stream
259    ///
260    /// Pushes best bid/ask updates for all symbols.
261    ///
262    /// # Arguments
263    ///
264    /// - `params`: [`AllBookTickerStreamParams`]
265    ///   The parameters for this operation.
266    ///
267    /// # Returns
268    ///
269    /// [`Arc<WebsocketStream<models::AllBookTickerStreamResponse>>`] on success.
270    ///
271    /// # Errors
272    ///
273    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
274    ///
275    ///
276    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#all-book-ticker-stream).
277    ///
278    pub async fn all_book_ticker_stream(
279        &self,
280        params: AllBookTickerStreamParams,
281    ) -> anyhow::Result<Arc<WebsocketStream<models::AllBookTickerStreamResponse>>> {
282        self.api_client.all_book_ticker_stream(params).await
283    }
284
285    /// All Mini Ticker Stream
286    ///
287    /// Pushes mini ticker statistics for all symbols.
288    ///
289    /// # Arguments
290    ///
291    /// - `params`: [`AllMiniTickerStreamParams`]
292    ///   The parameters for this operation.
293    ///
294    /// # Returns
295    ///
296    /// [`Arc<WebsocketStream<models::AllMiniTickerStreamResponse>>`] on success.
297    ///
298    /// # Errors
299    ///
300    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
301    ///
302    ///
303    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#all-mini-ticker-stream).
304    ///
305    pub async fn all_mini_ticker_stream(
306        &self,
307        params: AllMiniTickerStreamParams,
308    ) -> anyhow::Result<Arc<WebsocketStream<models::AllMiniTickerStreamResponse>>> {
309        self.api_client.all_mini_ticker_stream(params).await
310    }
311
312    /// All Ticker Stream
313    ///
314    /// Pushes full ticker statistics for all symbols.
315    ///
316    /// # Arguments
317    ///
318    /// - `params`: [`AllTickerStreamParams`]
319    ///   The parameters for this operation.
320    ///
321    /// # Returns
322    ///
323    /// [`Arc<WebsocketStream<models::AllTickerStreamResponse>>`] on success.
324    ///
325    /// # Errors
326    ///
327    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
328    ///
329    ///
330    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#all-ticker-stream).
331    ///
332    pub async fn all_ticker_stream(
333        &self,
334        params: AllTickerStreamParams,
335    ) -> anyhow::Result<Arc<WebsocketStream<models::AllTickerStreamResponse>>> {
336        self.api_client.all_ticker_stream(params).await
337    }
338
339    /// All Tokens 24h Ticker Stream
340    ///
341    /// Pushes 24h ticker-like metrics for all tokens.
342    ///
343    /// # Arguments
344    ///
345    /// - `params`: [`AllTokens24hTickerStreamParams`]
346    ///   The parameters for this operation.
347    ///
348    /// # Returns
349    ///
350    /// [`Arc<WebsocketStream<models::AllTokens24hTickerStreamResponse>>`] on success.
351    ///
352    /// # Errors
353    ///
354    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
355    ///
356    ///
357    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#all-tokens24h-ticker-stream).
358    ///
359    pub async fn all_tokens24h_ticker_stream(
360        &self,
361        params: AllTokens24hTickerStreamParams,
362    ) -> anyhow::Result<Arc<WebsocketStream<models::AllTokens24hTickerStreamResponse>>> {
363        self.api_client.all_tokens24h_ticker_stream(params).await
364    }
365
366    /// Book Ticker Stream
367    ///
368    /// Pushes best bid/ask updates for a symbol.
369    ///
370    /// # Arguments
371    ///
372    /// - `params`: [`BookTickerStreamParams`]
373    ///   The parameters for this operation.
374    ///
375    /// # Returns
376    ///
377    /// [`Arc<WebsocketStream<models::BookTickerStreamResponse>>`] on success.
378    ///
379    /// # Errors
380    ///
381    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
382    ///
383    ///
384    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#book-ticker-stream).
385    ///
386    pub async fn book_ticker_stream(
387        &self,
388        params: BookTickerStreamParams,
389    ) -> anyhow::Result<Arc<WebsocketStream<models::BookTickerStreamResponse>>> {
390        self.api_client.book_ticker_stream(params).await
391    }
392
393    /// Contract Kline Stream
394    ///
395    /// Pushes kline updates by contractAddress@chainId.
396    ///
397    /// # Arguments
398    ///
399    /// - `params`: [`ContractKlineStreamParams`]
400    ///   The parameters for this operation.
401    ///
402    /// # Returns
403    ///
404    /// [`Arc<WebsocketStream<models::ContractKlineStreamResponse>>`] on success.
405    ///
406    /// # Errors
407    ///
408    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
409    ///
410    ///
411    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#contract-kline-stream).
412    ///
413    pub async fn contract_kline_stream(
414        &self,
415        params: ContractKlineStreamParams,
416    ) -> anyhow::Result<Arc<WebsocketStream<models::ContractKlineStreamResponse>>> {
417        self.api_client.contract_kline_stream(params).await
418    }
419
420    /// Full Depth Stream
421    ///
422    /// Returns all available depth, including UI and API orders.
423    ///
424    /// # Arguments
425    ///
426    /// - `params`: [`FullDepthStreamParams`]
427    ///   The parameters for this operation.
428    ///
429    /// # Returns
430    ///
431    /// [`Arc<WebsocketStream<models::FullDepthStreamResponse>>`] on success.
432    ///
433    /// # Errors
434    ///
435    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
436    ///
437    ///
438    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#full-depth-stream).
439    ///
440    pub async fn full_depth_stream(
441        &self,
442        params: FullDepthStreamParams,
443    ) -> anyhow::Result<Arc<WebsocketStream<models::FullDepthStreamResponse>>> {
444        self.api_client.full_depth_stream(params).await
445    }
446
447    /// Kline Stream
448    ///
449    /// Pushes kline updates for a symbol.
450    ///
451    /// # Arguments
452    ///
453    /// - `params`: [`KlineStreamParams`]
454    ///   The parameters for this operation.
455    ///
456    /// # Returns
457    ///
458    /// [`Arc<WebsocketStream<models::KlineStreamResponse>>`] on success.
459    ///
460    /// # Errors
461    ///
462    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
463    ///
464    ///
465    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#kline-stream).
466    ///
467    pub async fn kline_stream(
468        &self,
469        params: KlineStreamParams,
470    ) -> anyhow::Result<Arc<WebsocketStream<models::KlineStreamResponse>>> {
471        self.api_client.kline_stream(params).await
472    }
473
474    /// Mini Ticker Stream
475    ///
476    /// Pushes 24h rolling mini ticker statistics.
477    ///
478    /// # Arguments
479    ///
480    /// - `params`: [`MiniTickerStreamParams`]
481    ///   The parameters for this operation.
482    ///
483    /// # Returns
484    ///
485    /// [`Arc<WebsocketStream<models::MiniTickerStreamResponse>>`] on success.
486    ///
487    /// # Errors
488    ///
489    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
490    ///
491    ///
492    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#mini-ticker-stream).
493    ///
494    pub async fn mini_ticker_stream(
495        &self,
496        params: MiniTickerStreamParams,
497    ) -> anyhow::Result<Arc<WebsocketStream<models::MiniTickerStreamResponse>>> {
498        self.api_client.mini_ticker_stream(params).await
499    }
500
501    /// Partial Depth Stream
502    ///
503    /// Pushes partial depth updates (UI orders only).
504    ///
505    /// # Arguments
506    ///
507    /// - `params`: [`PartialDepthStreamParams`]
508    ///   The parameters for this operation.
509    ///
510    /// # Returns
511    ///
512    /// [`Arc<WebsocketStream<models::PartialDepthStreamResponse>>`] on success.
513    ///
514    /// # Errors
515    ///
516    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
517    ///
518    ///
519    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#partial-depth-stream).
520    ///
521    pub async fn partial_depth_stream(
522        &self,
523        params: PartialDepthStreamParams,
524    ) -> anyhow::Result<Arc<WebsocketStream<models::PartialDepthStreamResponse>>> {
525        self.api_client.partial_depth_stream(params).await
526    }
527
528    /// Ticker Stream
529    ///
530    /// Pushes full 24h rolling ticker statistics.
531    ///
532    /// # Arguments
533    ///
534    /// - `params`: [`TickerStreamParams`]
535    ///   The parameters for this operation.
536    ///
537    /// # Returns
538    ///
539    /// [`Arc<WebsocketStream<models::TickerStreamResponse>>`] on success.
540    ///
541    /// # Errors
542    ///
543    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
544    ///
545    ///
546    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#ticker-stream).
547    ///
548    pub async fn ticker_stream(
549        &self,
550        params: TickerStreamParams,
551    ) -> anyhow::Result<Arc<WebsocketStream<models::TickerStreamResponse>>> {
552        self.api_client.ticker_stream(params).await
553    }
554
555    /// Trade Stream
556    ///
557    /// Pushes raw trade updates for a symbol.
558    ///
559    /// # Arguments
560    ///
561    /// - `params`: [`TradeStreamParams`]
562    ///   The parameters for this operation.
563    ///
564    /// # Returns
565    ///
566    /// [`Arc<WebsocketStream<models::TradeStreamResponse>>`] on success.
567    ///
568    /// # Errors
569    ///
570    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
571    ///
572    ///
573    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-alpha-trading/api/ws-streams/~#trade-stream).
574    ///
575    pub async fn trade_stream(
576        &self,
577        params: TradeStreamParams,
578    ) -> anyhow::Result<Arc<WebsocketStream<models::TradeStreamResponse>>> {
579        self.api_client.trade_stream(params).await
580    }
581}