binance_api_async/
userstream.rs

1use serde_json::from_str;
2use uuid::Uuid;
3
4use crate::client::*;
5use crate::error::*;
6use crate::model::*;
7use crate::websocket::*;
8
9static USER_DATA_STREAM: &str = "/api/v3/userDataStream";
10
11
12pub struct UserStream {
13    pub client: Client,
14    pub recv_window: u64,
15    pub ws: Option<Websocket>,
16}
17
18#[async_trait::async_trait]
19pub trait UserStreamAsync {
20    async fn subscribe(&mut self) -> Result<Uuid, BinanceErr>;
21    fn unsubscribe(&mut self, uuid: Uuid) -> Option<StoredStream>;
22}
23
24#[async_trait::async_trait]
25impl UserStreamAsync for UserStream {
26    async fn subscribe(&mut self) -> Result<Uuid, BinanceErr> {
27        match self.start().await? {
28            UserDataStream { listen_key } => {
29                let mut ws = Websocket::new();
30                let id = ws.subscribe(WebsocketStreamType::UserStream(listen_key)).await?;
31                self.ws = Some(ws);
32                Ok(id)
33            }
34        }
35    }
36
37    fn unsubscribe(&mut self, uuid: Uuid) -> Option<StoredStream> {
38        if let Some(ws) = &mut self.ws {
39            ws.unsubscribe(uuid)
40        } else {
41            None
42        }
43    }
44}
45
46impl UserStream {
47    pub async fn start(&self) -> Result<UserDataStream, BinanceErr> {
48        let data = self.client.post(USER_DATA_STREAM).await?;
49        let user_data_stream: UserDataStream = from_str(data.as_str())?;
50        Ok(user_data_stream)
51    }
52
53    pub async fn keep_alive(&self, listen_key: &str) -> Result<Success, BinanceErr> {
54        let data = self.client.put(USER_DATA_STREAM, listen_key).await?;
55        let success: Success = from_str(data.as_str())?;
56        Ok(success)
57    }
58
59    pub async fn close(&self, listen_key: &str) -> Result<Success, BinanceErr> {
60        let data = self.client.delete(USER_DATA_STREAM, listen_key).await?;
61        let success: Success = from_str(data.as_str())?;
62        Ok(success)
63    }
64}