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
use crate::{CandleComponent, Trade};

/// This 'CandleComponent' keeps track of the volume weighted price
#[derive(Debug, Default, Clone)]
pub struct WeightedPrice {
    total_weights: f64,
    weighted_sum: f64,
}

impl CandleComponent for WeightedPrice {
    #[inline(always)]
    fn value(&self) -> f64 {
        self.weighted_sum / self.total_weights
    }

    #[inline(always)]
    fn update(&mut self, trade: &Trade) {
        self.total_weights += trade.size.abs();
        self.weighted_sum += trade.price * trade.size.abs();
    }

    #[inline(always)]
    fn reset(&mut self) {
        self.total_weights = 0.0;
        self.weighted_sum = 0.0;
    }
}

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

    #[test]
    fn weighted_price() {
        let mut m = WeightedPrice::default();
        for t in &crate::candle_components::tests::TRADES {
            m.update(t);
        }
        assert_eq!(m.value(), 102.0);
    }
}