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
use std::{collections::HashMap, num::NonZeroU32};

use async_trait::async_trait;
use nonzero_ext::nonzero;
use serde_json::Value;
use tokio_tungstenite::tungstenite::Message;

use crate::{
    clients::common_traits::{
        Candlestick, Level3OrderBook, OrderBook, OrderBookTopK, Ticker, Trade, BBO,
    },
    common::{
        command_translator::CommandTranslator,
        message_handler::{MessageHandler, MiscMessage},
        ws_client_internal::WSClientInternal,
    },
    WSClient,
};
use log::*;

use super::EXCHANGE_NAME;

const WEBSOCKET_URL: &str = "wss://fapi.zb.com/ws/public/v1";

// The default limit for the number of requests for a single interface is 200
// times/2s
//
// See https://github.com/ZBFuture/docs/blob/main/API%20V2%20_en.md#14-access-limit-frequency-rules
const UPLINK_LIMIT: (NonZeroU32, std::time::Duration) =
    (nonzero!(200u32), std::time::Duration::from_secs(2));

/// The WebSocket client for ZB swap market.
///
/// * WebSocket API doc: <https://github.com/ZBFuture/docs/blob/main/API%20V2%20_en.md>
/// * Trading at: <https://www.zb.com/en/futures/btc_usdt>
pub struct ZbSwapWSClient {
    client: WSClientInternal<ZbMessageHandler>,
    translator: ZbCommandTranslator,
}

impl ZbSwapWSClient {
    pub async fn new(tx: std::sync::mpsc::Sender<String>, url: Option<&str>) -> Self {
        let real_url = match url {
            Some(endpoint) => endpoint,
            None => WEBSOCKET_URL,
        };
        ZbSwapWSClient {
            client: WSClientInternal::connect(
                EXCHANGE_NAME,
                real_url,
                ZbMessageHandler {},
                Some(UPLINK_LIMIT),
                tx,
            )
            .await,
            translator: ZbCommandTranslator {},
        }
    }
}

#[rustfmt::skip]
impl_trait!(Trade, ZbSwapWSClient, subscribe_trade, "Trade");
#[rustfmt::skip]
impl_trait!(OrderBook, ZbSwapWSClient, subscribe_orderbook, "Depth");
#[rustfmt::skip]
impl_trait!(OrderBookTopK, ZbSwapWSClient, subscribe_orderbook_topk, "DepthWhole");
#[rustfmt::skip]
impl_trait!(Ticker, ZbSwapWSClient, subscribe_ticker, "Ticker");
impl_candlestick!(ZbSwapWSClient);

panic_bbo!(ZbSwapWSClient);
panic_l3_orderbook!(ZbSwapWSClient);

impl_ws_client_trait!(ZbSwapWSClient);

struct ZbMessageHandler {}
struct ZbCommandTranslator {}

impl MessageHandler for ZbMessageHandler {
    fn handle_message(&mut self, msg: &str) -> MiscMessage {
        if msg == r#"{"action":"pong"}"# {
            return MiscMessage::Pong;
        }
        if msg.contains("error") {
            error!("Received {} from {}", msg, EXCHANGE_NAME);
            return MiscMessage::Other;
        }
        let obj = serde_json::from_str::<HashMap<String, Value>>(msg).unwrap();
        if obj.contains_key("channel") && obj.contains_key("data") {
            MiscMessage::Normal
        } else {
            warn!("Received {} from {}", msg, EXCHANGE_NAME);
            MiscMessage::Other
        }
    }

    fn get_ping_msg_and_interval(&self) -> Option<(Message, u64)> {
        // https://github.com/ZBFuture/docs/blob/main/API%20V2%20_en.md#812-ping
        Some((Message::Text(r#"{"action":"ping"}"#.to_string()), 10))
    }
}

impl ZbCommandTranslator {
    fn to_candlestick_raw_channel(&self, symbol: &str, interval: usize) -> String {
        let interval_str = match interval {
            60 => "1M",
            300 => "5M",
            900 => "15M",
            1800 => "30M",
            3600 => "1H",
            21600 => "6H",
            86400 => "1D",
            432000 => "5D",
            _ => panic!("ZB swap available intervals: 1M,5M,15M, 30M, 1H, 6H, 1D, 5D"),
        };
        format!("{symbol}.KLine_{interval_str}",)
    }
}

impl CommandTranslator for ZbCommandTranslator {
    fn translate_to_commands(&self, subscribe: bool, topics: &[(String, String)]) -> Vec<String> {
        let action = if subscribe { "subscribe" } else { "unsubscribe" };
        topics
            .iter()
            .map(|(channel, symbol)| match channel.as_str() {
                "Trade" => format!(
                    r#"{{"action":"{action}", "channel":"{symbol}.{channel}", "size":100}}"#,
                ),
                "Depth" => format!(
                    r#"{{"action":"{action}", "channel":"{symbol}.{channel}", "size":200}}"#,
                ),
                "DepthWhole" => format!(
                    r#"{{"action":"{action}", "channel":"{symbol}.{channel}", "size":10}}"#,
                ),
                "Ticker" => {
                    format!(r#"{{"action":"{action}", "channel":"{symbol}.{channel}"}}"#,)
                }
                _ => panic!("Unknown ZB channel {channel}"),
            })
            .collect()
    }

    fn translate_to_candlestick_commands(
        &self,
        subscribe: bool,
        symbol_interval_list: &[(String, usize)],
    ) -> Vec<String> {
        let action = if subscribe { "subscribe" } else { "unsubscribe" };
        symbol_interval_list
            .iter()
            .map(|(symbol, interval)| {
                format!(
                    r#"{{"action":"{}", "channel":"{}", "size":1}}"#,
                    action,
                    self.to_candlestick_raw_channel(symbol, *interval),
                )
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use crate::common::command_translator::CommandTranslator;

    #[tokio::test(flavor = "multi_thread")]
    async fn test_one_topic() {
        let translator = super::ZbCommandTranslator {};
        let commands = translator
            .translate_to_commands(true, &[("Trade".to_string(), "BTC_USDT".to_string())]);

        assert_eq!(1, commands.len());
        assert_eq!(
            r#"{"action":"subscribe", "channel":"BTC_USDT.Trade", "size":100}"#,
            commands[0]
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_two_topic() {
        let translator = super::ZbCommandTranslator {};
        let commands = translator.translate_to_commands(
            true,
            &[
                ("Trade".to_string(), "BTC_USDT".to_string()),
                ("Depth".to_string(), "ETH_USDT".to_string()),
            ],
        );

        assert_eq!(2, commands.len());
        assert_eq!(
            r#"{"action":"subscribe", "channel":"BTC_USDT.Trade", "size":100}"#,
            commands[0]
        );
        assert_eq!(
            r#"{"action":"subscribe", "channel":"ETH_USDT.Depth", "size":200}"#,
            commands[1]
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_candlestick() {
        let translator = super::ZbCommandTranslator {};
        let commands =
            translator.translate_to_candlestick_commands(true, &[("BTC_USDT".to_string(), 60)]);

        assert_eq!(1, commands.len());
        assert_eq!(
            r#"{"action":"subscribe", "channel":"BTC_USDT.KLine_1M", "size":1}"#,
            commands[0]
        );
    }
}