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
use crate::WSClient;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use super::super::ws_client_internal::{MiscMessage, WSClientInternal};
use super::super::{Candlestick, OrderBook, OrderBookSnapshot, Ticker, Trade, BBO};
use super::utils::fetch_symbol_id_map_spot;

use lazy_static::lazy_static;
use log::*;

const EXCHANGE_NAME: &str = "zbg";

const WEBSOCKET_URL: &str = "wss://kline.zbg.com/websocket";

const PING_INTERVAL_AND_MSG: (u64, &str) = (10, r#"{"action":"PING"}"#);

lazy_static! {
    static ref SYMBOL_ID_MAP: HashMap<String, String> = fetch_symbol_id_map_spot();
}

/// The WebSocket client for ZBG spot market.
///
/// * WebSocket API doc: <https://zbgapi.github.io/docs/spot/v1/en/#websocket-market-data>
/// * Trading at: <https://www.zbg.com/trade/>
pub struct ZbgSpotWSClient<'a> {
    client: WSClientInternal<'a>,
}

fn channel_to_command(channel: &str, subscribe: bool) -> String {
    if channel.starts_with('{') {
        channel.to_string()
    } else {
        format!(
            r#"{{"action":"{}", "dataType":{}}}"#,
            if subscribe { "ADD" } else { "DEL" },
            channel,
        )
    }
}

fn channels_to_commands(channels: &[String], subscribe: bool) -> Vec<String> {
    channels
        .iter()
        .map(|ch| channel_to_command(ch, subscribe))
        .collect()
}

fn on_misc_msg(msg: &str) -> MiscMessage {
    if msg.contains(r#"action":"PING"#) {
        debug!("Received {} from {}", msg, EXCHANGE_NAME);
        MiscMessage::Misc
    } else {
        MiscMessage::Normal
    }
}

fn to_raw_channel(channel: &str, pair: &str) -> String {
    let symbol_id = SYMBOL_ID_MAP
        .get(pair)
        .unwrap_or_else(|| panic!("Failed to find symbol_id for {}", pair));
    if channel == "TRADE_STATISTIC_24H" {
        format!("{}_{}", symbol_id, channel)
    } else {
        format!("{}_{}_{}", symbol_id, channel, pair.to_uppercase())
    }
}

#[rustfmt::skip]
impl_trait!(Trade, ZbgSpotWSClient, subscribe_trade, "TRADE", to_raw_channel);
#[rustfmt::skip]
impl_trait!(OrderBook, ZbgSpotWSClient, subscribe_orderbook, "ENTRUST_ADD", to_raw_channel);
#[rustfmt::skip]
impl_trait!(Ticker, ZbgSpotWSClient, subscribe_ticker, "TRADE_STATISTIC_24H", to_raw_channel);

impl<'a> BBO for ZbgSpotWSClient<'a> {
    fn subscribe_bbo(&self, _pairs: &[String]) {
        panic!("ZBG does NOT have BBO channel");
    }
}

impl<'a> OrderBookSnapshot for ZbgSpotWSClient<'a> {
    fn subscribe_orderbook_snapshot(&self, _pairs: &[String]) {
        panic!("Bitget does NOT have orderbook snapshot channel");
    }
}

fn to_candlestick_raw_channel(pair: &str, interval: u32) -> String {
    let interval_str = match interval {
        60 => "1M",
        300 => "5M",
        900 => "15M",
        1800 => "30M",
        3600 => "1H",
        14400 => "4H",
        86400 => "1D",
        604800 => "1W",
        _ => panic!("ZBG spot available intervals 1M,5M,15M,30M,1H,4H,1D,1W"),
    };

    let symbol_id = SYMBOL_ID_MAP
        .get(pair)
        .unwrap_or_else(|| panic!("Failed to find symbol_id for {}", pair));

    format!(
        "{}_KLINE_{}_{}",
        symbol_id,
        interval_str,
        pair.to_uppercase()
    )
}

impl_candlestick!(ZbgSpotWSClient);

define_client!(
    ZbgSpotWSClient,
    EXCHANGE_NAME,
    WEBSOCKET_URL,
    channels_to_commands,
    on_misc_msg,
    Some(PING_INTERVAL_AND_MSG)
);