Skip to main content

binance_sdk/cms/websocket_streams/
mod.rs

1/*
2 * Binance Announcements
3 *
4 * Binance announcements in English
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
58        websocket_streams_base
59            .signed_streams
60            .store(true, Ordering::Relaxed);
61        websocket_streams_base.clone().connect(streams).await?;
62
63        Ok(Self {
64            websocket_streams_base: websocket_streams_base.clone(),
65            api_client: ApiClient::new(websocket_streams_base.clone()),
66        })
67    }
68
69    /// Subscribes to WebSocket events with a provided callback function.
70    ///
71    /// # Arguments
72    ///
73    /// * `callback` - A mutable function that takes a `WebsocketEvent` and is `Send` and `'static`.
74    ///
75    /// # Returns
76    ///
77    /// A `Subscription` that can be used to manage the event subscription.
78    ///
79    /// # Examples
80    ///
81    ///
82    /// let subscription = `websocket_streams.subscribe_on_ws_events(|event`| {
83    ///     // Handle WebSocket event
84    /// });
85    ///
86    pub fn subscribe_on_ws_events<F>(&self, callback: F) -> Subscription
87    where
88        F: FnMut(WebsocketEvent) + Send + 'static,
89    {
90        let base = Arc::clone(&self.websocket_streams_base);
91        base.common.events.subscribe(callback)
92    }
93
94    /// Unsubscribes from WebSocket events for a given `Subscription`.
95    ///
96    /// # Arguments
97    ///
98    /// * `subscription` - The `Subscription` to unsubscribe from WebSocket events.
99    ///
100    /// # Examples
101    ///
102    ///
103    /// let subscription = `websocket_streams.subscribe_on_ws_events(|event`| {
104    ///     // Handle WebSocket event
105    /// });
106    /// `websocket_streams.unsubscribe_from_ws_events(subscription)`;
107    ///
108    pub fn unsubscribe_from_ws_events(&self, subscription: Subscription) {
109        subscription.unsubscribe();
110    }
111
112    /// Disconnects the WebSocket connection.
113    ///
114    /// # Returns
115    ///
116    /// A `Result` indicating whether the disconnection was successful.
117    /// Returns an error if the disconnection fails.
118    ///
119    /// # Errors
120    ///
121    /// Returns an [`anyhow::Error`] if the connection fails.
122    ///
123    /// # Examples
124    ///
125    ///
126    /// let `websocket_streams` = `WebSocketStreams::new`(...);
127    /// `websocket_streams.disconnect().await`?;
128    ///
129    pub async fn disconnect(&self) -> anyhow::Result<()> {
130        self.websocket_streams_base
131            .disconnect()
132            .await
133            .map_err(anyhow::Error::msg)
134    }
135
136    /// Checks if the WebSocket connection is currently active.
137    ///
138    /// # Returns
139    ///
140    /// A `bool` indicating whether the WebSocket connection is established and connected.
141    ///
142    /// # Examples
143    ///
144    ///
145    /// let `is_active` = `websocket_streams.is_connected().await`;
146    /// if `is_active` {
147    ///     // WebSocket connection is active
148    /// }
149    ///
150    pub async fn is_connected(&self) -> bool {
151        self.websocket_streams_base.is_connected().await
152    }
153
154    /// Sends a ping to the WebSocket server to maintain the connection.
155    ///
156    /// # Examples
157    ///
158    ///
159    /// `websocket_streams.ping_server().await`;
160    ///
161    ///
162    /// This method sends a ping request to the WebSocket server to keep the connection alive
163    /// and check the server's responsiveness.
164    pub async fn ping_server(&self) {
165        self.websocket_streams_base.ping_server().await;
166    }
167
168    /// Subscribes to specified WebSocket streams.
169    ///
170    /// # Arguments
171    ///
172    /// * `streams` - A vector of stream names to subscribe to
173    /// * `id` - An optional identifier for the subscription request
174    ///
175    /// # Examples
176    ///
177    ///
178    /// `websocket_streams.subscribe(vec`!["`btcusdt@trade".to_string()`], None);
179    ///
180    ///
181    /// This method initiates an asynchronous subscription to the specified WebSocket streams.
182    /// The subscription is performed in a separate task using `spawn`.
183    pub fn subscribe(&self, streams: Vec<String>, id: Option<String>) {
184        let base = Arc::clone(&self.websocket_streams_base);
185        spawn(async move { base.subscribe(streams, id.map(StreamId::from), None).await });
186    }
187
188    /// Unsubscribes from specified WebSocket streams.
189    ///
190    /// # Arguments
191    ///
192    /// * `streams` - A vector of stream names to unsubscribe from
193    /// * `id` - An optional identifier for the unsubscription request
194    ///
195    /// # Examples
196    ///
197    ///
198    /// `websocket_streams.unsubscribe(vec`!["`btcusdt@trade".to_string()`], None);
199    ///
200    ///
201    /// This method initiates an asynchronous unsubscription from the specified WebSocket streams.
202    /// The unsubscription is performed in a separate task using `spawn`.
203    pub fn unsubscribe(&self, streams: Vec<String>, id: Option<String>) {
204        let base = Arc::clone(&self.websocket_streams_base);
205        spawn(async move {
206            base.unsubscribe(streams, id.map(StreamId::from), None)
207                .await;
208        });
209    }
210
211    /// Checks if the current WebSocket stream is subscribed to a specific stream.
212    ///
213    /// # Arguments
214    ///
215    /// * `stream` - The name of the stream to check for subscription
216    ///
217    /// # Returns
218    ///
219    /// A boolean indicating whether the stream is currently subscribed
220    ///
221    /// # Examples
222    ///
223    ///
224    /// let `is_subscribed` = `websocket_streams.is_subscribed("btcusdt@trade").await`;
225    ///
226    ///
227    /// This method checks the subscription status of a specific WebSocket stream.
228    pub async fn is_subscribed(&self, stream: &str) -> bool {
229        self.websocket_streams_base.is_subscribed(stream).await
230    }
231
232    ///
233    ///
234    /// Receive push notifications hen Binance publishes announcements in English (language code: en).
235    ///
236    /// # Arguments
237    ///
238    /// - `params`: [`ComAnnouncementEnParams`]
239    ///   The parameters for this operation.
240    ///
241    /// # Returns
242    ///
243    /// [`Arc<WebsocketStream<models::ComAnnouncementEnResponse>>`] on success.
244    ///
245    /// # Errors
246    ///
247    /// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
248    ///
249    ///
250    /// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/products/announcements/announcement).
251    ///
252    pub async fn com_announcement_en(
253        &self,
254    ) -> anyhow::Result<Arc<WebsocketStream<models::ComAnnouncementEnResponse>>> {
255        self.api_client.com_announcement_en().await
256    }
257}