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

/// Measures the velocity of candle creation based on the formula:
/// 1.0 / t  , where t is measured in minutes
/// The higher the velocity the faster the candle has been created
/// Assumes trade timestamps in milliseconds
#[derive(Debug, Clone)]
pub struct TimeVelocity {
    init: bool,
    init_time: i64,
    last_time: i64,
}

impl Default for TimeVelocity {
    fn default() -> Self {
        Self {
            init: true,
            init_time: 0,
            last_time: 0,
        }
    }
}

impl CandleComponent for TimeVelocity {
    #[inline(always)]
    fn value(&self) -> f64 {
        let mut elapsed_s: f64 = (self.last_time - self.init_time) as f64 / 1000.0;
        if elapsed_s < 1.0 {
            // cap elapsed_s to avoid time_velocity being infinite
            elapsed_s = 1.0;
        }
        1.0 / elapsed_s
    }

    #[inline(always)]
    fn update(&mut self, trade: &Trade) {
        if self.init {
            self.init_time = trade.timestamp;
        }
        self.last_time = trade.timestamp;
    }

    #[inline(always)]
    fn reset(&mut self) {
        self.init = true
    }
}