Skip to main content

quantwave_core/indicators/
cycle.rs

1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::traits::Next;
3
4talib_1_in_1_out!(HT_DCPERIOD, talib_rs::cycle::ht_dcperiod);
5impl Default for HT_DCPERIOD {
6    fn default() -> Self {
7        Self::new()
8    }
9}
10talib_1_in_2_out!(HT_PHASOR, talib_rs::cycle::ht_phasor);
11impl Default for HT_PHASOR {
12    fn default() -> Self {
13        Self::new()
14    }
15}
16talib_1_in_1_out!(HT_DCPHASE, talib_rs::cycle::ht_dcphase);
17impl Default for HT_DCPHASE {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22talib_1_in_2_out!(HT_SINE, talib_rs::cycle::ht_sine);
23impl Default for HT_SINE {
24    fn default() -> Self {
25        Self::new()
26    }
27}
28talib_1_in_1_out_i32!(HT_TRENDMODE, talib_rs::cycle::ht_trendmode);
29impl Default for HT_TRENDMODE {
30    fn default() -> Self {
31        Self::new()
32    }
33}
34
35pub const HT_DCPERIOD_METADATA: IndicatorMetadata = IndicatorMetadata {
36    name: "Hilbert Transform - Dominant Cycle Period (HT_DCPERIOD)",
37    description: "Identifies the period of the dominant cycle in the price data using the Hilbert Transform.",
38    usage: "Use to dynamically adjust the lookback periods of other indicators (e.g., adaptive moving averages). Knowing the current dominant cycle length allows for more accurate smoothing and trend detection.",
39    keywords: &["cycle", "hilbert", "adaptive", "dsp"],
40    ehlers_summary: "John Ehlers popularized the use of the Hilbert Transform to identify the dominant cycle in financial time series. The DCPERIOD indicator tracks the length of this cycle in bars, providing a crucial parameter for creating market-responsive technical indicators that adapt to changing volatility. — Rocket Science for Traders",
41    params: &[],
42    formula_source: "https://www.tradingview.com/support/solutions/43000502011-hilbert-transform-dominant-cycle-period-ht-dcperiod/",
43    formula_latex: r#"
44\[
45\text{DCPERIOD}_t = \text{Recalculated Dominant Cycle using Hilbert Transform}
46\]
47"#,
48    gold_standard_file: "ht_dcperiod.json",
49    category: "Ehlers DSP",
50};
51
52pub const HT_DCPHASE_METADATA: IndicatorMetadata = IndicatorMetadata {
53    name: "Hilbert Transform - Dominant Cycle Phase (HT_DCPHASE)",
54    description: "Calculates the phase angle (0 to 360 degrees) of the dominant cycle identified by the Hilbert Transform.",
55    usage: "Use to identify the current position within a market cycle. It is the core component for generating the Hilbert Sine Wave indicator, which signals trend vs. cycle regimes.",
56    keywords: &["cycle", "hilbert", "phase", "dsp"],
57    ehlers_summary: "The Dominant Cycle Phase represents the instantaneous position within a detected cycle. By measuring the phase angle, traders can determine if the market is at a peak, trough, or mid-cycle, enabling more precise timing for entry and exit signals. — Rocket Science for Traders",
58    params: &[],
59    formula_source: "https://www.tradingview.com/support/solutions/43000502010-hilbert-transform-dominant-cycle-phase-ht-dcphase/",
60    formula_latex: r#"
61\[
62Phase = \arctan\left(\frac{\text{Quadrature}}{\text{InPhase}}\right)
63\]
64"#,
65    gold_standard_file: "ht_dcphase.json",
66    category: "Ehlers DSP",
67};
68
69pub const HT_PHASOR_METADATA: IndicatorMetadata = IndicatorMetadata {
70    name: "Hilbert Transform - Phasor Components (HT_PHASOR)",
71    description: "Outputs the In-Phase and Quadrature components of the signal, which are used to calculate phase and amplitude.",
72    usage: "Use as building blocks for custom DSP indicators. The In-Phase component is the signal itself, while the Quadrature component is shifted by 90 degrees.",
73    keywords: &["cycle", "hilbert", "phasor", "dsp"],
74    ehlers_summary: "The Phasor components (In-Phase and Quadrature) are the fundamental outputs of the Hilbert Transform. They allow for the decomposition of a signal into its vector representation, which is essential for advanced cycle analysis and the creation of lag-free filters. — Rocket Science for Traders",
75    params: &[],
76    formula_source: "https://www.tradingview.com/support/solutions/43000502012-hilbert-transform-phasor-components-ht-phasor/",
77    formula_latex: r#"
78\[
79\text{Result} = (InPhase, Quadrature)
80\]
81"#,
82    gold_standard_file: "ht_phasor.json",
83    category: "Ehlers DSP",
84};
85
86pub const HT_SINE_METADATA: IndicatorMetadata = IndicatorMetadata {
87    name: "Hilbert Transform - Sine Wave (HT_SINE)",
88    description: "An indicator that plots a sine wave and a lead-sine wave (shifted by 45 degrees) to identify cyclical turns.",
89    usage: "Use to identify cycle turning points and trend regimes. When the two waves are separated and rhythmic, the market is in a cycle; when they are compressed or crossover erratically, the market is in a trend.",
90    keywords: &["cycle", "hilbert", "sine", "dsp"],
91    ehlers_summary: "The Hilbert Sine Wave is one of John Ehlers' most famous contributions. It provides a clear visual indication of market cycles. Crossovers of the Sine and Lead-Sine waves provide high-probability entry points in ranging markets while identifying when a strong trend has taken over. — Rocket Science for Traders",
92    params: &[],
93    formula_source: "https://www.tradingview.com/support/solutions/43000502013-hilbert-transform-sine-wave-ht-sine/",
94    formula_latex: r#"
95\[
96Sine = \sin(Phase) \\ LeadSine = \sin(Phase + 45^\circ)
97\]
98"#,
99    gold_standard_file: "ht_sine.json",
100    category: "Ehlers DSP",
101};
102
103pub const HT_TRENDMODE_METADATA: IndicatorMetadata = IndicatorMetadata {
104    name: "Hilbert Transform - Trend vs. Cycle Mode (HT_TRENDMODE)",
105    description: "A binary indicator that determines if the market is currently in a trending state (1) or a cyclical state (0).",
106    usage: "Use as a master filter for strategy selection. Deploy trend-following tools when TRENDMODE is 1, and mean-reversion tools when TRENDMODE is 0.",
107    keywords: &["cycle", "trend", "hilbert", "regime-detection", "dsp"],
108    ehlers_summary: "Determining the current market regime is the 'holy grail' of technical analysis. The HT_TRENDMODE indicator uses the rate of change of the dominant cycle phase to distinguish between trending and ranging price action, allowing traders to avoid 'whipsaws' in non-conducive environments. — Rocket Science for Traders",
109    params: &[],
110    formula_source: "https://www.tradingview.com/support/solutions/43000502014-hilbert-transform-trend-vs-cycle-mode-ht-trendmode/",
111    formula_latex: r#"
112\[
113\text{TRENDMODE} = \begin{cases} 1 & \text{if trend detected} \\ 0 & \text{if cycle detected} \end{cases}
114\]
115"#,
116    gold_standard_file: "ht_trendmode.json",
117    category: "Ehlers DSP",
118};
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use crate::traits::Next;
124    use proptest::prelude::*;
125
126    proptest! {
127        #[test]
128        fn test_ht_dcperiod_parity(input in prop::collection::vec(0.1..100.0, 1..100)) {
129            let mut ht = HT_DCPERIOD::new();
130            let streaming_results: Vec<f64> = input.iter().map(|&x| ht.next(x)).collect();
131            let batch_results = talib_rs::cycle::ht_dcperiod(&input).unwrap_or_else(|_| vec![f64::NAN; input.len()]);
132
133            for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
134                if s.is_nan() {
135                    assert!(b.is_nan());
136                } else {
137                    approx::assert_relative_eq!(s, b, epsilon = 1e-6);
138                }
139            }
140        }
141
142        #[test]
143        fn test_ht_phasor_parity(input in prop::collection::vec(0.1..100.0, 1..100)) {
144            let mut ht = HT_PHASOR::new();
145            let streaming_results: Vec<(f64, f64)> = input.iter().map(|&x| ht.next(x)).collect();
146            let (b_inphase, b_quadrature) = talib_rs::cycle::ht_phasor(&input).unwrap_or_else(|_| {
147                (vec![f64::NAN; input.len()], vec![f64::NAN; input.len()])
148            });
149
150            for (i, (s_in, s_quad)) in streaming_results.into_iter().enumerate() {
151                if s_in.is_nan() {
152                    assert!(b_inphase[i].is_nan());
153                } else {
154                    approx::assert_relative_eq!(s_in, b_inphase[i], epsilon = 1e-6);
155                }
156                if s_quad.is_nan() {
157                    assert!(b_quadrature[i].is_nan());
158                } else {
159                    approx::assert_relative_eq!(s_quad, b_quadrature[i], epsilon = 1e-6);
160                }
161            }
162        }
163
164        #[test]
165        fn test_ht_trendmode_parity(input in prop::collection::vec(0.1..100.0, 1..100)) {
166            let mut ht = HT_TRENDMODE::new();
167            let streaming_results: Vec<f64> = input.iter().map(|&x| ht.next(x)).collect();
168            let batch_results = talib_rs::cycle::ht_trendmode(&input).unwrap_or_else(|_| vec![0; input.len()]);
169
170            for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
171                assert_eq!(*s as i32, *b);
172            }
173        }
174    }
175}