kiteticker_async_manager/models/
depth.rs

1use crate::Exchange;
2
3use crate::parser::{price, value, value_short};
4
5#[derive(Debug, Clone, Default, PartialEq)]
6///
7/// Market depth packet structure
8///
9pub struct Depth {
10  pub buy: [DepthItem; 5],
11  pub sell: [DepthItem; 5],
12}
13
14impl Depth {
15  pub(crate) fn from(input: &[u8], exchange: &Exchange) -> Option<Self> {
16    if let Some(bs) = input.get(0..120) {
17      let parse_depth_item = |v: &[u8], start: usize| {
18        v.get(start..start + 10)
19          .and_then(|xs| DepthItem::from(xs, exchange))
20          .unwrap_or_default()
21      };
22      let mut depth = Depth::default();
23      for i in 0..5 {
24        let start = i * 12;
25        depth.buy[i] = parse_depth_item(bs, start)
26      }
27      for i in 0..5 {
28        let start = 60 + i * 12;
29        depth.sell[i] = parse_depth_item(bs, start);
30      }
31
32      Some(depth)
33    } else {
34      None
35    }
36  }
37}
38
39#[derive(Debug, Clone, Default, PartialEq)]
40///
41/// Structure for each market depth entry
42///
43pub struct DepthItem {
44  pub qty: u32,
45  pub price: f64,
46  pub orders: u16,
47}
48
49impl DepthItem {
50  pub fn from(input: &[u8], exchange: &Exchange) -> Option<Self> {
51    if let Some(bs) = input.get(0..10) {
52      Some(DepthItem {
53        qty: value(&bs[0..=3]).unwrap(),
54        price: price(&bs[4..=7], exchange).unwrap(),
55        orders: value_short(&bs[8..=9]).unwrap(),
56      })
57    } else {
58      None
59    }
60  }
61}