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 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
use super::SubKind;
use crate::{
event::{MarketEvent, MarketIter},
exchange::ExchangeId,
};
use barter_integration::model::{instrument::Instrument, Exchange, 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, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub struct OrderBookL1 {
pub last_update_time: DateTime<Utc>,
pub best_bid: Level,
pub best_ask: Level,
}
impl OrderBookL1 {
/// 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) -> f64 {
mid_price(self.best_bid.price, self.best_ask.price)
}
/// 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) -> f64 {
volume_weighted_mid_price(self.best_bid, self.best_ask)
}
}
/// 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, Eq, PartialOrd, Ord, 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()
}
/// 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<f64> {
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<f64> {
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, PartialOrd, Ord, 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
}
}
// Todo: Add tests
/// 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: f64, best_ask_price: f64) -> f64 {
(best_bid_price + best_ask_price) / 2.0
}
/// 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) -> f64 {
((best_bid.price * best_ask.amount) + (best_ask.price * best_bid.amount))
/ (best_bid.amount + best_ask.amount)
}
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_l1 {
use super::*;
#[test]
fn test_mid_price() {
struct TestCase {
input: OrderBookL1,
expected: f64,
}
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: 150.0,
},
TestCase {
// TC1
input: OrderBookL1 {
last_update_time: Default::default(),
best_bid: Level::new(50, 1),
best_ask: Level::new(250, 999999),
},
expected: 150.0,
},
TestCase {
// TC2
input: OrderBookL1 {
last_update_time: Default::default(),
best_bid: Level::new(10, 999999),
best_ask: Level::new(250, 999999),
},
expected: 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: f64,
}
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: 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: 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: 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::*;
#[test]
fn test_mid_price() {
struct TestCase {
input: OrderBook,
expected: Option<f64>,
}
let tests = vec![
TestCase {
// TC0: no levels so 0.0 mid-price
input: OrderBook {
last_update_time: Default::default(),
bids: OrderBookSide {
side: Side::Buy,
levels: vec![],
},
asks: OrderBookSide {
side: Side::Sell,
levels: vec![],
},
},
expected: None,
},
TestCase {
// TC1: no asks in the book so take best bid price
input: OrderBook {
last_update_time: Default::default(),
bids: OrderBookSide {
side: Side::Buy,
levels: vec![Level::new(100.0, 100.0), Level::new(50.0, 100.0)],
},
asks: OrderBookSide {
side: Side::Sell,
levels: vec![],
},
},
expected: Some(100.0),
},
TestCase {
// TC2: no bids in the book so take ask price
input: OrderBook {
last_update_time: Default::default(),
bids: OrderBookSide {
side: Side::Buy,
levels: vec![],
},
asks: OrderBookSide {
side: Side::Sell,
levels: vec![Level::new(50.0, 100.0), Level::new(100.0, 100.0)],
},
},
expected: Some(50.0),
},
TestCase {
// TC3: best bid and ask amount is the same, so regular mid-price
input: OrderBook {
last_update_time: Default::default(),
bids: OrderBookSide {
side: Side::Buy,
levels: vec![Level::new(100.0, 100.0), Level::new(50.0, 100.0)],
},
asks: OrderBookSide {
side: Side::Sell,
levels: vec![Level::new(200.0, 100.0), Level::new(300.0, 100.0)],
},
},
expected: Some(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<f64>,
}
let tests = vec![
TestCase {
// TC0: no levels so 0.0 mid-price
input: OrderBook {
last_update_time: Default::default(),
bids: OrderBookSide {
side: Side::Buy,
levels: vec![],
},
asks: OrderBookSide {
side: Side::Sell,
levels: vec![],
},
},
expected: None,
},
TestCase {
// TC1: no asks in the book so take best bid price
input: OrderBook {
last_update_time: Default::default(),
bids: OrderBookSide {
side: Side::Buy,
levels: vec![Level::new(100.0, 100.0), Level::new(50.0, 100.0)],
},
asks: OrderBookSide {
side: Side::Sell,
levels: vec![],
},
},
expected: Some(100.0),
},
TestCase {
// TC2: no bids in the book so take ask price
input: OrderBook {
last_update_time: Default::default(),
bids: OrderBookSide {
side: Side::Buy,
levels: vec![],
},
asks: OrderBookSide {
side: Side::Sell,
levels: vec![Level::new(50.0, 100.0), Level::new(100.0, 100.0)],
},
},
expected: Some(50.0),
},
TestCase {
// TC3: best bid and ask amount is the same, so regular mid-price
input: OrderBook {
last_update_time: Default::default(),
bids: OrderBookSide {
side: Side::Buy,
levels: vec![Level::new(100.0, 100.0), Level::new(50.0, 100.0)],
},
asks: OrderBookSide {
side: Side::Sell,
levels: vec![Level::new(200.0, 100.0), Level::new(300.0, 100.0)],
},
},
expected: Some(150.0),
},
TestCase {
// TC4: valid volume weighted mid-price
input: OrderBook {
last_update_time: Default::default(),
bids: OrderBookSide {
side: Side::Buy,
levels: vec![Level::new(100.0, 3000.0), Level::new(50.0, 100.0)],
},
asks: OrderBookSide {
side: Side::Sell,
levels: vec![Level::new(200.0, 1000.0), Level::new(300.0, 100.0)],
},
},
expected: Some(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::*;
#[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);
}
}
}
}