maicoin_max 2.1.1

MaiCoin Max API client for Rust
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Feed messages received from server.
//!
//! Currently MaiCoin MAX supports the following feeds:
//!
//! - Public orderbooks ([`PubOrderBookFeed`])
//! - Public trades ([`PubTradeFeed`])
//! - Public tickers ([`PubTickerFeed`])
//! - Private orderbooks ([`PrivOrderBookFeed`])
//! - Private trades ([`PrivTradeFeed`])
//! - Private balance changes ([`PrivBalanceFeed`])
//!
//! Each feeds implement [`Feed`] trait, which makes it easy to be dispatched by [`crate::v2::ws::ServerPushEvent`].

use std::result::Result as StdResult;

use chrono::serde as chrono_serde;
use rust_decimal::Decimal;
use serde::{de, de::DeserializeOwned, Deserialize};
use serde_json::Value as JsonValue;

use crate::common::*;
use crate::error::*;

// ========================
// Interfaces and Utilities
// ========================

/// Common interface for feed events pushed by server.
pub trait Feed
where
    Self: Sized + DeserializeOwned,
{
    /// Feed content data.
    type Records;

    /// Returns whether current feed event is a snapshot, or an update.
    fn is_snapshot(&self) -> bool;

    /// Transform the feed into the records it contains.
    fn into_record(self) -> Self::Records;

    /// Deserialize a serde_json::Value into a feed event. You are unlikely to need to work with this directly except via
    /// [`crate::v2::ws::ServerPushEvent`].
    fn from_json_value(value: JsonValue) -> Result<Self> {
        serde_json::from_value::<Self>(value).map_err(Error::WsApiParse)
    }
}

fn parse_pub_feed_type<'de, D>(deserializer: D) -> StdResult<bool, D::Error>
where
    D: de::Deserializer<'de>,
{
    let val: String = Deserialize::deserialize(deserializer)?;
    match val.to_lowercase().as_str() {
        "snapshot" => Ok(true),
        "update" => Ok(false),
        _ => Err(de::Error::invalid_value(
            de::Unexpected::Str(val.as_str()),
            &"snapshot/update",
        )),
    }
}

fn parse_priv_feed_type<'de, D>(deserializer: D) -> StdResult<bool, D::Error>
where
    D: de::Deserializer<'de>,
{
    let val: String = Deserialize::deserialize(deserializer)?;
    match val.to_lowercase().as_str() {
        s if s.ends_with("_snapshot") => Ok(true),
        s if s.ends_with("_update") => Ok(false),
        _ => Err(de::Error::invalid_value(
            de::Unexpected::Str(val.as_str()),
            &"*_snapshot/*_update",
        )),
    }
}

// ==================================
// Orderbook feed from public channel
// ==================================

/// Orderbook feed from public channel.
///
/// [Official document](https://maicoin.github.io/max-websocket-docs/#/public_orderbook?id=orderbook-subscription)
#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PubOrderBookFeed {
    /// `true` if this feed is a snapshot.
    #[serde(rename = "e", deserialize_with = "parse_pub_feed_type")]
    pub is_snapshot: bool,
    /// Market name.
    #[serde(rename = "M")]
    pub market: Symbol,
    /// List of ask orders.
    #[serde(rename = "a")]
    pub ask: Vec<PubOrderBookRec>,
    /// List of bid orders.
    #[serde(rename = "b")]
    pub bid: Vec<PubOrderBookRec>,
    /// Timestamp.
    #[serde(rename = "T", with = "chrono_serde::ts_milliseconds")]
    pub time: DateTime,
}

impl Feed for PubOrderBookFeed {
    type Records = (Vec<PubOrderBookRec>, Vec<PubOrderBookRec>);

    fn is_snapshot(&self) -> bool {
        self.is_snapshot
    }

    fn into_record(self) -> Self::Records {
        (self.ask, self.bid)
    }
}

#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PubOrderBookRec {
    pub price: Decimal,
    pub volume: Decimal,
}

// ==============================
// Trade feed from public channel
// ==============================

/// Trade feed from public channel.
///
/// [Official document](https://maicoin.github.io/max-websocket-docs/#/public_trade?id=trade-subscription)
#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PubTradeFeed {
    /// `true` if this feed is a snapshot.
    #[serde(rename = "e", deserialize_with = "parse_pub_feed_type")]
    pub is_snapshot: bool,
    /// Market name.
    #[serde(rename = "M")]
    pub market: Symbol,
    /// List of filled trades.
    #[serde(rename = "t")]
    pub trades: Vec<PubTradeRec>,
    /// Timestamp.
    #[serde(rename = "T", with = "chrono_serde::ts_milliseconds")]
    pub time: DateTime,
}

impl Feed for PubTradeFeed {
    type Records = Vec<PubTradeRec>;

    fn is_snapshot(&self) -> bool {
        self.is_snapshot
    }

    fn into_record(self) -> Self::Records {
        self.trades
    }
}

#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PubTradeRec {
    #[serde(rename = "p")]
    pub price: Decimal,
    #[serde(rename = "v")]
    pub volume: Decimal,
    #[serde(rename = "T", with = "chrono_serde::ts_milliseconds")]
    pub create_time: DateTime,
    #[serde(rename = "tr")]
    pub trend: String,
}

// ===============================
// Ticker feed from public channel
// ===============================

/// Ticker feed from public channel.
///
/// [Official document](https://maicoin.github.io/max-websocket-docs/#/public_ticker?id=ticker-subscription)
#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PubTickerFeed {
    /// `true` if this feed is a snapshot.
    #[serde(rename = "e", deserialize_with = "parse_pub_feed_type")]
    pub is_snapshot: bool,
    /// Market name.
    #[serde(rename = "M")]
    pub market: Symbol,
    /// Ticker (OHLC).
    #[serde(rename = "tk")]
    pub tick: TickerRec,
    /// Timestamp
    #[serde(rename = "T", with = "chrono_serde::ts_milliseconds")]
    pub time: DateTime,
}

impl Feed for PubTickerFeed {
    type Records = TickerRec;

    fn is_snapshot(&self) -> bool {
        self.is_snapshot
    }

    fn into_record(self) -> Self::Records {
        self.tick
    }
}

#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct TickerRec {
    #[serde(rename = "O")]
    pub open: Decimal,
    #[serde(rename = "H")]
    pub close: Decimal,
    #[serde(rename = "L")]
    pub high: Decimal,
    #[serde(rename = "C")]
    pub low: Decimal,
    #[serde(rename = "v")]
    pub volume: Decimal,
}

// ===============================
// Market status feed from public channel
// ===============================

/// Market status feed from public channel.
///
/// [Official document](https://maicoin.github.io/max-websocket-docs/#/public_market_status)
#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PubMarketStatueFeed {
    /// `true` if this feed is a snapshot.
    #[serde(rename = "c")]
    pub channel: String,
    #[serde(rename = "e", deserialize_with = "parse_pub_feed_type")]
    pub is_snapshot: bool,
    /// Market name.
    #[serde(rename = "ms")]
    pub markets: Vec<MarketStatusInfo>,
}

impl Feed for PubMarketStatueFeed {
    type Records = Vec<MarketStatusInfo>;

    fn is_snapshot(&self) -> bool {
        self.is_snapshot
    }

    fn into_record(self) -> Self::Records {
        self.markets
    }
}

#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct MarketStatusInfo {
    #[serde(rename = "M")]
    pub market: String,
    #[serde(rename = "st")]
    pub status: String,
    #[serde(rename = "bu")]
    pub base_unit: String,
    #[serde(rename = "bup")]
    pub base_unit_precision: i8,
    #[serde(rename = "mba")]
    pub min_base_amount: Decimal,
    #[serde(rename = "qu")]
    pub quote_unit: String,
    #[serde(rename = "qup")]
    pub quote_unit_precision: i8,
    #[serde(rename = "mqa")]
    pub min_quote_amount: Decimal,
    #[serde(rename = "mws")]
    pub m_wallet_supported: bool,
}

// ===================================================
// Orderbook feed from private (authenticated) channel
// ===================================================

/// Orderbook feed from private (authenticated) channel.
///
/// [Official document](https://maicoin.github.io/max-websocket-docs/#/private_channels?id=order-response)
#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PrivOrderBookFeed {
    /// `true` if this feed is a snapshot.
    #[serde(rename = "e", deserialize_with = "parse_priv_feed_type")]
    pub is_snapshot: bool,
    /// List of submitted orders.
    #[serde(rename = "o")]
    pub orders: Vec<PrivOrderBookRec>,
    /// Timestamp.
    #[serde(rename = "T", with = "chrono_serde::ts_milliseconds")]
    pub time: DateTime,
}

impl Feed for PrivOrderBookFeed {
    type Records = Vec<PrivOrderBookRec>;

    fn is_snapshot(&self) -> bool {
        self.is_snapshot
    }

    fn into_record(self) -> Self::Records {
        self.orders
    }
}

#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PrivOrderBookRec {
    /// Order ID.
    #[serde(rename = "i")]
    pub oid: u64,
    /// Order side.
    #[serde(rename = "sd")]
    pub side: String,
    /// Order type.
    #[serde(rename = "ot")]
    pub ord_type: String,
    /// Order price.
    #[serde(rename = "p")]
    pub price: Option<Decimal>,
    /// Stop price.
    #[serde(rename = "sp")]
    pub stop_price: Option<Decimal>,
    /// Average price.
    #[serde(rename = "ap")]
    pub avg_price: Option<Decimal>,
    /// Order state.
    #[serde(rename = "S")]
    pub state: String,
    /// Market name.
    #[serde(rename = "M")]
    pub market: Symbol,
    /// Order create time.
    #[serde(rename = "T", with = "chrono_serde::ts_milliseconds")]
    pub create_time: DateTime,
    /// Volume.
    #[serde(rename = "v")]
    pub volume: Decimal,
    /// Remaining volume.
    #[serde(rename = "rv")]
    pub remaining_volume: Option<Decimal>,
    /// Executed volume.
    #[serde(rename = "ev")]
    pub executed_volume: Option<Decimal>,
    /// Trade count.
    #[serde(rename = "tc")]
    pub trade_count: Option<u64>,
    /// Client order ID.
    #[serde(rename = "ci")]
    pub client_oid: Option<String>,
    /// Group ID.
    #[serde(rename = "gi")]
    pub group_id: Option<u64>,
}

// ===============================================
// Trade feed from private (authenticated) channel
// ===============================================

/// Trade feed from private (authenticated) channel.
///
/// [Official document](https://maicoin.github.io/max-websocket-docs/#/private_channels?id=trade-response)
#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PrivTradeFeed {
    /// `true` if this feed is a snapshot.
    #[serde(rename = "e", deserialize_with = "parse_priv_feed_type")]
    pub is_snapshot: bool,
    /// List of filled trades.
    #[serde(rename = "t")]
    pub trades: Vec<PrivTradeRec>,
    /// Timestamp.
    #[serde(rename = "T", with = "chrono_serde::ts_milliseconds")]
    pub time: DateTime,
}

impl Feed for PrivTradeFeed {
    type Records = Vec<PrivTradeRec>;

    fn is_snapshot(&self) -> bool {
        self.is_snapshot
    }

    fn into_record(self) -> Self::Records {
        self.trades
    }
}

#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PrivTradeRec {
    /// Trade ID.
    #[serde(rename = "i")]
    pub tid: u64,
    /// Trade side.
    #[serde(rename = "sd")]
    pub side: String,
    /// Trade price.
    #[serde(rename = "p")]
    pub price: Decimal,
    /// Trade volume.
    #[serde(rename = "v")]
    pub volume: Decimal,
    /// Market name.
    #[serde(rename = "M")]
    pub market: Symbol,
    /// Create time.
    #[serde(rename = "T", with = "chrono_serde::ts_milliseconds")]
    pub create_time: DateTime,
    /// Trade fee.
    #[serde(rename = "f")]
    pub fee: Decimal,
    /// Trade fee currency.
    #[serde(rename = "fc")]
    pub fee_currency: String,
    /// Is trade maker or not.
    #[serde(rename = "m")]
    pub is_maker: bool,
}

// =============================================================
// Balance information feed from private (authenticated) channel
// =============================================================

/// Balance information feed from private (authenticated) channel.
///
/// [Official document](https://maicoin.github.io/max-websocket-docs/#/private_channels?id=account-response)
#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PrivBalanceFeed {
    /// `true` if this feed is a snapshot.
    #[serde(rename = "e", deserialize_with = "parse_priv_feed_type")]
    pub is_snapshot: bool,
    /// Balance for each wallets.
    #[serde(rename = "B")]
    pub balance: Vec<PrivBalanceItem>,
    /// Timestamp.
    #[serde(rename = "T", with = "chrono_serde::ts_milliseconds")]
    pub time: DateTime,
}

impl Feed for PrivBalanceFeed {
    type Records = Vec<PrivBalanceItem>;

    fn is_snapshot(&self) -> bool {
        self.is_snapshot
    }

    fn into_record(self) -> Self::Records {
        self.balance
    }
}

#[derive(Deserialize, Debug, Eq, PartialEq)]
pub struct PrivBalanceItem {
    /// Currency name.
    #[serde(rename = "cu")]
    pub currency: String,
    /// Available balance.
    #[serde(rename = "av")]
    pub available: Decimal,
    /// Locked amount.
    #[serde(rename = "l")]
    pub locked: Decimal,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pub_feed_type_parse() {
        fn parse(input: &str) -> StdResult<bool, serde_json::Error> {
            let mut deserializer = serde_json::Deserializer::from_str(input);
            parse_pub_feed_type(&mut deserializer)
        }

        assert!(parse(r#""snapshot""#).expect("invalid test case"));
        assert!(!parse(r#""update""#).expect("invalid test case"));

        const ERROR_MSG: &str = "must not allow value other than snapshot and update";
        parse(r#""?""#).expect_err(ERROR_MSG);
        parse(r#""_snapshot""#).expect_err(ERROR_MSG);
        parse(r#"" update""#).expect_err(ERROR_MSG);
        parse(r#""""#).expect_err(ERROR_MSG);
        parse(r#""updatesnapshot""#).expect_err(ERROR_MSG);
    }

    #[test]
    fn test_priv_feed_type_parse() {
        fn parse(input: &str) -> StdResult<bool, serde_json::Error> {
            let mut deserializer = serde_json::Deserializer::from_str(input);
            parse_priv_feed_type(&mut deserializer)
        }

        assert!(parse(r#""order_snapshot""#).expect("invalid test case"));
        assert!(!parse(r#""order_update""#).expect("invalid test case"));
        assert!(parse(r#""trade_snapshot""#).expect("invalid test case"));
        assert!(!parse(r#""trade_update""#).expect("invalid test case"));
        assert!(parse(r#""account_snapshot""#).expect("invalid test case"));
        assert!(!parse(r#""account_update""#).expect("invalid test case"));
        assert!(parse(r#""*_snapshot""#).expect("invalid test case"));
        assert!(!parse(r#""??_update""#).expect("invalid test case"));
        assert!(parse(r#""_snapshot""#).expect("invalid test case"));
        assert!(!parse(r#"" _update""#).expect("invalid test case"));

        const ERROR_MSG: &str = "must not allow value other than snapshot and update";
        parse(r#""?""#).expect_err(ERROR_MSG);
        parse(r#""order_snapshot_""#).expect_err(ERROR_MSG);
        parse(r#""order update""#).expect_err(ERROR_MSG);
        parse(r#""order""#).expect_err(ERROR_MSG);
        parse(r#""""#).expect_err(ERROR_MSG);
        parse(r#""updatesnapshot""#).expect_err(ERROR_MSG);
    }
}