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
use async_trait::async_trait;
use nonzero_ext::nonzero;
use std::{collections::HashMap, num::NonZeroU32};
use tokio_tungstenite::tungstenite::Message;
use crate::{
common::{
command_translator::CommandTranslator,
message_handler::{MessageHandler, MiscMessage},
utils::ensure_frame_size,
ws_client_internal::WSClientInternal,
},
WSClient,
};
use log::*;
use serde_json::Value;
pub(crate) const EXCHANGE_NAME: &str = "binance";
const SPOT_WEBSOCKET_URL: &str = "wss://stream.binance.com:9443/stream";
const LINEAR_WEBSOCKET_URL: &str = "wss://fstream.binance.com/stream";
const INVERSE_WEBSOCKET_URL: &str = "wss://dstream.binance.com/stream";
const WS_FRAME_SIZE: usize = 4096;
const UPLINK_LIMIT: (NonZeroU32, std::time::Duration) =
(nonzero!(5u32), std::time::Duration::from_secs(1));
pub struct BinanceWSClient<const MARKET_TYPE: char> {
client: WSClientInternal<BinanceMessageHandler>,
translator: BinanceCommandTranslator,
}
pub type BinanceSpotWSClient = BinanceWSClient<'S'>;
pub type BinanceInverseWSClient = BinanceWSClient<'I'>;
pub type BinanceLinearWSClient = BinanceWSClient<'L'>;
impl<const MARKET_TYPE: char> BinanceWSClient<MARKET_TYPE> {
pub async fn new(tx: std::sync::mpsc::Sender<String>, url: Option<&str>) -> Self {
let real_url = match url {
Some(endpoint) => endpoint,
None => {
if MARKET_TYPE == 'S' {
SPOT_WEBSOCKET_URL
} else if MARKET_TYPE == 'I' {
INVERSE_WEBSOCKET_URL
} else if MARKET_TYPE == 'L' {
LINEAR_WEBSOCKET_URL
} else {
panic!("Unknown market type {MARKET_TYPE}");
}
}
};
BinanceWSClient {
client: WSClientInternal::connect(
EXCHANGE_NAME,
real_url,
BinanceMessageHandler {},
Some(UPLINK_LIMIT),
tx,
)
.await,
translator: BinanceCommandTranslator { market_type: MARKET_TYPE },
}
}
}
#[async_trait]
impl<const URL: char> WSClient for BinanceWSClient<URL> {
async fn subscribe_trade(&self, symbols: &[String]) {
let topics = symbols
.iter()
.map(|symbol| ("aggTrade".to_string(), symbol.to_string()))
.collect::<Vec<(String, String)>>();
self.subscribe(&topics).await;
}
async fn subscribe_orderbook(&self, symbols: &[String]) {
let topics = symbols
.iter()
.map(|symbol| ("depth@100ms".to_string(), symbol.to_string()))
.collect::<Vec<(String, String)>>();
self.subscribe(&topics).await;
}
async fn subscribe_orderbook_topk(&self, symbols: &[String]) {
let topics = symbols
.iter()
.map(|symbol| ("depth20".to_string(), symbol.to_string()))
.collect::<Vec<(String, String)>>();
self.subscribe(&topics).await;
}
async fn subscribe_l3_orderbook(&self, _symbols: &[String]) {
panic!("{EXCHANGE_NAME} does NOT have the level3 websocket channel");
}
async fn subscribe_ticker(&self, symbols: &[String]) {
let topics = symbols
.iter()
.map(|symbol| ("ticker".to_string(), symbol.to_string()))
.collect::<Vec<(String, String)>>();
self.subscribe(&topics).await;
}
async fn subscribe_bbo(&self, symbols: &[String]) {
let topics = symbols
.iter()
.map(|symbol| ("bookTicker".to_string(), symbol.to_string()))
.collect::<Vec<(String, String)>>();
self.subscribe(&topics).await;
}
async fn subscribe_candlestick(&self, symbol_interval_list: &[(String, usize)]) {
let commands =
self.translator.translate_to_candlestick_commands(true, symbol_interval_list);
self.client.send(&commands).await;
}
async fn subscribe(&self, topics: &[(String, String)]) {
let commands = self.translator.translate_to_commands(true, topics);
self.client.send(&commands).await;
}
async fn unsubscribe(&self, topics: &[(String, String)]) {
let commands = self.translator.translate_to_commands(false, topics);
self.client.send(&commands).await;
}
async fn send(&self, commands: &[String]) {
self.client.send(commands).await;
}
async fn run(&self) {
self.client.run().await;
}
async fn close(&self) {
self.client.close().await;
}
}
struct BinanceMessageHandler {}
struct BinanceCommandTranslator {
market_type: char,
}
impl BinanceCommandTranslator {
fn topics_to_command(topics: &[(String, String)], subscribe: bool) -> String {
let raw_topics = topics
.iter()
.map(|(topic, symbol)| format!("{}@{}", symbol.to_lowercase(), topic))
.collect::<Vec<String>>();
format!(
r#"{{"id":9527,"method":"{}","params":{}}}"#,
if subscribe { "SUBSCRIBE" } else { "UNSUBSCRIBE" },
serde_json::to_string(&raw_topics).unwrap()
)
}
fn to_candlestick_raw_channel(interval: usize) -> String {
let interval_str = match interval {
60 => "1m",
180 => "3m",
300 => "5m",
900 => "15m",
1800 => "30m",
3600 => "1h",
7200 => "2h",
14400 => "4h",
21600 => "6h",
28800 => "8h",
43200 => "12h",
86400 => "1d",
259200 => "3d",
604800 => "1w",
2592000 => "1M",
_ => panic!("Binance has intervals 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M"),
};
format!("kline_{interval_str}")
}
}
impl MessageHandler for BinanceMessageHandler {
fn handle_message(&mut self, msg: &str) -> MiscMessage {
let resp = serde_json::from_str::<HashMap<String, Value>>(msg);
if resp.is_err() {
error!("{} is not a JSON string, {}", msg, EXCHANGE_NAME);
return MiscMessage::Other;
}
let obj = resp.unwrap();
if obj.contains_key("error") {
panic!("Received {msg} from {EXCHANGE_NAME}");
} else if obj.contains_key("stream") && obj.contains_key("data") {
MiscMessage::Normal
} else {
if let Some(result) = obj.get("result") {
if serde_json::Value::Null != *result {
panic!("Received {msg} from {EXCHANGE_NAME}");
} else {
info!("Received {} from {}", msg, EXCHANGE_NAME);
}
} else {
warn!("Received {} from {}", msg, EXCHANGE_NAME);
}
MiscMessage::Other
}
}
fn get_ping_msg_and_interval(&self) -> Option<(Message, u64)> {
Some((Message::Pong(Vec::new()), 180))
}
}
impl CommandTranslator for BinanceCommandTranslator {
fn translate_to_commands(&self, subscribe: bool, topics: &[(String, String)]) -> Vec<String> {
let max_num_topics = if self.market_type == 'S' {
1024
} else {
200
};
ensure_frame_size(
topics,
subscribe,
Self::topics_to_command,
WS_FRAME_SIZE,
Some(max_num_topics),
)
}
fn translate_to_candlestick_commands(
&self,
subscribe: bool,
symbol_interval_list: &[(String, usize)],
) -> Vec<String> {
let topics = symbol_interval_list
.iter()
.map(|(symbol, interval)| {
let channel = Self::to_candlestick_raw_channel(*interval);
(channel, symbol.to_lowercase())
})
.collect::<Vec<(String, String)>>();
self.translate_to_commands(subscribe, &topics)
}
}
#[cfg(test)]
mod tests {
use crate::common::command_translator::CommandTranslator;
#[test]
fn test_one_topic() {
let translator = super::BinanceCommandTranslator { market_type: 'S' };
let commands = translator
.translate_to_commands(true, &[("aggTrade".to_string(), "BTCUSDT".to_string())]);
assert_eq!(1, commands.len());
assert_eq!(
r#"{"id":9527,"method":"SUBSCRIBE","params":["btcusdt@aggTrade"]}"#,
commands[0]
);
}
#[test]
fn test_two_topics() {
let translator = super::BinanceCommandTranslator { market_type: 'S' };
let commands = translator.translate_to_commands(
true,
&[
("aggTrade".to_string(), "BTCUSDT".to_string()),
("ticker".to_string(), "BTCUSDT".to_string()),
],
);
assert_eq!(1, commands.len());
assert_eq!(
r#"{"id":9527,"method":"SUBSCRIBE","params":["btcusdt@aggTrade","btcusdt@ticker"]}"#,
commands[0]
);
}
}