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
use std::sync::atomic::{AtomicBool, Ordering};
use futures::StreamExt;
use serde_json::from_str;
use tokio::net::TcpStream;
use tokio_tungstenite::tungstenite::handshake::client::Response;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::{connect_async, MaybeTlsStream};
use url::Url;
use crate::config::Config;
use crate::errors::*;
pub static STREAM_ENDPOINT: &str = "stream";
pub static WS_ENDPOINT: &str = "ws";
pub static OUTBOUND_ACCOUNT_INFO: &str = "outboundAccountInfo";
pub static OUTBOUND_ACCOUNT_POSITION: &str = "outboundAccountPosition";
pub static EXECUTION_REPORT: &str = "executionReport";
pub static KLINE: &str = "kline";
pub static AGGREGATED_TRADE: &str = "aggTrade";
pub static DEPTH_ORDERBOOK: &str = "depthUpdate";
pub static PARTIAL_ORDERBOOK: &str = "lastUpdateId";
pub static DAYTICKER: &str = "24hrTicker";
pub fn all_ticker_stream() -> &'static str { "!ticker@arr" }
pub fn ticker_stream(symbol: &str) -> String { format!("{}@ticker", symbol) }
pub fn agg_trade_stream(symbol: &str) -> String { format!("{}@aggTrade", symbol) }
pub fn trade_stream(symbol: &str) -> String { format!("{}@trade", symbol) }
pub fn kline_stream(symbol: &str, interval: &str) -> String { format!("{}@kline_{}", symbol, interval) }
pub fn book_ticker_stream(symbol: &str) -> String { format!("{}@bookTicker", symbol) }
pub fn all_book_ticker_stream() -> &'static str { "!bookTicker" }
pub fn all_mini_ticker_stream() -> &'static str { "!miniTicker@arr" }
pub fn mini_ticker_stream(symbol: &str) -> String { format!("{}@miniTicker", symbol) }
pub fn partial_book_depth_stream(symbol: &str, levels: u16, update_speed: u16) -> String {
format!("{}@depth{}@{}ms", symbol, levels, update_speed)
}
pub fn diff_book_depth_stream(symbol: &str, update_speed: u16) -> String {
format!("{}@depth@{}ms", symbol, update_speed)
}
fn combined_stream(streams: Vec<String>) -> String { streams.join("/") }
pub struct WebSockets<'a, WE> {
pub socket: Option<(WebSocketStream<MaybeTlsStream<TcpStream>>, Response)>,
handler: Box<dyn FnMut(WE) -> Result<()> + 'a>,
conf: Config,
}
impl<'a, WE: serde::de::DeserializeOwned> WebSockets<'a, WE> {
pub fn new<Callback>(handler: Callback) -> WebSockets<'a, WE>
where
Callback: FnMut(WE) -> Result<()> + 'a,
{
Self::new_with_options(handler, Config::default())
}
pub fn new_with_options<Callback>(handler: Callback, conf: Config) -> WebSockets<'a, WE>
where
Callback: FnMut(WE) -> Result<()> + 'a,
{
WebSockets {
socket: None,
handler: Box::new(handler),
conf,
}
}
pub async fn connect_multiple(&mut self, endpoints: Vec<String>) -> Result<()> {
let mut url = Url::parse(&self.conf.ws_endpoint)?;
url.path_segments_mut()
.map_err(|_| Error::UrlParserError(url::ParseError::RelativeUrlWithoutBase))?
.push(STREAM_ENDPOINT);
url.set_query(Some(&format!("streams={}", combined_stream(endpoints))));
match connect_async(url).await {
Ok(answer) => {
self.socket = Some(answer);
Ok(())
}
Err(e) => Err(Error::Msg(format!("Error during handshake {}", e))),
}
}
pub async fn connect(&mut self, endpoint: &str) -> Result<()> {
let wss: String = format!("{}/{}/{}", self.conf.ws_endpoint, WS_ENDPOINT, endpoint);
let url = Url::parse(&wss)?;
match connect_async(url).await {
Ok(answer) => {
self.socket = Some(answer);
Ok(())
}
Err(e) => Err(Error::Msg(format!("Error during handshake {}", e))),
}
}
pub async fn disconnect(&mut self) -> Result<()> {
if let Some(ref mut socket) = self.socket {
socket.0.close(None).await?;
Ok(())
} else {
Err(Error::Msg("Not able to close the connection".to_string()))
}
}
pub fn socket(&self) -> &Option<(WebSocketStream<MaybeTlsStream<TcpStream>>, Response)> { &self.socket }
pub async fn event_loop(&mut self, running: &AtomicBool) -> Result<()> {
while running.load(Ordering::Relaxed) {
if let Some((ref mut socket, _)) = self.socket {
let message = socket.next().await.unwrap()?;
match message {
Message::Text(msg) => {
if msg.is_empty() {
return Ok(());
}
let event: WE = from_str(msg.as_str())?;
(self.handler)(event)?;
}
Message::Ping(_) | Message::Pong(_) | Message::Binary(_) => {}
Message::Close(e) => {
return Err(Error::Msg(format!("Disconnected {:?}", e)));
}
}
}
}
Ok(())
}
}