Skip to main content

quantwave_core/indicators/
hilbert_transform.rs

1use std::collections::VecDeque;
2
3/// Hilbert Transform 7-tap FIR Filter
4///
5/// Based on John Ehlers' "Rocket Science for Traders".
6/// This filter provides a 90-degree phase shift for the input signal.
7#[derive(Debug, Clone)]
8pub struct HilbertFIR {
9    window: VecDeque<f64>,
10}
11
12impl HilbertFIR {
13    pub fn new() -> Self {
14        Self {
15            window: VecDeque::from(vec![0.0; 7]),
16        }
17    }
18
19    pub fn next(&mut self, input: f64, period: f64) -> f64 {
20        self.window.pop_back();
21        self.window.push_front(input);
22
23        // FIR coefficients for 90-degree phase shift
24        (0.0962 * self.window[0] 
25            + 0.5769 * self.window[2] 
26            - 0.5769 * self.window[4] 
27            - 0.0962 * self.window[6]) 
28            * (0.075 * period + 0.54)
29    }
30}
31
32impl Default for HilbertFIR {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38/// A simpler 4-tap WMA often used in Ehlers' smoothing
39#[derive(Debug, Clone)]
40pub struct EhlersWma4 {
41    window: VecDeque<f64>,
42}
43
44impl EhlersWma4 {
45    pub fn new() -> Self {
46        Self {
47            window: VecDeque::from(vec![0.0; 4]),
48        }
49    }
50
51    pub fn next(&mut self, input: f64) -> f64 {
52        self.window.pop_back();
53        self.window.push_front(input);
54        
55        (4.0 * self.window[0] 
56            + 3.0 * self.window[1] 
57            + 2.0 * self.window[2] 
58            + self.window[3]) / 10.0
59    }
60}
61
62impl Default for EhlersWma4 {
63    fn default() -> Self {
64        Self::new()
65    }
66}