trading_types/
depthmap.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5use crate::{Amount, Depth, Liq, Price};
6
7#[derive(Clone, Debug, Default, Deserialize, Serialize)]
8pub struct DepthMap {
9    pub asks: HashMap<Price, Liq>,
10    pub bids: HashMap<Price, Liq>,
11}
12
13impl DepthMap {
14    pub fn new() -> Self {
15        Self {
16            asks: Default::default(),
17            bids: Default::default(),
18        }
19    }
20
21    pub fn replace(&mut self, other: Self) {
22        *self = other;
23    }
24
25    pub fn into_depth(self) -> Depth {
26        let mut d = Depth::new();
27        d.asks = self.asks.into_values().collect();
28        d.bids = self.bids.into_values().collect();
29        d.asks.sort_by(|x, y| x.p.partial_cmp(&y.p).unwrap()); // ascending
30        d.bids.sort_by(|x, y| y.p.partial_cmp(&x.p).unwrap()); // descending
31        d
32    }
33
34    pub fn update(&mut self, other: &Self) {
35        other.asks.iter().for_each(|(&p, &l)| {
36            if l.a == Amount(0.0) {
37                self.asks.remove(&p);
38            } else {
39                self.asks.entry(p).and_modify(|e| *e = l).or_insert(l);
40            }
41        });
42        other.bids.iter().for_each(|(&p, &l)| {
43            if l.a == Amount(0.0) {
44                self.bids.remove(&p);
45            } else {
46                self.bids.entry(p).and_modify(|e| *e = l).or_insert(l);
47            }
48        });
49    }
50}