crypto-msg-parser 2.9.2

Parse websocket messages from cryptocurreny exchanges
Documentation
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use crypto_market_type::MarketType;
use crypto_msg_type::MessageType;

use crypto_message::{
    BboMsg, CandlestickMsg, FundingRateMsg, Order, OrderBookMsg, TradeMsg, TradeSide,
};

use super::{super::utils::calc_quantity_and_volume, EXCHANGE_NAME};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use simple_error::SimpleError;
use std::collections::HashMap;

// see https://binance-docs.github.io/apidocs/spot/en/#aggregate-trade-streams
#[derive(Serialize, Deserialize)]
#[allow(non_snake_case)]
struct AggTradeMsg {
    e: String, // Event type
    E: i64,    // Event time
    s: String, // Symbol
    a: i64,    // Aggregate trade ID
    p: String, // Price
    q: String, // Quantity
    f: i64,    // First trade ID
    l: i64,    // Last trade ID
    T: i64,    // Trade time
    m: bool,   // Is the buyer the market maker?
    #[serde(flatten)]
    extra: HashMap<String, Value>,
}

// see https://binance-docs.github.io/apidocs/spot/en/#trade-streams
#[derive(Serialize, Deserialize)]
#[allow(non_snake_case)]
struct RawTradeMsg {
    e: String, // Event type
    E: i64,    // Event time
    s: String, // Symbol
    t: i64,    // Trade ID
    p: String, // Price
    q: String, // Quantity
    b: i64,    // Buyer order ID
    a: i64,    // Seller order ID
    T: i64,    // Trade time
    m: bool,   // Is the buyer the market maker?
    #[serde(flatten)]
    extra: HashMap<String, Value>,
}

/// price, quantity
pub type RawOrder = [String; 2];

// See:
// https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream
// https://binance-docs.github.io/apidocs/delivery/en/#diff-book-depth-streams
// https://binance-docs.github.io/apidocs/futures/en/#partial-book-depth-streams
// https://binance-docs.github.io/apidocs/delivery/en/#partial-book-depth-streams
#[derive(Serialize, Deserialize)]
#[allow(non_snake_case)]
struct RawOrderbookMsg {
    e: String,          // Event type
    E: i64,             // Event time
    T: Option<i64>,     // Transction time
    s: String,          // Symbol
    ps: Option<String>, // Pair, available to L2_TOPK
    U: u64,             // First update ID in event
    u: u64,             // Final update ID in event
    pu: Option<i64>,    /* Previous event update sequense ("u" of previous message), -1 also
                         * means None */
    b: Vec<RawOrder>,
    a: Vec<RawOrder>,
    #[serde(flatten)]
    extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize)]
struct WebsocketMsg<T: Sized> {
    stream: String,
    data: T,
}

pub(super) fn parse_trade(
    market_type: MarketType,
    msg: &str,
) -> Result<Vec<TradeMsg>, SimpleError> {
    let obj = serde_json::from_str::<HashMap<String, Value>>(msg)
        .map_err(|_e| SimpleError::new(format!("{msg} is not a JSON object")))?;
    let data = obj
        .get("data")
        .ok_or_else(|| SimpleError::new(format!("There is no data field in {msg}")))?;
    let event_type = data["e"].as_str().ok_or_else(|| {
        SimpleError::new(format!("There is no e field in the data field of {msg}"))
    })?;

    match event_type {
        "aggTrade" => {
            let agg_trade: AggTradeMsg = serde_json::from_value(data.clone()).map_err(|_e| {
                SimpleError::new(format!("Failed to deserialize {msg} to AggTradeMsg"))
            })?;
            let pair =
                crypto_pair::normalize_pair(&agg_trade.s, EXCHANGE_NAME).ok_or_else(|| {
                    SimpleError::new(format!("Failed to normalize {} from {}", agg_trade.s, msg))
                })?;
            let price = agg_trade.p.parse::<f64>().unwrap();
            let quantity = agg_trade.q.parse::<f64>().unwrap();
            let (quantity_base, quantity_quote, quantity_contract) =
                calc_quantity_and_volume(EXCHANGE_NAME, market_type, &pair, price, quantity);
            let trade = TradeMsg {
                exchange: EXCHANGE_NAME.to_string(),
                market_type,
                symbol: agg_trade.s.clone(),
                pair,
                msg_type: MessageType::Trade,
                timestamp: agg_trade.E,
                price,
                quantity_base,
                quantity_quote,
                quantity_contract,
                side: if agg_trade.m { TradeSide::Sell } else { TradeSide::Buy },
                trade_id: agg_trade.a.to_string(),
                json: msg.to_string(),
            };

            Ok(vec![trade])
        }
        "trade" => {
            let raw_trade: RawTradeMsg = serde_json::from_value(data.clone()).map_err(|_e| {
                SimpleError::new(format!("Failed to deserialize {data} to RawTradeMsg"))
            })?;
            let pair =
                crypto_pair::normalize_pair(&raw_trade.s, EXCHANGE_NAME).ok_or_else(|| {
                    SimpleError::new(format!("Failed to normalize {} from {}", raw_trade.s, msg))
                })?;
            let price = raw_trade.p.parse::<f64>().unwrap();
            let quantity = raw_trade.q.parse::<f64>().unwrap();
            let (quantity_base, quantity_quote, quantity_contract) =
                calc_quantity_and_volume(EXCHANGE_NAME, market_type, &pair, price, quantity);
            let trade = TradeMsg {
                exchange: EXCHANGE_NAME.to_string(),
                market_type,
                symbol: raw_trade.s.clone(),
                pair,
                msg_type: MessageType::Trade,
                timestamp: raw_trade.E,
                price,
                quantity_base,
                quantity_quote,
                quantity_contract,
                side: if raw_trade.m { TradeSide::Sell } else { TradeSide::Buy },
                trade_id: raw_trade.t.to_string(),
                json: msg.to_string(),
            };

            Ok(vec![trade])
        }
        _ => Err(SimpleError::new(format!("Unsupported event type {event_type}"))),
    }
}

pub(super) fn parse_l2(
    market_type: MarketType,
    msg: &str,
) -> Result<Vec<OrderBookMsg>, SimpleError> {
    let ws_msg =
        serde_json::from_str::<WebsocketMsg<RawOrderbookMsg>>(msg).map_err(SimpleError::from)?;
    let pair = crypto_pair::normalize_pair(&ws_msg.data.s, EXCHANGE_NAME).ok_or_else(|| {
        SimpleError::new(format!("Failed to normalize {} from {}", ws_msg.data.s, msg))
    })?;

    let parse_order = |raw_order: &RawOrder| -> Order {
        let price = raw_order[0].parse::<f64>().unwrap();
        let (quantity_base, quantity_quote, quantity_contract) = calc_quantity_and_volume(
            EXCHANGE_NAME,
            market_type,
            &pair,
            price,
            raw_order[1].parse::<f64>().unwrap(),
        );
        Order { price, quantity_base, quantity_quote, quantity_contract }
    };

    let orderbook = OrderBookMsg {
        exchange: EXCHANGE_NAME.to_string(),
        market_type,
        symbol: ws_msg.data.s.clone(),
        pair: pair.clone(),
        msg_type: MessageType::L2Event,
        timestamp: ws_msg.data.E,
        seq_id: Some(ws_msg.data.u),
        prev_seq_id: if let Some(id) = ws_msg.data.pu {
            if id == -1 { None } else { Some(id as u64) }
        } else {
            None
        },
        asks: ws_msg.data.a.iter().map(parse_order).collect::<Vec<Order>>(),
        bids: ws_msg.data.b.iter().map(parse_order).collect::<Vec<Order>>(),
        snapshot: false,
        json: msg.to_string(),
    };
    Ok(vec![orderbook])
}

pub(super) fn parse_l2_topk(
    market_type: MarketType,
    msg: &str,
) -> Result<Vec<OrderBookMsg>, SimpleError> {
    match parse_l2(market_type, msg) {
        Ok(mut orderbooks) => {
            for ob in orderbooks.iter_mut() {
                ob.snapshot = true;
                ob.msg_type = MessageType::L2TopK;
            }
            Ok(orderbooks)
        }
        Err(err) => Err(err),
    }
}

/// docs:
/// * https://binance-docs.github.io/apidocs/spot/en/#all-book-tickers-stream
/// * https://binance-docs.github.io/apidocs/futures/en/#all-book-tickers-stream
/// * https://binance-docs.github.io/apidocs/delivery/en/#all-book-tickers-stream
#[derive(Serialize, Deserialize)]
#[allow(non_snake_case)]
struct RawBboMsg {
    E: Option<i64>, // event time, None if spot
    u: u64,         // order book updateId
    s: String,      // symbol
    b: String,      // best bid price
    B: String,      // best bid qty
    a: String,      // best ask price
    A: String,      // best ask qty
    #[serde(flatten)]
    extra: HashMap<String, Value>,
}

pub(super) fn parse_bbo(
    market_type: MarketType,
    msg: &str,
    received_at: Option<i64>,
) -> Result<Vec<BboMsg>, SimpleError> {
    let ws_msg = serde_json::from_str::<WebsocketMsg<RawBboMsg>>(msg).map_err(|_e| {
        SimpleError::new(format!("Failed to deserialize {msg} to WebsocketMsg<RawBboMsg>"))
    })?;
    debug_assert!(ws_msg.stream.ends_with("bookTicker"));
    let timestamp =
        if market_type == MarketType::Spot { received_at.unwrap() } else { ws_msg.data.E.unwrap() };

    let symbol = ws_msg.data.s.as_str();
    let pair = crypto_pair::normalize_pair(symbol, EXCHANGE_NAME).unwrap();

    let (ask_quantity_base, ask_quantity_quote, ask_quantity_contract) = calc_quantity_and_volume(
        EXCHANGE_NAME,
        market_type,
        &pair,
        ws_msg.data.a.parse::<f64>().unwrap(),
        ws_msg.data.A.parse::<f64>().unwrap(),
    );

    let (bid_quantity_base, bid_quantity_quote, bid_quantity_contract) = calc_quantity_and_volume(
        EXCHANGE_NAME,
        market_type,
        &pair,
        ws_msg.data.b.parse::<f64>().unwrap(),
        ws_msg.data.B.parse::<f64>().unwrap(),
    );

    let bbo_msg = BboMsg {
        exchange: EXCHANGE_NAME.to_string(),
        market_type,
        symbol: symbol.to_string(),
        pair,
        msg_type: MessageType::BBO,
        timestamp,
        ask_price: ws_msg.data.a.parse::<f64>().unwrap(),
        ask_quantity_base,
        ask_quantity_quote,
        ask_quantity_contract,
        bid_price: ws_msg.data.b.parse::<f64>().unwrap(),
        bid_quantity_base,
        bid_quantity_quote,
        bid_quantity_contract,
        id: Some(ws_msg.data.u),
        json: msg.to_string(),
    };
    Ok(vec![bbo_msg])
}

#[derive(Serialize, Deserialize)]
#[allow(non_snake_case)]
struct RawFundingRateMsg {
    e: String,         // Event type
    E: i64,            // Event time
    s: String,         // Symbol
    p: String,         // Mark price
    i: Option<String>, // Index price
    P: String,         /* Estimated Settle Price, only useful in the last hour before the
                        * settlement starts */
    r: String, // Funding rate
    T: i64,    // Next funding time
    #[serde(flatten)]
    extra: HashMap<String, Value>,
}

pub(super) fn parse_funding_rate(
    market_type: MarketType,
    msg: &str,
) -> Result<Vec<FundingRateMsg>, SimpleError> {
    let obj = serde_json::from_str::<HashMap<String, Value>>(msg).map_err(|_e| {
        SimpleError::new(format!("Failed to deserialize {msg} to HashMap<String, Value>"))
    })?;
    let stream = obj.get("stream").unwrap().as_str().unwrap();
    let data = if stream == "!markPrice@arr" {
        obj.get("data")
            .unwrap()
            .as_array()
            .unwrap()
            .iter()
            .map(|x| serde_json::from_value::<RawFundingRateMsg>(x.clone()).unwrap())
            .collect()
    } else if stream.ends_with("@markPrice") {
        vec![serde_json::from_value::<RawFundingRateMsg>(obj.get("data").unwrap().clone()).unwrap()]
    } else {
        return Err(SimpleError::new(format!("Unknown funding rate messaeg {msg}")));
    };
    let mut funding_rates: Vec<FundingRateMsg> = data
        .into_iter()
        .filter(|x| !x.r.is_empty())
        .map(|raw_msg| FundingRateMsg {
            exchange: EXCHANGE_NAME.to_string(),
            market_type,
            symbol: raw_msg.s.clone(),
            pair: crypto_pair::normalize_pair(&raw_msg.s, EXCHANGE_NAME).unwrap(),
            msg_type: MessageType::FundingRate,
            timestamp: raw_msg.E,
            funding_rate: raw_msg.r.parse::<f64>().unwrap(),
            funding_time: raw_msg.T,
            estimated_rate: None,
            json: serde_json::to_string(&raw_msg).unwrap(),
        })
        .collect();
    if funding_rates.len() == 1 {
        funding_rates[0].json = msg.to_string();
    }
    Ok(funding_rates)
}

#[derive(Serialize, Deserialize)]
#[allow(non_snake_case)]
struct RawKlineMsgWithTime {
    e: String, // Event type
    E: i64,    // Event time
    s: String, // Symbol
    k: RawKlineMsg,
}

// See:
// * https://binance-docs.github.io/apidocs/spot/en/#kline-candlestick-streams
// * https://binance-docs.github.io/apidocs/futures/en/#kline-candlestick-streams
// * https://binance-docs.github.io/apidocs/delivery/en/#kline-candlestick-streams
#[derive(Serialize, Deserialize)]
#[allow(non_snake_case)]
struct RawKlineMsg {
    t: i64,    // Kline start time
    T: u64,    // Kline close time
    s: String, // Symbol
    i: String, // Interval
    f: u64,    // First trade ID
    L: u64,    // Last trade ID
    o: String, // Open price
    c: String, // Close price
    h: String, // High price
    l: String, // Low price
    v: String, // Base asset volume
    n: u64,    // Number of trades
    x: bool,   // Is this kline closed?
    q: String, // Quote asset volume
    V: String, // Taker buy base asset volume
    Q: String, // Taker buy quote asset volume
    B: String, // Ignore
}

pub(super) fn parse_candlestick(
    market_type: MarketType,
    msg: &str,
) -> Result<Vec<CandlestickMsg>, SimpleError> {
    let obj = serde_json::from_str::<WebsocketMsg<RawKlineMsgWithTime>>(msg)
        .map_err(SimpleError::from)?;

    let symbol = obj.data.k.s.as_str();
    let pair = crypto_pair::normalize_pair(symbol, EXCHANGE_NAME).unwrap();

    let v = obj.data.k.v.parse::<f64>().unwrap();
    let q = obj.data.k.q.parse::<f64>().unwrap();
    let (volume, quote_volume) = if market_type == MarketType::InverseFuture
        || market_type == MarketType::InverseSwap
    {
        let contract_value =
            crypto_contract_value::get_contract_value(EXCHANGE_NAME, market_type, &pair).unwrap();
        let quote_volume = v * contract_value;
        (q, quote_volume)
    } else {
        (v, q)
    };

    let kline_msg = CandlestickMsg {
        exchange: EXCHANGE_NAME.to_string(),
        market_type,
        msg_type: MessageType::Candlestick,
        symbol: symbol.to_string(),
        pair,
        timestamp: obj.data.E,
        period: obj.data.k.i,
        begin_time: obj.data.k.t / 1000,
        open: obj.data.k.o.parse().unwrap(),
        high: obj.data.k.h.parse().unwrap(),
        low: obj.data.k.l.parse().unwrap(),
        close: obj.data.k.c.parse().unwrap(),
        volume,
        quote_volume: Some(quote_volume),
        json: msg.to_string(),
    };

    Ok(vec![kline_msg])
}