Skip to main content

wickra_core/indicators/
fib_confluence.rs

1//! Fibonacci Confluence — the strongest retracement cluster across recent legs.
2
3use crate::indicators::pattern_swing::{
4    approx_equal, SwingTracker, LEVEL_TOLERANCE, SWING_THRESHOLD,
5};
6use crate::ohlcv::Candle;
7use crate::traits::Indicator;
8
9/// How many recent pivots to consider; six pivots yield up to five legs.
10const PIVOT_HISTORY: usize = 6;
11
12/// The retracement ratios contributed by each leg to the confluence search.
13const RATIOS: [f64; 3] = [0.382, 0.5, 0.618];
14
15/// The strongest Fibonacci confluence zone found across recent swing legs.
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub struct FibConfluenceOutput {
18    /// Mean price of the densest cluster of retracement levels.
19    pub price: f64,
20    /// Number of retracement levels that fall inside the cluster (its strength).
21    pub strength: f64,
22}
23
24/// Fibonacci Confluence (`FibConfluence`).
25///
26/// Computes the 38.2% / 50% / 61.8% retracement prices of every leg among the
27/// last six confirmed pivots, then reports the densest price cluster — where
28/// levels from different legs stack up, the zone the market is most likely to
29/// react to. `price` is the cluster mean; `strength` is how many levels it
30/// gathers.
31///
32/// Parameter-free; construction is infallible. Returns `None` until at least two
33/// legs (three pivots) exist.
34///
35/// See `crates/wickra-core/src/indicators/fib_confluence.rs`.
36/// # Example
37///
38/// ```
39/// use wickra_core::{FibConfluence, Candle, Indicator};
40///
41/// let mut indicator = FibConfluence::new();
42/// // `None` during warmup, then `Some(_)` once enough bars are seen.
43/// let mut out = None;
44/// for i in 0..40i64 {
45///     let p = 100.0 + (i as f64 * 0.4).sin() * 5.0;
46///     let candle = Candle::new(p, p + 1.5, p - 1.5, p + 0.3, 1_000.0, i).unwrap();
47///     out = indicator.update(candle);
48/// }
49/// let _ = out;
50/// ```
51#[derive(Debug, Clone)]
52pub struct FibConfluence {
53    swing: SwingTracker,
54}
55
56impl FibConfluence {
57    /// Construct a new Fibonacci Confluence tracker.
58    #[must_use]
59    pub const fn new() -> Self {
60        Self {
61            swing: SwingTracker::new(SWING_THRESHOLD, PIVOT_HISTORY),
62        }
63    }
64
65    fn confluence(&self) -> Option<FibConfluenceOutput> {
66        let pivots = self.swing.pivots();
67        if pivots.len() < 3 {
68            return None;
69        }
70        let levels: Vec<f64> = pivots
71            .windows(2)
72            .flat_map(|leg| {
73                let (start, end) = (leg[0].price, leg[1].price);
74                RATIOS.map(|r| end + r * (start - end))
75            })
76            .collect();
77        // The `len < 3` guard guarantees at least two legs, hence a non-empty
78        // level set, so `max_by` always yields a cluster.
79        let (count, total) = levels
80            .iter()
81            .map(|&center| {
82                let members: Vec<f64> = levels
83                    .iter()
84                    .copied()
85                    .filter(|&x| approx_equal(x, center, LEVEL_TOLERANCE))
86                    .collect();
87                (members.len(), members.iter().sum::<f64>())
88            })
89            .max_by(|a, b| a.0.cmp(&b.0))
90            .expect("at least two legs guarantee a non-empty level set");
91        Some(FibConfluenceOutput {
92            price: total / count as f64,
93            strength: count as f64,
94        })
95    }
96}
97
98impl Default for FibConfluence {
99    fn default() -> Self {
100        Self::new()
101    }
102}
103
104impl Indicator for FibConfluence {
105    type Input = Candle;
106    type Output = FibConfluenceOutput;
107
108    #[inline]
109    fn update(&mut self, candle: Candle) -> Option<FibConfluenceOutput> {
110        self.swing.update(candle);
111        self.confluence()
112    }
113
114    fn reset(&mut self) {
115        self.swing.reset();
116    }
117
118    #[inline]
119    fn warmup_period(&self) -> usize {
120        3
121    }
122
123    #[inline]
124    fn is_ready(&self) -> bool {
125        self.swing.pivots().len() >= 3
126    }
127
128    #[inline]
129    fn name(&self) -> &'static str {
130        "FibConfluence"
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use crate::indicators::pattern_swing::candles_for_pivots;
138    use crate::traits::BatchExt;
139    use approx::assert_relative_eq;
140
141    #[test]
142    fn accessors_and_metadata() {
143        let indicator = FibConfluence::new();
144        assert_eq!(indicator.name(), "FibConfluence");
145        assert_eq!(indicator.warmup_period(), 3);
146        assert!(!indicator.is_ready());
147        assert!(!FibConfluence::default().is_ready());
148    }
149
150    #[test]
151    fn no_output_before_two_legs() {
152        let mut indicator = FibConfluence::new();
153        let outputs: Vec<_> = candles_for_pivots(&[200.0, 100.0])
154            .into_iter()
155            .map(|c| indicator.update(c))
156            .collect();
157        assert!(outputs.iter().all(Option::is_none));
158        assert!(!indicator.is_ready());
159    }
160
161    #[test]
162    fn picks_the_densest_cluster() {
163        // Legs 200->100 and 100->160. The 38.2% of each (138.2 and ~137.08)
164        // sit within 3% of each other and form the densest cluster (strength 2).
165        let mut indicator = FibConfluence::new();
166        let mut last = None;
167        for candle in candles_for_pivots(&[200.0, 100.0, 160.0]) {
168            last = indicator.update(candle);
169        }
170        let v = last.unwrap();
171        assert!(indicator.is_ready());
172        assert_relative_eq!(v.strength, 2.0);
173        let want = (138.2 + (160.0 + 0.382 * (100.0 - 160.0))) / 2.0;
174        assert_relative_eq!(v.price, want, epsilon = 1e-9);
175    }
176
177    #[test]
178    fn reset_clears_state() {
179        let mut indicator = FibConfluence::new();
180        for candle in candles_for_pivots(&[200.0, 100.0, 160.0]) {
181            let _ = indicator.update(candle);
182        }
183        assert!(indicator.is_ready());
184        indicator.reset();
185        assert!(!indicator.is_ready());
186        let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
187        assert!(indicator.update(c).is_none());
188    }
189
190    #[test]
191    fn batch_equals_streaming() {
192        let candles = candles_for_pivots(&[200.0, 100.0, 160.0, 120.0]);
193        let mut a = FibConfluence::new();
194        let mut b = FibConfluence::new();
195        assert_eq!(
196            a.batch(&candles),
197            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
198        );
199    }
200}