candlestick_rs/
candle_stream.rs

1use crate::CandleStick;
2
3const SERIES_SIZE: usize = 5;
4
5/// The `CandleStream` provides detection capabilities for powerful multi-candle patterns
6///
7/// - **Reversal Patterns**: Engulfing, Harami, Morning/Evening Stars, Doji Stars
8/// - **Continuation Patterns**: Three White Soldiers, Three Black Crows
9/// - **Top/Bottom Formations**: Dark Cloud Cover and other significant reversal signals
10///
11/// These formations often provide stronger trading signals than single-candle patterns,
12/// offering insights into potential trend reversals, continuations, or exhaustion points.
13/// Each pattern detection method includes detailed documentation about market context
14/// and trading significance.
15///
16/// # Examples
17///
18/// ```
19/// use candlestick_rs::{CandleStick, CandleStream};
20///
21/// // Create a new stream and add candles
22/// let candle1 = (100.0, 105.0, 99.0, 104.0);
23/// let candle2 = (104.5, 110.0, 104.0, 109.0);
24///
25/// let mut stream = CandleStream::new();
26/// stream.push(&candle1).push(&candle2);
27///
28/// // Check for patterns
29/// if stream.is_bullish_engulfing() {
30///     println!("Bullish engulfing pattern detected!");
31/// }
32/// ```
33
34#[derive(Debug)]
35pub struct CandleStream<'s, T> {
36    series: [Option<&'s T>; SERIES_SIZE],
37    idx: usize,
38}
39
40impl<'s, T> CandleStream<'s, T> {
41    /// Returns a new candle series
42    pub fn new() -> Self {
43        Self::default()
44    }
45
46    // Returns the candle at the given index
47    fn at(&self, idx: usize) -> Option<&T> {
48        match idx < SERIES_SIZE {
49            true => self.series[idx],
50            false => None,
51        }
52    }
53
54    // Fetches reference to the current candle
55    fn get(&self) -> Option<&T> {
56        self.at(self.idx.checked_sub(1)?)
57    }
58
59    // Returns the previous candle
60    fn prev(&self, n: usize) -> Option<&T> {
61        self.at(self.idx.checked_sub(n + 1)?)
62    }
63
64    /// Pushes a candle to the series
65    pub fn push(&mut self, candle: &'s T) -> &mut Self {
66        self.series[self.idx % SERIES_SIZE] = Some(candle);
67        self.idx = (self.idx + 1) % SERIES_SIZE;
68        self
69    }
70}
71
72impl<T: CandleStick> CandleStream<'_, T> {
73    /// Identifies a Bullish Doji Star pattern, a potential reversal signal in downtrends.
74    ///
75    /// This two-candle pattern occurs when a bearish candle is followed by a Doji that gaps below
76    /// the prior candle's low. The Doji represents market indecision after a dominant downtrend.
77    ///
78    /// **Trading Significance**:
79    /// - Signals potential exhaustion of selling pressure
80    /// - Often precedes bullish price movements when confirmed
81    /// - Traders typically wait for a third bullish candle before entering long positions
82    /// - Most effective when appearing at support levels or after extended downtrends
83    ///
84    /// # Example
85    /// ```
86    /// use candlestick_rs::CandleStream;
87    /// let prev = (52.0, 52.5, 48.0, 48.5);      
88    /// let curr = (47.0, 47.5, 46.8, 47.0);
89    /// let mut series = CandleStream::new();
90    /// assert!(series.push(&prev).push(&curr).is_bullish_doji_star());
91    /// ```
92    pub fn is_bullish_doji_star(&self) -> bool {
93        self.get()
94            .zip(self.prev(1))
95            .is_some_and(|(c, p)| p.is_bearish() && c.is_doji() && c.high() < p.low())
96    }
97
98    /// Identifies a Bearish Doji Star pattern, a potential reversal signal in uptrends.
99    ///
100    /// This two-candle pattern occurs when a bullish candle is followed by a Doji that gaps above
101    /// the prior candle's high. The Doji represents market indecision after a dominant uptrend.
102    ///
103    /// **Trading Significance**:
104    /// - Signals potential exhaustion of buying pressure
105    /// - Often precedes bearish price movements when confirmed
106    /// - Traders typically wait for a third bearish candle before entering short positions
107    /// - Most effective when appearing at resistance levels or after extended uptrends
108    ///
109    /// # Example
110    /// ```
111    /// use candlestick_rs::CandleStream;
112    /// let prev = (48.0, 52.5, 47.8, 52.0);
113    /// let curr = (52.6, 53.2, 52.6, 52.6);
114    /// let mut series = CandleStream::new();
115    /// assert!(series.push(&prev).push(&curr).is_bearish_doji_star());
116    /// ```
117    pub fn is_bearish_doji_star(&self) -> bool {
118        self.get()
119            .zip(self.prev(1))
120            .is_some_and(|(c, p)| p.is_bullish() && c.is_doji() && c.low() > p.high())
121    }
122
123    ///
124    /// Identifies a Bullish Engulfing pattern, a strong reversal signal at the end of downtrends.
125    ///
126    /// This two-candle pattern occurs when a bearish candle is completely engulfed by a larger bullish candle
127    /// (open lower than prior close, close higher than prior open). It shows buyers overwhelmingly defeating sellers.
128    ///
129    /// **Trading Significance**:
130    /// - Indicates strong shift from selling to buying pressure
131    /// - More reliable than single-candle patterns due to the decisive price action
132    /// - Often used as an immediate entry signal, especially when volume increases
133    /// - Higher reliability when occurring at support zones or after extended downtrends
134    ///
135    /// # Example
136    /// ```
137    /// use candlestick_rs::CandleStream;
138    /// let prev = (101.0, 102.0, 99.5, 100.5); // bearish: open > close
139    /// let curr = (99.0, 103.0, 98.5, 102.5);  // bullish: open < close, engulfs prev body
140    /// let mut series = CandleStream::new();
141    /// assert!(series.push(&prev).push(&curr).is_bullish_engulfing());
142    /// ```
143    pub fn is_bullish_engulfing(&self) -> bool {
144        self.get().zip(self.prev(1)).is_some_and(|(c, p)| {
145            p.is_bearish() && c.is_bullish() && c.open() < p.close() && c.close() > p.open()
146        })
147    }
148
149    /// Identifies a Bearish Engulfing pattern, a strong reversal signal at the end of uptrends.
150    ///
151    /// This two-candle pattern occurs when a bullish candle is completely engulfed by a larger bearish candle
152    /// (open higher than prior close, close lower than prior open). It shows sellers overwhelmingly defeating buyers.
153    ///
154    /// **Trading Significance**:
155    /// - Indicates strong shift from buying to selling pressure
156    /// - More reliable than single-candle patterns due to the decisive price action
157    /// - Often used as an immediate exit signal for longs or entry for shorts
158    /// - Higher reliability when occurring at resistance zones or after extended uptrends
159    ///
160    /// # Example
161    /// ```
162    /// use candlestick_rs::CandleStream;
163    /// let prev = (99.0, 100.5, 98.5, 100.0);  // bullish: open < close
164    /// let curr = (101.5, 102.0, 97.0, 98.5);  // bearish: open > close, engulfs prev body
165    /// let mut series = CandleStream::new();
166    /// assert!(series.push(&prev).push(&curr).is_bearish_engulfing());
167    /// ```
168    pub fn is_bearish_engulfing(&self) -> bool {
169        self.get().zip(self.prev(1)).is_some_and(|(c, p)| {
170            p.is_bullish() && c.is_bearish() && c.open() > p.close() && c.close() < p.open()
171        })
172    }
173
174    /// Identifies a Bullish Harami pattern, indicating potential reversal or continuation in downtrends.
175    ///
176    /// This two-candle pattern occurs when a small bullish candle is contained within the trading range of a
177    /// preceding larger bearish candle. The Japanese word "harami" means pregnant, describing the visual appearance.
178    ///
179    /// **Trading Significance**:
180    /// - Signals indecision after a bearish move and possible loss of downward momentum
181    /// - Less powerful than engulfing patterns but still a notable reversal signal
182    /// - Traders typically wait for additional confirmation before entering long positions
183    /// - Part of contingent trading strategies where position size increases after confirmation
184    ///
185    /// # Example
186    /// ```
187    /// use candlestick_rs::CandleStream;
188    /// let prev = (129.0, 130.0, 124.0, 125.0);
189    /// let curr = (125.2, 127.0, 124.8, 126.5);
190    /// let mut series = CandleStream::new();
191    /// assert!(series.push(&prev).push(&curr).is_bullish_harami());
192    /// ```
193    pub fn is_bullish_harami(&self) -> bool {
194        self.get().zip(self.prev(1)).is_some_and(|(c, p)| {
195            p.is_bearish() && c.is_bullish() && c.open() > p.close() && c.close() < p.open()
196        })
197    }
198
199    /// Identifies a Bearish Harami pattern, indicating potential reversal or continuation in uptrends.
200    ///
201    /// This two-candle pattern occurs when a small bearish candle is contained within the trading range of a
202    /// preceding larger bullish candle. The Japanese word "harami" means pregnant, describing the visual appearance.
203    ///
204    /// **Trading Significance**:
205    /// - Signals indecision after a bullish move and possible loss of upward momentum
206    /// - Less powerful than engulfing patterns but still a notable reversal warning
207    /// - Often used to protect profits on long positions or tighten stop losses
208    /// - Sometimes precedes a period of consolidation rather than immediate reversal
209    ///
210    /// # Example
211    /// ```
212    /// use candlestick_rs::CandleStream;
213    /// let prev = (124.0, 129.0, 122.0, 127.0);
214    /// let curr = (126.9, 129.7, 125.0, 124.8);
215    /// let mut series = CandleStream::new();
216    /// assert!(series.push(&prev).push(&curr).is_bearish_harami());
217    /// ```
218    pub fn is_bearish_harami(&self) -> bool {
219        self.get().zip(self.prev(1)).is_some_and(|(c, p)| {
220            p.is_bullish() && c.is_bearish() && c.open() < p.close() && c.close() > p.open()
221        })
222    }
223
224    /// Identifies a Dark Cloud Cover pattern, a bearish reversal signal in uptrends.
225    ///
226    /// This two-candle pattern occurs when a bearish candle opens above the prior bullish candle's close
227    /// but closes below the midpoint of the prior candle's body. It shows rejection of higher prices.
228    ///
229    /// **Trading Significance**:
230    /// - Signals strong selling pressure after an uptrend
231    /// - More significant when the bearish candle closes deep into the prior bullish candle
232    /// - Often used by traders to exit long positions or initiate short positions
233    /// - Particularly effective when appearing at historical resistance levels
234    ///
235    /// # Example
236    /// ```
237    /// use candlestick_rs::CandleStream;
238    /// let prev = (100.0, 105.0, 99.5, 104.5);
239    /// let curr = (105.5, 106.0, 102.0, 101.5);
240    /// let mut series = CandleStream::new();
241    /// assert!(series.push(&prev).push(&curr).is_dark_cloud_cover());
242    /// ```
243    pub fn is_dark_cloud_cover(&self) -> bool {
244        self.get().zip(self.prev(1)).is_some_and(|(c, p)| {
245            c.is_bearish()
246                && p.is_bullish()
247                && c.open() > p.close()
248                && c.close() < T::midpoint(p.open(), p.close())
249        })
250    }
251
252    /// Identifies an Evening Star pattern, a bearish reversal formation at market tops.
253    ///
254    /// This three-candle pattern consists of:
255    /// 1. A strong bullish candle extending the uptrend
256    /// 2. A small-bodied candle showing indecision (star), often with a gap
257    /// 3. A bearish candle closing well into the first candle's body
258    ///
259    /// **Trading Significance**:
260    /// - Represents a complete shift from bullish to bearish sentiment
261    /// - Considered one of the most reliable bearish reversal patterns
262    /// - Traders often exit longs or enter shorts when the third candle confirms
263    /// - Effectiveness increases with the size of the third bearish candle
264    ///
265    /// # Example
266    /// ```
267    /// use candlestick_rs::CandleStream;
268    /// let prev2 = (100.0, 106.0, 99.5, 105.5);
269    /// let prev1 = (106.2, 107.0, 105.8, 106.5);
270    /// let curr = (105.5, 106.0, 102.0, 101.5);
271    /// let mut series = CandleStream::new();
272    /// assert!(series.push(&prev2).push(&prev1).push(&curr).is_evening_star());
273    /// ```
274    pub fn is_evening_star(&self) -> bool {
275        self.get()
276            .zip(self.prev(1))
277            .zip(self.prev(2))
278            .is_some_and(|((c, p1), p2)| {
279                p2.is_bullish()
280                    && (p1.is_doji() || p1.open() < p1.close())
281                    && c.is_bearish()
282                    && c.close() < T::midpoint(p2.open(), p2.close())
283            })
284    }
285
286    /// Identifies an Evening Star Doji variant, a strong bearish reversal pattern at market tops.
287    ///
288    /// This three-candle pattern is similar to the Evening Star, but the middle candle is specifically
289    /// a Doji (open ≈ close), emphasizing the perfect equilibrium between buyers and sellers before
290    /// bears take control.
291    ///
292    /// **Trading Significance**:
293    /// - Considered stronger than the standard Evening Star due to the Doji's stronger indecision signal
294    /// - Often precedes significant price declines when confirmed by the third candle
295    /// - Used by traders as a high-probability signal to exit long positions
296    /// - Particularly powerful when occurring after an extended uptrend with high momentum
297    ///
298    /// # Example
299    /// ```
300    /// use candlestick_rs::CandleStream;
301    /// let prev2 =  (100.0, 106.0, 99.5, 105.5);
302    /// let prev1 =  (106.1, 107.0, 105.8, 106.1);
303    /// let curr = (105.0, 105.2, 99.8, 101.0);
304    /// let mut series = CandleStream::new();
305    /// assert!(series.push(&prev2).push(&prev1).push(&curr).is_evening_star_doji());
306    /// ```
307    pub fn is_evening_star_doji(&self) -> bool {
308        self.get()
309            .zip(self.prev(1))
310            .zip(self.prev(2))
311            .is_some_and(|((c, p1), p2)| {
312                p2.is_bullish()
313                    && p1.is_doji() & c.is_bearish()
314                    && c.close() < T::midpoint(p2.open(), p2.close())
315            })
316    }
317
318    /// Identifies a Morning Star pattern, a bullish reversal formation at market bottoms.
319    ///
320    /// This three-candle pattern consists of:
321    /// 1. A strong bearish candle extending the downtrend
322    /// 2. A small-bodied candle showing indecision (star), often with a gap
323    /// 3. A bullish candle closing well into the first candle's body
324    ///
325    /// **Trading Significance**:
326    /// - Represents a complete shift from bearish to bullish sentiment
327    /// - Considered one of the most reliable bullish reversal patterns
328    /// - Traders often enter long positions when the third candle confirms
329    /// - Effectiveness increases with the size of the third bullish candle and supporting volume
330    ///
331    /// # Example
332    /// ```
333    /// use candlestick_rs::CandleStream;
334    /// let prev2 = (52.0, 52.5, 48.0, 48.5);
335    /// let prev1 = (48.2, 48.9, 47.5, 48.3);
336    /// let curr = (48.7, 51.5, 48.5, 51.2);   
337    /// let mut series = CandleStream::new();
338    /// assert!(series.push(&prev2).push(&prev1).push(&curr).is_morning_star());
339    /// ```
340    pub fn is_morning_star(&self) -> bool {
341        self.get()
342            .zip(self.prev(1))
343            .zip(self.prev(2))
344            .is_some_and(|((c, p1), p2)| {
345                p2.is_bearish()
346                    && (p1.is_doji() || p1.open() < p1.close())
347                    && c.is_bullish()
348                    && c.close() > T::midpoint(p2.open(), p2.close())
349            })
350    }
351
352    /// Identifies a Morning Star Doji variant, a strong bullish reversal pattern at market bottoms.
353    ///
354    /// This three-candle pattern is similar to the Morning Star, but the middle candle is specifically
355    /// a Doji (open ≈ close), emphasizing the perfect equilibrium between buyers and sellers before
356    /// bulls take control.
357    ///
358    /// **Trading Significance**:
359    /// - Considered stronger than the standard Morning Star due to the Doji's stronger indecision signal
360    /// - Often precedes significant price rallies when confirmed by the third candle
361    /// - Used by traders as a high-probability entry point for long positions
362    /// - Particularly powerful when occurring at support levels with increasing volume
363    ///
364    /// # Example
365    /// ```
366    /// use candlestick_rs::CandleStream;
367    /// let prev2 = (52.0, 52.5, 48.0, 48.5);
368    /// let prev1 = (48.3, 48.9, 47.5, 48.4);
369    /// let curr =  (48.7, 51.5, 48.5, 51.2);
370    /// let mut series = CandleStream::new();
371    /// assert!(series.push(&prev2).push(&prev1).push(&curr).is_morning_star_doji());
372    /// ```
373    pub fn is_morning_star_doji(&self) -> bool {
374        self.get()
375            .zip(self.prev(1))
376            .zip(self.prev(2))
377            .is_some_and(|((c, p1), p2)| {
378                p2.is_bearish()
379                    && p1.is_doji()
380                    && c.is_bullish()
381                    && c.close() > T::midpoint(p2.open(), p2.close())
382            })
383    }
384
385    /// Identifies Three White Soldiers, a powerful bullish reversal or continuation pattern.
386    ///
387    /// This three-candle pattern consists of consecutive bullish candles, each opening within the previous
388    /// candle's body and closing higher, creating a stair-step appearance. Each candle shows progressively
389    /// stronger buying pressure overtaking sellers.
390    ///
391    /// **Trading Significance**:
392    /// - Indicates sustained buying pressure and strong bullish momentum
393    /// - Shows buyers controlling the market over multiple time periods
394    /// - Traders use it to confirm bullish trend reversals or continuations
395    /// - Most reliable when candles have minimal upper shadows (little selling pressure at highs)
396    ///
397    /// # Example
398    /// ```
399    /// use candlestick_rs::CandleStream;
400    /// let prev2 = (48.0, 50.5, 47.8, 50.2);
401    /// let prev1 = (50.3, 52.7, 50.1, 52.4);
402    /// let curr =  (52.5, 54.8, 52.3, 54.5);
403    /// let mut series = CandleStream::new();
404    /// assert!(series.push(&prev2).push(&prev1).push(&curr).is_three_white_soldiers());
405    /// ```
406    pub fn is_three_white_soldiers(&self) -> bool {
407        self.get()
408            .zip(self.prev(1))
409            .zip(self.prev(2))
410            .is_some_and(|((c, p1), p2)| {
411                p2.is_bullish()
412                    && p1.is_bullish()
413                    && p1.open() > p2.close()
414                    && p1.close() > p2.close()
415                    && c.is_bullish()
416                    && c.open() > p1.close()
417                    && c.close() > p1.close()
418            })
419    }
420
421    /// Identifies Three Black Crows, a powerful bearish reversal or continuation pattern.
422    ///
423    /// This three-candle pattern consists of consecutive bearish candles, each opening within the previous
424    /// candle's body and closing lower, creating a downward stair-step appearance. Each candle shows progressively
425    /// stronger selling pressure overtaking buyers.
426    ///
427    /// **Trading Significance**:
428    /// - Indicates sustained selling pressure and strong bearish momentum
429    /// - Shows sellers controlling the market over multiple time periods
430    /// - Traders use it to confirm bearish trend reversals or continuations
431    /// - Most reliable when candles have minimal lower shadows (little buying pressure at lows)
432    ///
433    /// # Example
434    /// ```
435    /// use candlestick_rs::CandleStream;
436    /// let prev2 = (54.0, 54.5, 51.8, 52.2);
437    /// let prev1 = (52.0, 52.3, 49.7, 50.4);
438    /// let curr =  (50.2, 50.5, 47.9, 48.3);
439    /// let mut series = CandleStream::new();
440    /// assert!(series.push(&prev2).push(&prev1).push(&curr).is_three_black_crows());
441    /// ```
442    pub fn is_three_black_crows(&self) -> bool {
443        self.get()
444            .zip(self.prev(1))
445            .zip(self.prev(2))
446            .is_some_and(|((c, p1), p2)| {
447                p2.is_bearish()
448                    && p1.is_bearish()
449                    && p1.open() < p2.close()
450                    && p1.close() < p2.close()
451                    && c.is_bearish()
452                    && c.open() < p1.close()
453                    && c.close() < p1.close()
454            })
455    }
456}
457
458impl<T> Default for CandleStream<'_, T> {
459    fn default() -> Self {
460        Self {
461            series: [const { None }; SERIES_SIZE],
462            idx: 0,
463        }
464    }
465}