barter_data/books/
mod.rs

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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use crate::subscription::book::OrderBookEvent;
use chrono::{DateTime, Utc};
use derive_more::Display;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize, Serializer};
use std::cmp::Ordering;
use tracing::debug;

/// Provides a [`OrderBookL2Manager`](manager::OrderBookL2Manager) for maintaining a set of local
/// L2 [`OrderBook`]s.
pub mod manager;

/// Provides an abstract collection of cheaply cloneable shared-state [`OrderBooks`].
pub mod map;

/// Normalised Barter [`OrderBook`] snapshot.
#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
pub struct OrderBook {
    pub sequence: u64,
    pub time_engine: Option<DateTime<Utc>>,
    bids: OrderBookSide<Bids>,
    asks: OrderBookSide<Asks>,
}

impl OrderBook {
    /// Construct a new sorted [`OrderBook`].
    ///
    /// Note that the passed bid and asks levels do not need to be pre-sorted.
    pub fn new<IterBids, IterAsks, L>(
        sequence: u64,
        time_engine: Option<DateTime<Utc>>,
        bids: IterBids,
        asks: IterAsks,
    ) -> Self
    where
        IterBids: IntoIterator<Item = L>,
        IterAsks: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        Self {
            sequence,
            time_engine,
            bids: OrderBookSide::bids(bids),
            asks: OrderBookSide::asks(asks),
        }
    }

    /// Generate a sorted [`OrderBook`] snapshot with a maximum depth.
    pub fn snapshot(&self, depth: usize) -> Self {
        Self {
            sequence: self.sequence,
            time_engine: self.time_engine,
            bids: OrderBookSide::bids(self.bids.levels.iter().take(depth).copied()),
            asks: OrderBookSide::asks(self.asks.levels.iter().take(depth).copied()),
        }
    }

    /// Update the local [`OrderBook`] from a new [`OrderBookEvent`].
    pub fn update(&mut self, event: OrderBookEvent) {
        match event {
            OrderBookEvent::Snapshot(snapshot) => {
                *self = snapshot;
            }
            OrderBookEvent::Update(update) => {
                self.sequence = update.sequence;
                self.time_engine = update.time_engine;
                self.upsert_bids(update.bids);
                self.upsert_asks(update.asks);
            }
        }
    }

    /// Update the local [`OrderBook`] by upserting the levels in an [`OrderBookSide`].
    pub fn upsert_bids(&mut self, update: OrderBookSide<Bids>) {
        self.bids.upsert(update.levels)
    }

    /// Update the local [`OrderBook`] by upserting the levels in an [`OrderBookSide`].
    pub fn upsert_asks(&mut self, update: OrderBookSide<Asks>) {
        self.asks.upsert(update.levels)
    }

    /// Return a reference to this [`OrderBook`]s bids.
    pub fn bids(&self) -> &OrderBookSide<Bids> {
        &self.bids
    }

    /// Return a reference to this [`OrderBook`]s asks.
    pub fn asks(&self) -> &OrderBookSide<Asks> {
        &self.asks
    }

    /// Calculate the mid-price by taking the average of the best bid and ask prices.
    ///
    /// See Docs: <https://www.quantstart.com/articles/high-frequency-trading-ii-limit-order-book>
    pub fn mid_price(&self) -> Option<Decimal> {
        match (self.bids.levels.first(), self.asks.levels.first()) {
            (Some(best_bid), Some(best_ask)) => Some(mid_price(best_bid.price, best_ask.price)),
            (Some(best_bid), None) => Some(best_bid.price),
            (None, Some(best_ask)) => Some(best_ask.price),
            (None, None) => None,
        }
    }

    /// Calculate the volume weighted mid-price (micro-price), weighing the best bid and ask prices
    /// with their associated amount.
    ///
    /// See Docs: <https://www.quantstart.com/articles/high-frequency-trading-ii-limit-order-book>
    pub fn volume_weighed_mid_price(&self) -> Option<Decimal> {
        match (self.bids.levels.first(), self.asks.levels.first()) {
            (Some(best_bid), Some(best_ask)) => {
                Some(volume_weighted_mid_price(*best_bid, *best_ask))
            }
            (Some(best_bid), None) => Some(best_bid.price),
            (None, Some(best_ask)) => Some(best_ask.price),
            (None, None) => None,
        }
    }
}

/// Normalised Barter [`Level`]s for one [`Side`] of the [`OrderBook`].
#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
pub struct OrderBookSide<Side> {
    #[serde(skip_serializing)]
    pub side: Side,
    levels: Vec<Level>,
}

/// Unit type to tag an [`OrderBookSide`] as the bid Side (ie/ buyers) of an [`OrderBook`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Display)]
pub struct Bids;

/// Unit type to tag an [`OrderBookSide`] as the ask Side (ie/ sellers) of an [`OrderBook`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Display)]
pub struct Asks;

impl Serialize for Asks {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str("asks")
    }
}

impl OrderBookSide<Bids> {
    /// Construct a new [`OrderBookSide<Bids>`] from the provided [`Level`]s.
    pub fn bids<Iter, L>(levels: Iter) -> Self
    where
        Iter: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        let mut levels = levels.into_iter().map(L::into).collect::<Vec<_>>();
        levels.sort_unstable_by(|a, b| a.price.cmp(&b.price).reverse());

        Self { side: Bids, levels }
    }

    /// Upsert bid [`Level`]s into this [`OrderBookSide<Bids>`].
    pub fn upsert<Iter, L>(&mut self, levels: Iter)
    where
        Iter: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        levels.into_iter().for_each(|upsert| {
            let upsert = upsert.into();
            self.upsert_single(upsert, |existing| {
                existing.price.cmp(&upsert.price).reverse()
            })
        })
    }
}

impl OrderBookSide<Asks> {
    /// Construct a new [`OrderBookSide<Asks>`] from the provided [`Level`]s.
    pub fn asks<Iter, L>(levels: Iter) -> Self
    where
        Iter: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        let mut levels = levels.into_iter().map(L::into).collect::<Vec<_>>();
        levels.sort_unstable_by(|a, b| a.price.cmp(&b.price));

        Self { side: Asks, levels }
    }

    /// Upsert ask [`Level`]s into this [`OrderBookSide<Asks>`].
    pub fn upsert<Iter, L>(&mut self, levels: Iter)
    where
        Iter: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        levels.into_iter().for_each(|upsert| {
            let upsert = upsert.into();
            self.upsert_single(upsert, |existing| existing.price.cmp(&upsert.price))
        })
    }
}

impl<Side> OrderBookSide<Side>
where
    Side: std::fmt::Display + std::fmt::Debug,
{
    /// Return a reference to the [`OrderBookSide`] levels.
    pub fn levels(&self) -> &[Level] {
        &self.levels
    }

    /// Upsert a single [`Level`] into this [`OrderBookSide`].
    ///
    /// ### Upsert Scenarios
    /// #### 1 Level Already Exists
    /// 1a) New value is 0, remove the level
    /// 1b) New value is > 0, replace the level
    ///
    /// #### 2 Level Does Not Exist
    /// 2a) New value is 0, log warn and continue
    /// 2b) New value is > 0, insert new level
    pub fn upsert_single<FnOrd>(&mut self, new_level: Level, fn_ord: FnOrd)
    where
        FnOrd: Fn(&Level) -> Ordering,
    {
        match (self.levels.binary_search_by(fn_ord), new_level.amount) {
            (Ok(index), new_amount) => {
                if new_amount.is_zero() {
                    // Scenario 1a: Level exists & new value is 0 => remove level
                    let _removed = self.levels.remove(index);
                } else {
                    // Scenario 1b: Level exists & new value is > 0 => replace level
                    self.levels[index].amount = new_amount;
                }
            }
            (Err(index), new_amount) => {
                if new_amount.is_zero() {
                    // Scenario 2a: Level does not exist & new value is 0 => log & continue
                    debug!(
                        ?new_level,
                        side = %self.side,
                        "received upsert Level with zero amount (to remove) that was not found"
                    );
                } else {
                    // Scenario 2b: Level does not exist & new value > 0 => insert new level
                    self.levels.insert(index, new_level);
                }
            }
        }
    }
}

impl Default for OrderBookSide<Bids> {
    fn default() -> Self {
        Self {
            side: Bids,
            levels: vec![],
        }
    }
}

impl Default for OrderBookSide<Asks> {
    fn default() -> Self {
        Self {
            side: Asks,
            levels: vec![],
        }
    }
}

/// Normalised Barter OrderBook [`Level`].
#[derive(Clone, Copy, PartialEq, Debug, Default, Deserialize, Serialize)]
pub struct Level {
    pub price: Decimal,
    pub amount: Decimal,
}

impl<T> From<(T, T)> for Level
where
    T: Into<Decimal>,
{
    fn from((price, amount): (T, T)) -> Self {
        Self::new(price, amount)
    }
}

impl Eq for Level {}

impl Level {
    pub fn new<T>(price: T, amount: T) -> Self
    where
        T: Into<Decimal>,
    {
        Self {
            price: price.into(),
            amount: amount.into(),
        }
    }
}

/// Calculate the mid-price by taking the average of the best bid and ask prices.
///
/// See Docs: <https://www.quantstart.com/articles/high-frequency-trading-ii-limit-order-book>
pub fn mid_price(best_bid_price: Decimal, best_ask_price: Decimal) -> Decimal {
    (best_bid_price + best_ask_price) / Decimal::TWO
}

/// Calculate the volume weighted mid-price (micro-price), weighing the best bid and ask prices
/// with their associated amount.
///
/// See Docs: <https://www.quantstart.com/articles/high-frequency-trading-ii-limit-order-book>
pub fn volume_weighted_mid_price(best_bid: Level, best_ask: Level) -> Decimal {
    ((best_bid.price * best_ask.amount) + (best_ask.price * best_bid.amount))
        / (best_bid.amount + best_ask.amount)
}

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

    mod order_book_l1 {
        use super::*;
        use crate::subscription::book::OrderBookL1;
        use rust_decimal_macros::dec;

        #[test]
        fn test_mid_price() {
            struct TestCase {
                input: OrderBookL1,
                expected: Decimal,
            }

            let tests = vec![
                TestCase {
                    // TC0
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Level::new(100, 999999),
                        best_ask: Level::new(200, 1),
                    },
                    expected: dec!(150.0),
                },
                TestCase {
                    // TC1
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Level::new(50, 1),
                        best_ask: Level::new(250, 999999),
                    },
                    expected: dec!(150.0),
                },
                TestCase {
                    // TC2
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Level::new(10, 999999),
                        best_ask: Level::new(250, 999999),
                    },
                    expected: dec!(130.0),
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                assert_eq!(test.input.mid_price(), test.expected, "TC{index} failed")
            }
        }

        #[test]
        fn test_volume_weighted_mid_price() {
            struct TestCase {
                input: OrderBookL1,
                expected: Decimal,
            }

            let tests = vec![
                TestCase {
                    // TC0: volume the same so should be equal to non-weighted mid price
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Level::new(100, 100),
                        best_ask: Level::new(200, 100),
                    },
                    expected: dec!(150.0),
                },
                TestCase {
                    // TC1: volume affects mid-price
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Level::new(100, 600),
                        best_ask: Level::new(200, 1000),
                    },
                    expected: dec!(137.5),
                },
                TestCase {
                    // TC2: volume the same and price the same
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Level::new(1000, 999999),
                        best_ask: Level::new(1000, 999999),
                    },
                    expected: dec!(1000.0),
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                assert_eq!(
                    test.input.volume_weighed_mid_price(),
                    test.expected,
                    "TC{index} failed"
                )
            }
        }
    }

    mod order_book {
        use super::*;
        use rust_decimal_macros::dec;

        #[test]
        fn test_mid_price() {
            struct TestCase {
                input: OrderBook,
                expected: Option<Decimal>,
            }

            let tests = vec![
                TestCase {
                    // TC0: no levels so 0.0 mid-price
                    input: OrderBook::new::<Vec<_>, Vec<_>, Level>(
                        0,
                        Default::default(),
                        vec![],
                        vec![],
                    ),
                    expected: None,
                },
                TestCase {
                    // TC1: no asks in the books so take best bid price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(100.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![],
                    ),
                    expected: Some(dec!(100.0)),
                },
                TestCase {
                    // TC2: no bids in the books so take ask price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![],
                        vec![
                            Level::new(dec!(50.0), dec!(100.0)),
                            Level::new(dec!(100.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(50.0)),
                },
                TestCase {
                    // TC3: best bid and ask amount is the same, so regular mid-price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(100.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![
                            Level::new(dec!(200.0), dec!(100.0)),
                            Level::new(dec!(300.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(150.0)),
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                assert_eq!(test.input.mid_price(), test.expected, "TC{index} failed")
            }
        }

        #[test]
        fn test_volume_weighted_mid_price() {
            struct TestCase {
                input: OrderBook,
                expected: Option<Decimal>,
            }

            let tests = vec![
                TestCase {
                    // TC0: no levels so 0.0 mid-price
                    input: OrderBook::new::<Vec<_>, Vec<_>, Level>(
                        0,
                        Default::default(),
                        vec![],
                        vec![],
                    ),
                    expected: None,
                },
                TestCase {
                    // TC1: no asks in the books so take best bid price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(100.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![],
                    ),
                    expected: Some(dec!(100.0)),
                },
                TestCase {
                    // TC2: no bids in the books so take ask price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![],
                        vec![
                            Level::new(dec!(50.0), dec!(100.0)),
                            Level::new(dec!(100.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(50.0)),
                },
                TestCase {
                    // TC3: best bid and ask amount is the same, so regular mid-price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(100.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![
                            Level::new(dec!(200.0), dec!(100.0)),
                            Level::new(dec!(300.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(150.0)),
                },
                TestCase {
                    // TC4: valid volume weighted mid-price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(3000.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![
                            Level::new(dec!(200.0), dec!(1000.0)),
                            Level::new(dec!(300.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(175.0)),
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                assert_eq!(
                    test.input.volume_weighed_mid_price(),
                    test.expected,
                    "TC{index} failed"
                )
            }
        }
    }

    mod order_book_side {
        use super::*;
        use rust_decimal_macros::dec;

        #[test]
        fn test_upsert_single() {
            struct TestCase {
                book_side: OrderBookSide<Bids>,
                new_level: Level,
                expected: OrderBookSide<Bids>,
            }

            let tests = vec![
                TestCase {
                    // TC0: Level exists & new value is 0 => remove Level
                    book_side: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                    new_level: Level::new(dec!(100), dec!(0)),
                    expected: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                    ]),
                },
                TestCase {
                    // TC1: Level exists & new value is > 0 => replace Level
                    book_side: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                    new_level: Level::new(dec!(100), dec!(10)),
                    expected: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(10)),
                    ]),
                },
                TestCase {
                    // TC2: Level does not exist & new value > 0 => insert new Level
                    book_side: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                    new_level: Level::new(dec!(110), dec!(1)),
                    expected: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                        Level::new(dec!(110), dec!(1)),
                    ]),
                },
                TestCase {
                    // TC3: Level does not exist & new value is 0 => no change
                    book_side: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                    new_level: Level::new(dec!(110), dec!(0)),
                    expected: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                },
            ];

            for (index, mut test) in tests.into_iter().enumerate() {
                test.book_side.upsert_single(test.new_level, |existing| {
                    existing.price.cmp(&test.new_level.price).reverse()
                });
                assert_eq!(test.book_side, test.expected, "TC{} failed", index);
            }
        }
    }
}