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
/*
* Stocks Trading WebSocket Streams
*
* WebSocket stream definitions for Binance Stocks Trading. Base URL: wss://nbstream.binance.com/equity
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#![allow(unused_imports)]
use serde_json::Value;
use std::sync::{Arc, atomic::Ordering};
use tokio::spawn;
use crate::common::config::ConfigurationWebsocketStreams;
use crate::common::websocket::{
Subscription, WebsocketBase, WebsocketStream, WebsocketStreams as WebsocketStreamsBase,
create_stream_handler,
};
use crate::models::{StreamId, WebsocketEvent, WebsocketMode};
mod apis;
mod handle;
mod models;
pub use apis::*;
pub use handle::*;
pub use models::*;
const HAS_TIME_UNIT: bool = false;
pub struct WebsocketStreams {
websocket_streams_base: Arc<WebsocketStreamsBase>,
market_streams_api_client: MarketStreamsApiClient,
user_streams_api_client: UserStreamsApiClient,
}
impl WebsocketStreams {
pub(crate) async fn connect(
config: ConfigurationWebsocketStreams,
streams: Vec<String>,
mode: Option<WebsocketMode>,
) -> anyhow::Result<Self> {
let mut cfg = config;
if let Some(m) = mode {
cfg.mode = m;
}
if !HAS_TIME_UNIT {
cfg.time_unit = None;
}
let websocket_streams_base = WebsocketStreamsBase::new(cfg, vec![], vec![]);
websocket_streams_base.clone().connect(streams).await?;
Ok(Self {
websocket_streams_base: websocket_streams_base.clone(),
market_streams_api_client: MarketStreamsApiClient::new(websocket_streams_base.clone()),
user_streams_api_client: UserStreamsApiClient::new(websocket_streams_base.clone()),
})
}
/// Subscribes to WebSocket events with a provided callback function.
///
/// # Arguments
///
/// * `callback` - A mutable function that takes a `WebsocketEvent` and is `Send` and `'static`.
///
/// # Returns
///
/// A `Subscription` that can be used to manage the event subscription.
///
/// # Examples
///
///
/// let subscription = `websocket_streams.subscribe_on_ws_events(|event`| {
/// // Handle WebSocket event
/// });
///
pub fn subscribe_on_ws_events<F>(&self, callback: F) -> Subscription
where
F: FnMut(WebsocketEvent) + Send + 'static,
{
let base = Arc::clone(&self.websocket_streams_base);
base.common.events.subscribe(callback)
}
/// Unsubscribes from WebSocket events for a given `Subscription`.
///
/// # Arguments
///
/// * `subscription` - The `Subscription` to unsubscribe from WebSocket events.
///
/// # Examples
///
///
/// let subscription = `websocket_streams.subscribe_on_ws_events(|event`| {
/// // Handle WebSocket event
/// });
/// `websocket_streams.unsubscribe_from_ws_events(subscription)`;
///
pub fn unsubscribe_from_ws_events(&self, subscription: Subscription) {
subscription.unsubscribe();
}
/// Disconnects the WebSocket connection.
///
/// # Returns
///
/// A `Result` indicating whether the disconnection was successful.
/// Returns an error if the disconnection fails.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the connection fails.
///
/// # Examples
///
///
/// let `websocket_streams` = `WebSocketStreams::new`(...);
/// `websocket_streams.disconnect().await`?;
///
pub async fn disconnect(&self) -> anyhow::Result<()> {
self.websocket_streams_base
.disconnect()
.await
.map_err(anyhow::Error::msg)
}
/// Checks if the WebSocket connection is currently active.
///
/// # Returns
///
/// A `bool` indicating whether the WebSocket connection is established and connected.
///
/// # Examples
///
///
/// let `is_active` = `websocket_streams.is_connected().await`;
/// if `is_active` {
/// // WebSocket connection is active
/// }
///
pub async fn is_connected(&self) -> bool {
self.websocket_streams_base.is_connected().await
}
/// Sends a ping to the WebSocket server to maintain the connection.
///
/// # Examples
///
///
/// `websocket_streams.ping_server().await`;
///
///
/// This method sends a ping request to the WebSocket server to keep the connection alive
/// and check the server's responsiveness.
pub async fn ping_server(&self) {
self.websocket_streams_base.ping_server().await;
}
/// Subscribes to specified WebSocket streams.
///
/// # Arguments
///
/// * `streams` - A vector of stream names to subscribe to
/// * `id` - An optional identifier for the subscription request
///
/// # Examples
///
///
/// `websocket_streams.subscribe(vec`!["`btcusdt@trade".to_string()`], None);
///
///
/// This method initiates an asynchronous subscription to the specified WebSocket streams.
/// The subscription is performed in a separate task using `spawn`.
pub fn subscribe(&self, streams: Vec<String>, id: Option<String>) {
let base = Arc::clone(&self.websocket_streams_base);
spawn(async move { base.subscribe(streams, id.map(StreamId::from), None).await });
}
/// Unsubscribes from specified WebSocket streams.
///
/// # Arguments
///
/// * `streams` - A vector of stream names to unsubscribe from
/// * `id` - An optional identifier for the unsubscription request
///
/// # Examples
///
///
/// `websocket_streams.unsubscribe(vec`!["`btcusdt@trade".to_string()`], None);
///
///
/// This method initiates an asynchronous unsubscription from the specified WebSocket streams.
/// The unsubscription is performed in a separate task using `spawn`.
pub fn unsubscribe(&self, streams: Vec<String>, id: Option<String>) {
let base = Arc::clone(&self.websocket_streams_base);
spawn(async move {
base.unsubscribe(streams, id.map(StreamId::from), None)
.await;
});
}
/// Checks if the current WebSocket stream is subscribed to a specific stream.
///
/// # Arguments
///
/// * `stream` - The name of the stream to check for subscription
///
/// # Returns
///
/// A boolean indicating whether the stream is currently subscribed
///
/// # Examples
///
///
/// let `is_subscribed` = `websocket_streams.is_subscribed("btcusdt@trade").await`;
///
///
/// This method checks the subscription status of a specific WebSocket stream.
pub async fn is_subscribed(&self, stream: &str) -> bool {
self.websocket_streams_base.is_subscribed(stream).await
}
/// Calendar Stream
///
/// Single-stream broadcast of market-phase transitions. One message per transition; no periodic heartbeat payload. Server polls every 5 seconds. Also reachable via the SUBSCRIBE/UNSUBSCRIBE RPC — see [Subscribing via RPC](https://developers.binance.com/en/docs/products/stocks/websocket-streams-general-info#subscribing-via-rpc).
///
/// # Arguments
///
/// - `params`: [`CalendarStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::CalendarStreamResponse>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-stocks-trading/api/ws-streams/market-streams#calendar-stream).
///
pub async fn calendar_stream(
&self,
params: CalendarStreamParams,
) -> anyhow::Result<Arc<WebsocketStream<models::CalendarStreamResponse>>> {
self.market_streams_api_client.calendar_stream(params).await
}
/// Kline Stream
///
/// Per-symbol candlestick updates. One stream per (symbol, interval) combination. Supported intervals: 5m, 1h, 1d, 1w, 1M. Also reachable via the SUBSCRIBE/UNSUBSCRIBE RPC — see [Subscribing via RPC](https://developers.binance.com/en/docs/products/stocks/websocket-streams-general-info#subscribing-via-rpc).
///
/// # Arguments
///
/// - `params`: [`KlineStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::KlineStreamResponse>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-stocks-trading/api/ws-streams/market-streams#kline-stream).
///
pub async fn kline_stream(
&self,
params: KlineStreamParams,
) -> anyhow::Result<Arc<WebsocketStream<models::KlineStreamResponse>>> {
self.market_streams_api_client.kline_stream(params).await
}
/// Price Stream
///
/// Push-all price snapshot, polled every 3 seconds. One message carries the latest price for every active US-equity symbol. Also reachable via the SUBSCRIBE/UNSUBSCRIBE RPC — see [Subscribing via RPC](https://developers.binance.com/en/docs/products/stocks/websocket-streams-general-info#subscribing-via-rpc).
///
/// # Arguments
///
/// - `params`: [`PriceStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::PriceStreamResponse>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-stocks-trading/api/ws-streams/market-streams#price-stream).
///
pub async fn price_stream(
&self,
params: PriceStreamParams,
) -> anyhow::Result<Arc<WebsocketStream<models::PriceStreamResponse>>> {
self.market_streams_api_client.price_stream(params).await
}
/// Quote Stream
///
/// Per-symbol real-time best-bid / best-ask. Each symbol has its own stream. Per-symbol throttle: at most one push per symbol every 200 ms. Also reachable via the SUBSCRIBE/UNSUBSCRIBE RPC — see [Subscribing via RPC](https://developers.binance.com/en/docs/products/stocks/websocket-streams-general-info#subscribing-via-rpc).
///
/// # Arguments
///
/// - `params`: [`QuoteStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::QuoteStreamResponse>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-stocks-trading/api/ws-streams/market-streams#quote-stream).
///
pub async fn quote_stream(
&self,
params: QuoteStreamParams,
) -> anyhow::Result<Arc<WebsocketStream<models::QuoteStreamResponse>>> {
self.market_streams_api_client.quote_stream(params).await
}
/// Tradability Stream
///
/// Per-symbol push whenever the tradable direction of a symbol changes. Pushed only when the value actually changes (new value ≠ old value). Also reachable via the SUBSCRIBE/UNSUBSCRIBE RPC — see [Subscribing via RPC](https://developers.binance.com/en/docs/products/stocks/websocket-streams-general-info#subscribing-via-rpc).
///
/// # Arguments
///
/// - `params`: [`TradabilityStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::TradabilityStreamResponse>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-stocks-trading/api/ws-streams/market-streams#tradability-stream).
///
pub async fn tradability_stream(
&self,
params: TradabilityStreamParams,
) -> anyhow::Result<Arc<WebsocketStream<models::TradabilityStreamResponse>>> {
self.market_streams_api_client
.tradability_stream(params)
.await
}
/// Trading Status Stream
///
/// Per-symbol trading-status transitions (halts, resumes, SSR, LULD pauses, etc.). Events that do not match a known status/reason rule are not pushed. Also reachable via the SUBSCRIBE/UNSUBSCRIBE RPC — see [Subscribing via RPC](https://developers.binance.com/en/docs/products/stocks/websocket-streams-general-info#subscribing-via-rpc).
///
/// # Arguments
///
/// - `params`: [`TradingStatusStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::TradingStatusStreamResponse>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-stocks-trading/api/ws-streams/market-streams#trading-status-stream).
///
pub async fn trading_status_stream(
&self,
params: TradingStatusStreamParams,
) -> anyhow::Result<Arc<WebsocketStream<models::TradingStatusStreamResponse>>> {
self.market_streams_api_client
.trading_status_stream(params)
.await
}
/// Order Report Stream
///
/// Real-time push of the authenticated user's order state transitions — both open-state updates (`ORDER_UPDATE`) and terminal-state notifications (`ORDER_TERMINAL`). Prerequisite: obtain a `listenKey` via the Listen Key endpoint first.
///
/// # Arguments
///
/// - `params`: [`OrderReportStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::OrderReportStreamResponse>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the stream request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/en/docs/catalog/advanced-trading-stocks-trading/api/ws-streams/user-streams#order-report-stream).
///
pub async fn order_report_stream(
&self,
params: OrderReportStreamParams,
) -> anyhow::Result<Arc<WebsocketStream<models::OrderReportStreamResponse>>> {
self.user_streams_api_client
.order_report_stream(params)
.await
}
}