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