bitvavo-api-client 0.2.0

Async Rust client for the Bitvavo REST and WebSocket API
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Data types shared by the REST and WebSocket clients.
//!
//! Monetary amounts and prices are kept as strings to preserve the exact
//! decimal representation returned by the exchange.

use serde::de::{self, Deserializer, SeqAccess, Visitor};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Order side.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Side {
    Buy,
    Sell,
}

/// Order type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum OrderType {
    Limit,
    Market,
    StopLoss,
    StopLossLimit,
    TakeProfit,
    TakeProfitLimit,
}

/// Response of `GET /time`.
#[derive(Debug, Clone, Deserialize)]
pub struct ServerTime {
    pub time: u64,
}

/// A tradable market.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Market {
    pub market: String,
    pub status: String,
    pub base: String,
    pub quote: String,
    #[serde(default)]
    pub price_precision: Option<u32>,
    #[serde(default)]
    pub min_order_in_base_asset: Option<String>,
    #[serde(default)]
    pub min_order_in_quote_asset: Option<String>,
    #[serde(default)]
    pub max_order_in_base_asset: Option<String>,
    #[serde(default)]
    pub max_order_in_quote_asset: Option<String>,
    #[serde(default)]
    pub order_types: Vec<String>,
}

/// A supported asset.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Asset {
    pub symbol: String,
    pub name: String,
    #[serde(default)]
    pub decimals: Option<u32>,
    #[serde(default)]
    pub deposit_fee: Option<String>,
    #[serde(default)]
    pub deposit_confirmations: Option<u32>,
    #[serde(default)]
    pub deposit_status: Option<String>,
    #[serde(default)]
    pub withdrawal_fee: Option<String>,
    #[serde(default)]
    pub withdrawal_min_amount: Option<String>,
    #[serde(default)]
    pub withdrawal_status: Option<String>,
    #[serde(default)]
    pub networks: Vec<String>,
    #[serde(default)]
    pub message: Option<String>,
}

/// A single price level as `[price, size]`.
pub type PriceLevel = [String; 2];

/// Order book snapshot.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderBook {
    pub market: String,
    pub nonce: u64,
    pub bids: Vec<PriceLevel>,
    pub asks: Vec<PriceLevel>,
}

/// A public trade.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicTrade {
    pub id: String,
    pub timestamp: u64,
    pub amount: String,
    pub price: String,
    pub side: Side,
}

/// A single OHLCV candle.
/// The API returns candles as arrays of the form
/// `[timestamp, open, high, low, close, volume]`.
#[derive(Debug, Clone)]
pub struct Candle {
    pub timestamp: u64,
    pub open: String,
    pub high: String,
    pub low: String,
    pub close: String,
    pub volume: String,
}

impl<'de> Deserialize<'de> for Candle {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct CandleVisitor;

        impl<'de> Visitor<'de> for CandleVisitor {
            type Value = Candle;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a candle array [timestamp, open, high, low, close, volume]")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Candle, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let timestamp = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
                let open = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;
                let high = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(2, &self))?;
                let low = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(3, &self))?;
                let close = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(4, &self))?;
                let volume = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(5, &self))?;
                Ok(Candle {
                    timestamp,
                    open,
                    high,
                    low,
                    close,
                    volume,
                })
            }
        }

        deserializer.deserialize_seq(CandleVisitor)
    }
}

/// Latest trade price for a market.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TickerPrice {
    pub market: String,
    #[serde(default)]
    pub price: Option<String>,
}

/// Best bid and ask for a market.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TickerBook {
    pub market: String,
    #[serde(default)]
    pub bid: Option<String>,
    #[serde(default)]
    pub ask: Option<String>,
    #[serde(default)]
    pub bid_size: Option<String>,
    #[serde(default)]
    pub ask_size: Option<String>,
}

/// 24 hour ticker statistics for a market.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Ticker24h {
    pub market: String,
    #[serde(default)]
    pub open: Option<String>,
    #[serde(default)]
    pub high: Option<String>,
    #[serde(default)]
    pub low: Option<String>,
    #[serde(default)]
    pub last: Option<String>,
    #[serde(default)]
    pub volume: Option<String>,
    #[serde(default)]
    pub volume_quote: Option<String>,
    #[serde(default)]
    pub bid: Option<String>,
    #[serde(default)]
    pub bid_size: Option<String>,
    #[serde(default)]
    pub ask: Option<String>,
    #[serde(default)]
    pub ask_size: Option<String>,
    #[serde(default)]
    pub timestamp: Option<u64>,
    #[serde(default)]
    pub start_timestamp: Option<u64>,
    #[serde(default)]
    pub open_timestamp: Option<u64>,
    #[serde(default)]
    pub close_timestamp: Option<u64>,
}

/// An order as returned by the trading endpoints.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
    pub order_id: String,
    pub market: String,
    #[serde(default)]
    pub client_order_id: Option<String>,
    #[serde(default)]
    pub created: Option<u64>,
    #[serde(default)]
    pub updated: Option<u64>,
    pub status: String,
    pub side: Side,
    pub order_type: OrderType,
    #[serde(default)]
    pub amount: Option<String>,
    #[serde(default)]
    pub amount_remaining: Option<String>,
    #[serde(default)]
    pub amount_quote: Option<String>,
    #[serde(default)]
    pub amount_quote_remaining: Option<String>,
    #[serde(default)]
    pub price: Option<String>,
    #[serde(default)]
    pub on_hold: Option<String>,
    #[serde(default)]
    pub on_hold_currency: Option<String>,
    #[serde(default)]
    pub filled_amount: Option<String>,
    #[serde(default)]
    pub filled_amount_quote: Option<String>,
    #[serde(default)]
    pub fee_paid: Option<String>,
    #[serde(default)]
    pub fee_currency: Option<String>,
    #[serde(default)]
    pub fills: Vec<OrderFill>,
    #[serde(default)]
    pub trigger_price: Option<String>,
    #[serde(default)]
    pub trigger_amount: Option<String>,
    #[serde(default)]
    pub trigger_type: Option<String>,
    #[serde(default)]
    pub trigger_reference: Option<String>,
    #[serde(default)]
    pub time_in_force: Option<String>,
    #[serde(default)]
    pub post_only: Option<bool>,
    #[serde(default)]
    pub self_trade_prevention: Option<String>,
    #[serde(default)]
    pub visible: Option<bool>,
    #[serde(default)]
    pub disable_market_protection: Option<bool>,
}

/// A fill embedded in an order response.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderFill {
    pub id: String,
    pub timestamp: u64,
    pub amount: String,
    pub price: String,
    #[serde(default)]
    pub taker: Option<bool>,
    #[serde(default)]
    pub fee: Option<String>,
    #[serde(default)]
    pub fee_currency: Option<String>,
    #[serde(default)]
    pub settled: Option<bool>,
}

/// Response of a cancel order request.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CanceledOrder {
    pub order_id: String,
    #[serde(default)]
    pub client_order_id: Option<String>,
}

/// A private trade (an execution of one of your orders).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Trade {
    pub id: String,
    pub order_id: String,
    #[serde(default)]
    pub client_order_id: Option<String>,
    pub timestamp: u64,
    pub market: String,
    pub side: Side,
    pub amount: String,
    pub price: String,
    #[serde(default)]
    pub taker: Option<bool>,
    #[serde(default)]
    pub fee: Option<String>,
    #[serde(default)]
    pub fee_currency: Option<String>,
    #[serde(default)]
    pub settled: Option<bool>,
}

/// Fee rates that apply to the account.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FeeRates {
    #[serde(default)]
    pub tier: Option<serde_json::Value>,
    #[serde(default)]
    pub taker: Option<String>,
    #[serde(default)]
    pub maker: Option<String>,
    #[serde(default)]
    pub volume: Option<String>,
}

/// Account information.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Account {
    pub fees: FeeRates,
    #[serde(default)]
    pub capabilities: Vec<String>,
}

/// Balance of one asset.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Balance {
    pub symbol: String,
    pub available: String,
    pub in_order: String,
}

/// Deposit address or bank details for an asset.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DepositInfo {
    #[serde(default)]
    pub address: Option<String>,
    #[serde(default)]
    pub payment_id: Option<String>,
    #[serde(default)]
    pub iban: Option<String>,
    #[serde(default)]
    pub bic: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
}

/// Response of a withdrawal request.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WithdrawalResponse {
    pub success: bool,
    pub symbol: String,
    pub amount: String,
}

/// A historical deposit.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DepositEntry {
    pub timestamp: u64,
    pub symbol: String,
    pub amount: String,
    #[serde(default)]
    pub address: Option<String>,
    #[serde(default)]
    pub payment_id: Option<String>,
    #[serde(default)]
    pub tx_id: Option<String>,
    #[serde(default)]
    pub fee: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
}

/// A historical withdrawal.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WithdrawalEntry {
    pub timestamp: u64,
    pub symbol: String,
    pub amount: String,
    #[serde(default)]
    pub address: Option<String>,
    #[serde(default)]
    pub payment_id: Option<String>,
    #[serde(default)]
    pub tx_id: Option<String>,
    #[serde(default)]
    pub fee: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
}

/// Ticker update pushed on the `ticker` WebSocket channel.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TickerEvent {
    pub market: String,
    #[serde(default)]
    pub best_bid: Option<String>,
    #[serde(default)]
    pub best_bid_size: Option<String>,
    #[serde(default)]
    pub best_ask: Option<String>,
    #[serde(default)]
    pub best_ask_size: Option<String>,
    #[serde(default)]
    pub last_price: Option<String>,
}

/// Trade pushed on the `trades` WebSocket channel.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TradeEvent {
    pub id: String,
    pub timestamp: u64,
    pub market: String,
    pub amount: String,
    pub price: String,
    pub side: Side,
}

/// Candle update pushed on the `candles` WebSocket channel.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CandleEvent {
    pub market: String,
    pub interval: String,
    pub candle: Vec<Candle>,
}

/// Order book delta pushed on the `book` WebSocket channel.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BookEvent {
    pub market: String,
    pub nonce: u64,
    #[serde(default)]
    pub bids: Vec<PriceLevel>,
    #[serde(default)]
    pub asks: Vec<PriceLevel>,
}

/// Order update pushed on the `account` WebSocket channel.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderEvent {
    pub order_id: String,
    pub market: String,
    #[serde(default)]
    pub client_order_id: Option<String>,
    #[serde(default)]
    pub created: Option<u64>,
    #[serde(default)]
    pub updated: Option<u64>,
    pub status: String,
    pub side: Side,
    #[serde(default)]
    pub order_type: Option<OrderType>,
    #[serde(default)]
    pub amount: Option<String>,
    #[serde(default)]
    pub amount_remaining: Option<String>,
    #[serde(default)]
    pub amount_quote: Option<String>,
    #[serde(default)]
    pub amount_quote_remaining: Option<String>,
    #[serde(default)]
    pub price: Option<String>,
    #[serde(default)]
    pub on_hold: Option<String>,
    #[serde(default)]
    pub on_hold_currency: Option<String>,
    #[serde(default)]
    pub time_in_force: Option<String>,
    #[serde(default)]
    pub post_only: Option<bool>,
    #[serde(default)]
    pub self_trade_prevention: Option<String>,
    #[serde(default)]
    pub visible: Option<bool>,
}

/// Fill pushed on the `account` WebSocket channel.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FillEvent {
    pub market: String,
    pub order_id: String,
    pub fill_id: String,
    pub timestamp: u64,
    pub side: Side,
    pub amount: String,
    pub price: String,
    #[serde(default)]
    pub taker: Option<bool>,
    #[serde(default)]
    pub fee: Option<String>,
    #[serde(default)]
    pub fee_currency: Option<String>,
}

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

    #[test]
    fn candle_deserializes_from_array() {
        let json = r#"[1548051540000, "3416.3", "3416.3", "3396.1", "3396.1", "4.14"]"#;
        let candle: Candle = serde_json::from_str(json).unwrap();
        assert_eq!(candle.timestamp, 1548051540000);
        assert_eq!(candle.open, "3416.3");
        assert_eq!(candle.volume, "4.14");
    }

    mod fuzz {
        use super::*;
        use crate::tests::arb_json;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn candle_deserialize_never_panics(value in arb_json()) {
                let _ = serde_json::from_value::<Candle>(value);
            }

            #[test]
            fn candle_deserializes_valid_arrays(
                timestamp in any::<u64>(),
                fields in proptest::collection::vec("[0-9]{1,12}(\\.[0-9]{1,8})?", 5),
            ) {
                let json = serde_json::json!([
                    timestamp, fields[0], fields[1], fields[2], fields[3], fields[4]
                ]);
                let candle: Candle = serde_json::from_value(json).unwrap();
                prop_assert_eq!(candle.timestamp, timestamp);
                prop_assert_eq!(&candle.volume, &fields[4]);
            }
        }
    }

    #[test]
    fn side_serializes_lowercase() {
        assert_eq!(serde_json::to_string(&Side::Buy).unwrap(), "\"buy\"");
        assert_eq!(serde_json::to_string(&Side::Sell).unwrap(), "\"sell\"");
    }

    #[test]
    fn order_type_serializes_camel_case() {
        assert_eq!(
            serde_json::to_string(&OrderType::StopLossLimit).unwrap(),
            "\"stopLossLimit\""
        );
    }
}