/*
* Prediction Trading Streams
*
* Binance Web3 Prediction pushes 14 kinds of real-time events over the Binance SApi WebSocket channel, covering market and limit trading, reward claims, fund transfers and market resolution, plus order book (bid/ask) quotes per market. Trading events go only to the user they belong to; order book quotes go to everyone subscribed. A message may occasionally be missed, order is not guaranteed, and nothing is stored while you are offline — after reconnecting, fetch the latest state from the REST API and drop duplicates using `pushId` (business events) or `marketId` + `updateTimestampMs` (order book).
*
* 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>,
api_client: ApiClient,
}
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
.signed_streams
.store(true, Ordering::Relaxed);
websocket_streams_base.clone().connect(streams).await?;
Ok(Self {
websocket_streams_base: websocket_streams_base.clone(),
api_client: ApiClient::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
}
/// Batch claim partially succeeded
///
/// Pushed when only part of a batch claim succeeds. Only `pushId` is included — call the REST
/// API for details.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`BatchClaimPartiallySucceededParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::BatchClaimPartiallySucceededResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#batch-claim-partially-succeeded).
///
pub async fn batch_claim_partially_succeeded(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::BatchClaimPartiallySucceededResponse>>> {
self.api_client.batch_claim_partially_succeeded().await
}
/// Fund transfer failed
///
/// Pushed when a fund transfer fails.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`FundTransferFailedParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::FundTransferFailedResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#fund-transfer-failed).
///
pub async fn fund_transfer_failed(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::FundTransferFailedResponse>>> {
self.api_client.fund_transfer_failed().await
}
/// Fund transfer succeeded
///
/// Pushed when a fund transfer into or out of the prediction wallet succeeds. The direction and
/// the token are not included (currently USDT only).
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`FundTransferSucceededParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::FundTransferSucceededResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#fund-transfer-succeeded).
///
pub async fn fund_transfer_succeeded(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::FundTransferSucceededResponse>>> {
self.api_client.fund_transfer_succeeded().await
}
/// Limit order fully filled
///
/// Pushed when a **limit order** is fully filled.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`LimitOrderFullyFilledParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::LimitOrderFullyFilledResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#limit-order-fully-filled).
///
pub async fn limit_order_fully_filled(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::LimitOrderFullyFilledResponse>>> {
self.api_client.limit_order_fully_filled().await
}
/// Limit order partially filled
///
/// Pushed on each new partial fill of a **limit order**. One order can be pushed several times,
/// so always remove duplicates by `pushId`.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`LimitOrderPartiallyFilledParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::LimitOrderPartiallyFilledResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#limit-order-partially-filled).
///
pub async fn limit_order_partially_filled(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::LimitOrderPartiallyFilledResponse>>> {
self.api_client.limit_order_partially_filled().await
}
/// Limit order submission failed
///
/// Pushed when a **limit order** is rejected when placed. No `amount` is included.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`LimitOrderSubmissionFailedParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::LimitOrderSubmissionFailedResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#limit-order-submission-failed).
///
pub async fn limit_order_submission_failed(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::LimitOrderSubmissionFailedResponse>>> {
self.api_client.limit_order_submission_failed().await
}
/// Limit order submitted successfully
///
/// Pushed when the user's **limit order** is successfully placed on the order book.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`LimitOrderSubmittedSuccessfullyParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::LimitOrderSubmittedSuccessfullyResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#limit-order-submitted-successfully).
///
pub async fn limit_order_submitted_successfully(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::LimitOrderSubmittedSuccessfullyResponse>>> {
self.api_client.limit_order_submitted_successfully().await
}
/// Market buy order failed / expired
///
/// Pushed when the user's **market buy order** fails or expires.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`MarketBuyOrderFailedParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::MarketBuyOrderFailedResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#market-buy-order-failed).
///
pub async fn market_buy_order_failed(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::MarketBuyOrderFailedResponse>>> {
self.api_client.market_buy_order_failed().await
}
/// Market buy order fully filled
///
/// Pushed when the user's **market buy order** is fully filled.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`MarketBuyOrderFullyFilledParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::MarketBuyOrderFullyFilledResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#market-buy-order-fully-filled).
///
pub async fn market_buy_order_fully_filled(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::MarketBuyOrderFullyFilledResponse>>> {
self.api_client.market_buy_order_fully_filled().await
}
/// Market resolution notification
///
/// Pushed when a market is resolved, to every user holding a position in it, win or lose. No
/// amount or outcome is included — call the REST API for the user's profit and loss.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`MarketResolutionNotificationParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::MarketResolutionNotificationResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#market-resolution-notification).
///
pub async fn market_resolution_notification(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::MarketResolutionNotificationResponse>>> {
self.api_client.market_resolution_notification().await
}
/// Market sell order failed / expired
///
/// Pushed when the user's **market sell order** fails or expires.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`MarketSellOrderFailedExpiredParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::MarketSellOrderFailedExpiredResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#market-sell-order-failed-expired).
///
pub async fn market_sell_order_failed_expired(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::MarketSellOrderFailedExpiredResponse>>> {
self.api_client.market_sell_order_failed_expired().await
}
/// Market sell order fully filled
///
/// Pushed when the user's **market sell order** is fully filled.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`MarketSellOrderFullyFilledParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::MarketSellOrderFullyFilledResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#market-sell-order-fully-filled).
///
pub async fn market_sell_order_fully_filled(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::MarketSellOrderFullyFilledResponse>>> {
self.api_client.market_sell_order_fully_filled().await
}
/// Prediction Order Book by marketId
///
/// Order book (bid/ask) updates for one market. Only active markets are pushed.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`PredictionOrderBookByMarketIdParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::PredictionOrderBookByMarketIdResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#prediction-order-book-by-market-id).
///
pub async fn prediction_order_book_by_market_id(
&self,
params: PredictionOrderBookByMarketIdParams,
) -> anyhow::Result<Arc<WebsocketStream<models::PredictionOrderBookByMarketIdResponse>>> {
self.api_client
.prediction_order_book_by_market_id(params)
.await
}
/// Reward claim failed
///
/// Pushed when a claim fails completely — a single claim, or every item of a batch. For a batch,
/// only the first failed item's amount and outcome are included.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`RewardClaimFailedParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::RewardClaimFailedResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#reward-claim-failed).
///
pub async fn reward_claim_failed(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::RewardClaimFailedResponse>>> {
self.api_client.reward_claim_failed().await
}
/// Reward claim succeeded
///
/// Pushed when a claim fully succeeds — a single claim, or every item of a batch. Only the total
/// is reported; no market title or outcome is included.
///
/// Update Speed: Real-time
///
/// # Arguments
///
/// - `params`: [`RewardClaimSucceededParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`Arc<WebsocketStream<models::RewardClaimSucceededResponse>>`] 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/web3-wallet-prediction-trading/api/ws-streams/~#reward-claim-succeeded).
///
pub async fn reward_claim_succeeded(
&self,
) -> anyhow::Result<Arc<WebsocketStream<models::RewardClaimSucceededResponse>>> {
self.api_client.reward_claim_succeeded().await
}
}