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
use super::SubKind;
use crate::{
    event::{MarketEvent, MarketIter},
    exchange::ExchangeId,
};
use barter_integration::model::{Exchange, Instrument, Side};
use barter_macro::{DeSubKind, SerSubKind};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use tracing::debug;

/// Barter [`Subscription`](super::Subscription) [`SubKind`] that yields level 1 [`OrderBook`]
/// [`MarketEvent<T>`](crate::event::MarketEvent) events.
///
/// Level 1 refers to the best non-aggregated bid and ask [`Level`] on each side of the
/// [`OrderBook`].
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, DeSubKind, SerSubKind)]
pub struct OrderBooksL1;

impl SubKind for OrderBooksL1 {
    type Event = OrderBookL1;
}

/// Normalised Barter [`OrderBookL1`] snapshot containing the latest best bid and ask.
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct OrderBookL1 {
    pub last_update_time: DateTime<Utc>,
    pub best_bid: Level,
    pub best_ask: Level,
}

/// Barter [`Subscription`](super::Subscription) [`SubKind`] that yields level 2 [`OrderBook`]
/// [`MarketEvent<T>`](crate::event::MarketEvent) events.
///
/// Level 2 refers to the [`OrderBook`] aggregated by price.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, DeSubKind, SerSubKind)]
pub struct OrderBooksL2;

impl SubKind for OrderBooksL2 {
    type Event = OrderBook;
}

/// Barter [`Subscription`](super::Subscription) [`SubKind`] that yields level 3 [`OrderBook`]
/// [`MarketEvent<T>`](crate::event::MarketEvent) events.
///
/// Level 3 refers to the non-aggregated [`OrderBook`]. This is a direct replication of the exchange
/// [`OrderBook`].
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, DeSubKind, SerSubKind)]
pub struct OrderBooksL3;

impl SubKind for OrderBooksL3 {
    type Event = OrderBook;
}

/// Normalised Barter [`OrderBook`] snapshot.
#[derive(Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct OrderBook {
    pub last_update_time: DateTime<Utc>,
    pub bids: OrderBookSide,
    pub asks: OrderBookSide,
}

impl OrderBook {
    /// Generate an [`OrderBook`] snapshot by cloning [`Self`] after sorting each [`OrderBookSide`].
    pub fn snapshot(&mut self) -> Self {
        // Sort OrderBook & Clone
        self.bids.sort();
        self.asks.sort();
        self.clone()
    }
}

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

impl OrderBookSide {
    /// Construct a new [`Self`] with the [`Level`]s provided.
    pub fn new<Iter, L>(side: Side, levels: Iter) -> Self
    where
        Iter: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        Self {
            side,
            levels: levels.into_iter().map(L::into).collect(),
        }
    }

    /// Upsert a collection of [`Level`]s into this [`OrderBookSide`].
    pub fn upsert<Iter, L>(&mut self, levels: Iter)
    where
        Iter: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        levels
            .into_iter()
            .for_each(|level| self.upsert_single(level))
    }

    /// 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, insert new level
    /// 2b) New value is 0, log error and continue
    pub fn upsert_single<L>(&mut self, new_level: L)
    where
        L: Into<Level>,
    {
        let new_level = new_level.into();

        match self
            .levels
            .iter_mut()
            .enumerate()
            .find(|(_index, level)| level.eq_price(new_level.price))
        {
            // Scenario 1a: Level exists & new value is 0 => remove Level
            Some((index, _)) if new_level.amount == 0.0 => {
                self.levels.remove(index);
            }

            // Scenario 1b: Level exists & new value is > 0 => replace Level
            Some((_, level)) => {
                *level = new_level;
            }

            // Scenario 2a: Level does not exist & new value > 0 => insert new Level
            None if new_level.amount > 0.0 => self.levels.push(new_level),

            // Scenario 2b: Level does not exist & new value is 0 => log error & continue
            _ => {
                debug!(
                    ?new_level,
                    side = %self.side,
                    "Level to remove not found",
                );
            }
        };
    }

    /// Sort this [`OrderBookSide`] (bids are reversed).
    pub fn sort(&mut self) {
        // Sort Levels
        self.levels.sort_unstable();

        // Reverse Bids
        if let Side::Buy = self.side {
            self.levels.reverse();
        }
    }
}

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

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

impl Ord for Level {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other)
            .unwrap_or_else(|| panic!("{:?}.partial_cmp({:?}) impossible", self, other))
    }
}

impl PartialOrd for Level {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match self.price.partial_cmp(&other.price)? {
            Ordering::Equal => self.amount.partial_cmp(&other.amount),
            non_equal => Some(non_equal),
        }
    }
}

impl Eq for Level {}

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

    pub fn eq_price(&self, price: f64) -> bool {
        let diff = (price - self.price).abs();
        f64::EPSILON > diff
    }
}

impl From<(ExchangeId, Instrument, OrderBook)> for MarketIter<OrderBook> {
    fn from((exchange_id, instrument, book): (ExchangeId, Instrument, OrderBook)) -> Self {
        Self(vec![Ok(MarketEvent {
            exchange_time: book.last_update_time,
            received_time: Utc::now(),
            exchange: Exchange::from(exchange_id),
            instrument,
            kind: book,
        })])
    }
}

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

    mod order_book_side {
        use super::*;

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

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

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

        #[test]
        fn test_sort_bids() {
            struct TestCase {
                input: OrderBookSide,
                expected: OrderBookSide,
            }

            let tests = vec![
                TestCase {
                    // TC0: sorted correctly from reverse sorted
                    input: OrderBookSide::new(
                        Side::Buy,
                        vec![
                            Level::new(80, 1),
                            Level::new(90, 1),
                            Level::new(100, 1),
                            Level::new(110, 1),
                            Level::new(120, 1),
                        ],
                    ),
                    expected: OrderBookSide::new(
                        Side::Buy,
                        vec![
                            Level::new(120, 1),
                            Level::new(110, 1),
                            Level::new(100, 1),
                            Level::new(90, 1),
                            Level::new(80, 1),
                        ],
                    ),
                },
                TestCase {
                    // TC1: sorted correctly from partially sorted
                    input: OrderBookSide::new(
                        Side::Buy,
                        vec![
                            Level::new(120, 1),
                            Level::new(90, 1),
                            Level::new(80, 1),
                            Level::new(110, 1),
                            Level::new(100, 1),
                        ],
                    ),
                    expected: OrderBookSide::new(
                        Side::Buy,
                        vec![
                            Level::new(120, 1),
                            Level::new(110, 1),
                            Level::new(100, 1),
                            Level::new(90, 1),
                            Level::new(80, 1),
                        ],
                    ),
                },
                TestCase {
                    // TC1: sorted correctly from already sorted
                    input: OrderBookSide::new(
                        Side::Buy,
                        vec![
                            Level::new(120, 1),
                            Level::new(110, 1),
                            Level::new(100, 1),
                            Level::new(90, 1),
                            Level::new(80, 1),
                        ],
                    ),
                    expected: OrderBookSide::new(
                        Side::Buy,
                        vec![
                            Level::new(120, 1),
                            Level::new(110, 1),
                            Level::new(100, 1),
                            Level::new(90, 1),
                            Level::new(80, 1),
                        ],
                    ),
                },
            ];

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

        #[test]
        fn test_sort_asks() {
            struct TestCase {
                input: OrderBookSide,
                expected: OrderBookSide,
            }

            let tests = vec![
                TestCase {
                    // TC0: sorted correctly from already sorted
                    input: OrderBookSide::new(
                        Side::Sell,
                        vec![
                            Level::new(80, 1),
                            Level::new(90, 1),
                            Level::new(100, 1),
                            Level::new(110, 1),
                            Level::new(120, 1),
                        ],
                    ),
                    expected: OrderBookSide::new(
                        Side::Sell,
                        vec![
                            Level::new(80, 1),
                            Level::new(90, 1),
                            Level::new(100, 1),
                            Level::new(110, 1),
                            Level::new(120, 1),
                        ],
                    ),
                },
                TestCase {
                    // TC1: sorted correctly from partially sorted
                    input: OrderBookSide::new(
                        Side::Sell,
                        vec![
                            Level::new(120, 1),
                            Level::new(90, 1),
                            Level::new(80, 1),
                            Level::new(110, 1),
                            Level::new(100, 1),
                        ],
                    ),
                    expected: OrderBookSide::new(
                        Side::Sell,
                        vec![
                            Level::new(80, 1),
                            Level::new(90, 1),
                            Level::new(100, 1),
                            Level::new(110, 1),
                            Level::new(120, 1),
                        ],
                    ),
                },
                TestCase {
                    // TC1: sorted correctly from reverse sorted
                    input: OrderBookSide::new(
                        Side::Sell,
                        vec![
                            Level::new(120, 1),
                            Level::new(110, 1),
                            Level::new(100, 1),
                            Level::new(90, 1),
                            Level::new(80, 1),
                        ],
                    ),
                    expected: OrderBookSide::new(
                        Side::Sell,
                        vec![
                            Level::new(80, 1),
                            Level::new(90, 1),
                            Level::new(100, 1),
                            Level::new(110, 1),
                            Level::new(120, 1),
                        ],
                    ),
                },
            ];

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

    mod level {
        use super::*;

        #[test]
        fn test_partial_ord() {
            struct TestCase {
                input_one: Level,
                input_two: Level,
                expected: Option<Ordering>,
            }

            let tests = vec![
                TestCase {
                    // TC0: Input One has higher price and higher quantity -> Greater
                    input_one: Level::new(100, 100),
                    input_two: Level::new(10, 10),
                    expected: Some(Ordering::Greater),
                },
                TestCase {
                    // TC1: Input One has higher price but same quantity -> Greater
                    input_one: Level::new(100, 100),
                    input_two: Level::new(10, 100),
                    expected: Some(Ordering::Greater),
                },
                TestCase {
                    // TC2: Input One has higher price but lower quantity -> Greater
                    input_one: Level::new(100, 10),
                    input_two: Level::new(10, 100),
                    expected: Some(Ordering::Greater),
                },
                TestCase {
                    // TC3: Input One has same price and higher quantity -> Greater
                    input_one: Level::new(10, 200),
                    input_two: Level::new(10, 100),
                    expected: Some(Ordering::Greater),
                },
                TestCase {
                    // TC4: Input One has same price and same quantity -> Equal
                    input_one: Level::new(100, 100),
                    input_two: Level::new(100, 100),
                    expected: Some(Ordering::Equal),
                },
                TestCase {
                    // TC5: Input One has same price but lower quantity -> Less
                    input_one: Level::new(10, 50),
                    input_two: Level::new(10, 100),
                    expected: Some(Ordering::Less),
                },
                TestCase {
                    // TC6: Input One has lower price but higher quantity -> Less
                    input_one: Level::new(10, 100),
                    input_two: Level::new(100, 50),
                    expected: Some(Ordering::Less),
                },
                TestCase {
                    // TC7: Input One has lower price and same quantity -> Less
                    input_one: Level::new(50, 100),
                    input_two: Level::new(100, 100),
                    expected: Some(Ordering::Less),
                },
                TestCase {
                    // TC8: Input One has lower price and lower quantity -> Less
                    input_one: Level::new(50, 50),
                    input_two: Level::new(100, 100),
                    expected: Some(Ordering::Less),
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                let actual = test.input_one.partial_cmp(&test.input_two);
                match (actual, test.expected) {
                    (None, None) => {
                        // Test passed
                    }
                    (Some(actual), Some(expected)) => {
                        assert_eq!(actual, expected, "TC{} failed", index)
                    }
                    (actual, expected) => {
                        // Test failed
                        panic!("TC{index} failed because actual != expected. \nActual: {actual:?}\nExpected: {expected:?}\n");
                    }
                }
            }
        }

        #[test]
        fn test_eq_price() {
            struct TestCase {
                level: Level,
                input_level: Level,
                expected: bool,
            }

            let tests = vec![
                TestCase {
                    // TC0: Input Level has higher price
                    level: Level::new(50, 100),
                    input_level: Level::new(100, 100),
                    expected: false,
                },
                TestCase {
                    // TC1: Input Level an equal price
                    level: Level::new(50, 100),
                    input_level: Level::new(50, 100),
                    expected: true,
                },
                TestCase {
                    // TC2: Input Level has lower price
                    level: Level::new(50, 100),
                    input_level: Level::new(10, 100),
                    expected: false,
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                let actual = test.level.eq_price(test.input_level.price);
                assert_eq!(actual, test.expected, "TC{} failed", index);
            }
        }
    }
}