kestrel-chartkit 0.1.1

High-performance Rust technical analysis library for indicator math, market regime classification, composite scoring, and SVG visualization.
Documentation
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Chart pattern framework: swing-based trendline fits, tolerance-checked pattern rules,
//! confidence ranking, overlap eviction, and a lifecycle state — built on
//! [`super::zigzag_advanced::ZigZagNode`] sequences (e.g. from
//! [`super::zigzag_advanced::AdvancedZigZagEngine::nodes`]) rather than re-detecting swings.
//!
//! Covers Triangle, Rising/Falling Wedge, the 1-2-3 Reversal, the Wolfe Wave, and auto-fitted
//! trendlines. Each detector is a fixed, documented geometric rule over swing points — a
//! deterministic approximation of how these patterns are described in TA literature, not a claim
//! that every instance found is a "real" tradable pattern.

use crate::model::Bar;

use super::zigzag_advanced::ZigZagNode;

/// A two-point price line, usable to project a value at any timestamp.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TrendLine {
    pub start: (i64, f64),
    pub end: (i64, f64),
}

impl TrendLine {
    pub fn from_nodes(a: &ZigZagNode, b: &ZigZagNode) -> Self {
        Self {
            start: (a.timestamp, a.price),
            end: (b.timestamp, b.price),
        }
    }

    pub fn slope(&self) -> f64 {
        let dt = (self.end.0 - self.start.0) as f64;
        if dt == 0.0 {
            return 0.0;
        }
        (self.end.1 - self.start.1) / dt
    }

    pub fn value_at(&self, timestamp: i64) -> f64 {
        self.start.1 + self.slope() * (timestamp - self.start.0) as f64
    }
}

/// Lifecycle of a detected pattern candidate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatternState {
    /// Still within its defining swing points; boundary not yet broken.
    Forming,
    /// Price broke out through a boundary in the pattern's implied direction.
    Confirmed,
    /// Price violated the pattern's structure without a valid breakout (e.g. closed back through
    /// the opposite boundary first).
    Invalidated,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChartPatternKind {
    Triangle,
    RisingWedge,
    FallingWedge,
    ReversalOneTwoThree,
    WolfeWave,
    AutoTrendline,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ChartPatternCandidate {
    pub kind: ChartPatternKind,
    pub nodes: Vec<ZigZagNode>,
    pub upper_line: Option<TrendLine>,
    pub lower_line: Option<TrendLine>,
    pub state: PatternState,
    /// Heuristic `0.0..=1.0` ranking used for overlap eviction: higher generally means a cleaner
    /// geometric fit (more converging, more parallel, etc., depending on `kind`).
    pub confidence: f64,
}

impl ChartPatternCandidate {
    fn formed_at(&self) -> i64 {
        self.nodes.last().map(|n| n.timestamp).unwrap_or(0)
    }

    fn node_range(&self) -> (i64, i64) {
        let start = self.nodes.first().map(|n| n.timestamp).unwrap_or(0);
        let end = self.formed_at();
        (start, end)
    }

    /// Advances this candidate's lifecycle given a subsequent bar, and returns the (possibly
    /// unchanged) resulting state. A no-op once already `Confirmed`/`Invalidated` — those are
    /// terminal.
    pub fn update_state(&mut self, bar: &Bar) -> PatternState {
        if self.state != PatternState::Forming {
            return self.state;
        }

        self.state = match self.kind {
            ChartPatternKind::Triangle
            | ChartPatternKind::RisingWedge
            | ChartPatternKind::FallingWedge => match (&self.upper_line, &self.lower_line) {
                (Some(upper), Some(lower)) => {
                    if bar.close > upper.value_at(bar.timestamp)
                        || bar.close < lower.value_at(bar.timestamp)
                    {
                        PatternState::Confirmed
                    } else {
                        PatternState::Forming
                    }
                }
                _ => PatternState::Forming,
            },
            ChartPatternKind::AutoTrendline => match self.upper_line.or(self.lower_line) {
                Some(line) => {
                    let is_resistance = self.upper_line.is_some();
                    let broke = if is_resistance {
                        bar.close > line.value_at(bar.timestamp)
                    } else {
                        bar.close < line.value_at(bar.timestamp)
                    };
                    if broke {
                        PatternState::Confirmed
                    } else {
                        PatternState::Forming
                    }
                }
                None => PatternState::Forming,
            },
            ChartPatternKind::ReversalOneTwoThree => {
                let (n2, n3) = (&self.nodes[1], &self.nodes[2]);
                let bearish = n2.is_high;
                if bearish {
                    if bar.close < n3.price {
                        PatternState::Confirmed
                    } else if bar.close > n2.price {
                        PatternState::Invalidated
                    } else {
                        PatternState::Forming
                    }
                } else if bar.close > n3.price {
                    PatternState::Confirmed
                } else if bar.close < n2.price {
                    PatternState::Invalidated
                } else {
                    PatternState::Forming
                }
            }
            ChartPatternKind::WolfeWave => {
                let n5 = self.nodes[4];
                let target_line = TrendLine::from_nodes(&self.nodes[0], &self.nodes[3]); // line 1-4 projects the target
                let target = target_line.value_at(bar.timestamp);
                let reverting_toward_target = if n5.is_high {
                    bar.close < n5.price && bar.close >= target.min(n5.price)
                } else {
                    bar.close > n5.price && bar.close <= target.max(n5.price)
                };
                let continuing_past_five = if n5.is_high {
                    bar.close > n5.price
                } else {
                    bar.close < n5.price
                };
                if reverting_toward_target {
                    PatternState::Confirmed
                } else if continuing_past_five {
                    PatternState::Invalidated
                } else {
                    PatternState::Forming
                }
            }
        };

        self.state
    }
}

/// Scans a swing-node sequence for pattern candidates and evicts overlapping lower-confidence
/// ones, so the result is a ranked, non-redundant set rather than every geometrically-possible
/// match.
pub struct ChartPatternDetector {
    pub tolerance_pct: f64,
}

impl ChartPatternDetector {
    pub fn new(tolerance_pct: f64) -> Self {
        Self {
            tolerance_pct: tolerance_pct.max(0.001),
        }
    }

    /// Detects all supported pattern kinds over `nodes`, then evicts overlapping candidates
    /// (sharing any swing node), keeping the highest-confidence one per overlapping cluster.
    pub fn scan(&self, nodes: &[ZigZagNode]) -> Vec<ChartPatternCandidate> {
        let mut candidates = Vec::new();
        candidates.extend(self.scan_triangles_and_wedges(nodes));
        candidates.extend(self.scan_reversal_one_two_three(nodes));
        candidates.extend(self.scan_wolfe_waves(nodes));
        if let Some(trendline) = self.auto_trendline(nodes, true) {
            candidates.push(trendline);
        }
        if let Some(trendline) = self.auto_trendline(nodes, false) {
            candidates.push(trendline);
        }
        self.evict_overlaps(candidates)
    }

    /// Evicts overlapping candidates *within the same pattern kind* only (sliding-window
    /// detection naturally produces redundant near-duplicates of one kind over the same swing
    /// points). Different kinds describe different information and are allowed to coexist over
    /// the same nodes — e.g. a 1-2-3 reversal and an unrelated 2-point auto-trendline spanning the
    /// same three nodes are not "competing" for the same signal.
    fn evict_overlaps(&self, candidates: Vec<ChartPatternCandidate>) -> Vec<ChartPatternCandidate> {
        let mut by_kind: Vec<(ChartPatternKind, Vec<ChartPatternCandidate>)> = Vec::new();
        for candidate in candidates {
            match by_kind.iter_mut().find(|(k, _)| *k == candidate.kind) {
                Some((_, group)) => group.push(candidate),
                None => by_kind.push((candidate.kind, vec![candidate])),
            }
        }

        let mut kept: Vec<ChartPatternCandidate> = Vec::new();
        for (_, mut group) in by_kind {
            group.sort_by(|a, b| b.confidence.total_cmp(&a.confidence));
            'outer: for candidate in group {
                let (c_start, c_end) = candidate.node_range();
                for existing in &kept {
                    if existing.kind != candidate.kind {
                        continue;
                    }
                    let (e_start, e_end) = existing.node_range();
                    let overlaps = c_start <= e_end && e_start <= c_end;
                    if overlaps {
                        continue 'outer;
                    }
                }
                kept.push(candidate);
            }
        }
        kept.sort_by_key(|c| c.formed_at());
        kept
    }

    /// Triangles/wedges need 4 alternating swing nodes (H,L,H,L or L,H,L,H): an upper line through
    /// the two highs, a lower line through the two lows.
    fn scan_triangles_and_wedges(&self, nodes: &[ZigZagNode]) -> Vec<ChartPatternCandidate> {
        let mut out = Vec::new();
        for window in nodes.windows(4) {
            let alternating = window.windows(2).all(|p| p[0].is_high != p[1].is_high);
            if !alternating {
                continue;
            }
            let highs: Vec<&ZigZagNode> = window.iter().filter(|n| n.is_high).collect();
            let lows: Vec<&ZigZagNode> = window.iter().filter(|n| !n.is_high).collect();
            if highs.len() != 2 || lows.len() != 2 {
                continue;
            }

            let upper = TrendLine::from_nodes(highs[0], highs[1]);
            let lower = TrendLine::from_nodes(lows[0], lows[1]);

            let (start_ts, end_ts) = (
                window.first().unwrap().timestamp,
                window.last().unwrap().timestamp,
            );
            let gap_start = upper.value_at(start_ts) - lower.value_at(start_ts);
            let gap_end = upper.value_at(end_ts) - lower.value_at(end_ts);
            if gap_start <= 0.0 || gap_end <= 0.0 || gap_end >= gap_start {
                continue; // must be converging
            }

            let convergence = 1.0 - (gap_end / gap_start);
            let flat_tol = self.tolerance_pct / 100.0;
            let upper_flat = upper.slope().abs() / gap_start.max(1e-9) < flat_tol;
            let lower_flat = lower.slope().abs() / gap_start.max(1e-9) < flat_tol;

            let kind = if upper.slope() > 0.0 && lower.slope() > 0.0 {
                ChartPatternKind::RisingWedge
            } else if upper.slope() < 0.0 && lower.slope() < 0.0 {
                ChartPatternKind::FallingWedge
            } else if (upper.slope() <= 0.0 || upper_flat) && (lower.slope() >= 0.0 || lower_flat) {
                ChartPatternKind::Triangle
            } else {
                continue;
            };

            out.push(ChartPatternCandidate {
                kind,
                nodes: window.to_vec(),
                upper_line: Some(upper),
                lower_line: Some(lower),
                state: PatternState::Forming,
                confidence: convergence.clamp(0.0, 1.0),
            });
        }
        out
    }

    /// A 1-2-3 reversal: three consecutive nodes where the middle one is a failed extreme (did
    /// not extend the trend) and the third breaks past the first's level in the opposite
    /// direction — e.g. bearish: low(1) < high(2) fails to make a new high vs. the prior trend,
    /// then low(3) < low(1).
    fn scan_reversal_one_two_three(&self, nodes: &[ZigZagNode]) -> Vec<ChartPatternCandidate> {
        let mut out = Vec::new();
        for window in nodes.windows(3) {
            let (n1, n2, n3) = (&window[0], &window[1], &window[2]);
            if n1.is_high == n2.is_high || n2.is_high == n3.is_high {
                continue;
            }

            let bearish = !n1.is_high && n2.is_high && !n3.is_high && n3.price < n1.price;
            let bullish = n1.is_high && !n2.is_high && n3.is_high && n3.price > n1.price;
            if !bearish && !bullish {
                continue;
            }

            let magnitude = (n3.price - n1.price).abs() / n1.price.abs().max(1e-9);
            out.push(ChartPatternCandidate {
                kind: ChartPatternKind::ReversalOneTwoThree,
                nodes: window.to_vec(),
                upper_line: None,
                lower_line: None,
                state: PatternState::Forming,
                confidence: magnitude.min(1.0),
            });
        }
        out
    }

    /// A Wolfe Wave: 5 alternating points where line(1-3) and line(2-4) are roughly parallel and
    /// point 5 pierces the line(1-3) extension.
    fn scan_wolfe_waves(&self, nodes: &[ZigZagNode]) -> Vec<ChartPatternCandidate> {
        let mut out = Vec::new();
        for window in nodes.windows(5) {
            let alternating = window.windows(2).all(|p| p[0].is_high != p[1].is_high);
            if !alternating {
                continue;
            }
            let (n1, n2, n3, n4, n5) = (&window[0], &window[1], &window[2], &window[3], &window[4]);

            let line13 = TrendLine::from_nodes(n1, n3);
            let line24 = TrendLine::from_nodes(n2, n4);

            let scale = (n1.price.abs() + n3.price.abs()).max(1e-9);
            let slope_diff = (line13.slope() - line24.slope()).abs() / scale;
            let parallel_tol = self.tolerance_pct / 100.0 * 5.0;
            if slope_diff > parallel_tol {
                continue;
            }

            let projected13_at5 = line13.value_at(n5.timestamp);
            let pierces = if n1.is_high {
                // 1,3,5 are lows (bullish Wolfe): point 5 must undercut the 1-3 extension.
                !n5.is_high && n5.price < projected13_at5
            } else {
                n5.is_high && n5.price > projected13_at5
            };
            if !pierces {
                continue;
            }

            let confidence = (1.0 - slope_diff / parallel_tol.max(1e-9)).clamp(0.0, 1.0);
            out.push(ChartPatternCandidate {
                kind: ChartPatternKind::WolfeWave,
                nodes: window.to_vec(),
                upper_line: Some(if n1.is_high { line24 } else { line13 }),
                lower_line: Some(if n1.is_high { line13 } else { line24 }),
                state: PatternState::Forming,
                confidence,
            });
        }
        out
    }

    /// Auto-fits the best trendline through same-type swing points: the oldest and newest node of
    /// that type, valid only if no intermediate node of the same type violates it (a resistance
    /// line no high pierces, or a support line no low pierces).
    fn auto_trendline(
        &self,
        nodes: &[ZigZagNode],
        for_highs: bool,
    ) -> Option<ChartPatternCandidate> {
        let same_type: Vec<&ZigZagNode> = nodes.iter().filter(|n| n.is_high == for_highs).collect();
        if same_type.len() < 2 {
            return None;
        }
        let first = *same_type.first().unwrap();
        let last = *same_type.last().unwrap();
        let line = TrendLine::from_nodes(first, last);

        let violated = same_type.iter().any(|n| {
            let projected = line.value_at(n.timestamp);
            if for_highs {
                n.price > projected * (1.0 + self.tolerance_pct / 100.0)
            } else {
                n.price < projected * (1.0 - self.tolerance_pct / 100.0)
            }
        });
        if violated {
            return None;
        }

        let touches = same_type.len();
        let confidence = ((touches as f64 - 2.0) / 4.0 + 0.5).clamp(0.0, 1.0);

        Some(ChartPatternCandidate {
            kind: ChartPatternKind::AutoTrendline,
            nodes: same_type.into_iter().copied().collect(),
            upper_line: for_highs.then_some(line),
            lower_line: (!for_highs).then_some(line),
            state: PatternState::Forming,
            confidence,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn node(ts: i64, price: f64, is_high: bool) -> ZigZagNode {
        ZigZagNode {
            timestamp: ts,
            price,
            is_high,
            confirmed: true,
        }
    }

    #[test]
    fn test_trendline_value_at_interpolates() {
        let a = node(0, 100.0, true);
        let b = node(100, 200.0, true);
        let line = TrendLine::from_nodes(&a, &b);
        assert!((line.value_at(50) - 150.0).abs() < 1e-9);
    }

    #[test]
    fn test_detects_converging_triangle() {
        let nodes = vec![
            node(0, 110.0, true),
            node(10, 90.0, false),
            node(20, 105.0, true),
            node(30, 95.0, false),
        ];
        let detector = ChartPatternDetector::new(50.0);
        let candidates = detector.scan(&nodes);
        assert!(candidates
            .iter()
            .any(|c| c.kind == ChartPatternKind::Triangle));
    }

    #[test]
    fn test_detects_bearish_one_two_three_reversal() {
        let nodes = vec![
            node(0, 100.0, false),
            node(10, 110.0, true),
            node(20, 95.0, false),
        ];
        let detector = ChartPatternDetector::new(1.0);
        let candidates = detector.scan(&nodes);
        assert!(candidates
            .iter()
            .any(|c| c.kind == ChartPatternKind::ReversalOneTwoThree));
    }

    #[test]
    fn test_auto_trendline_rejects_violated_support() {
        // Three lows: a line from the first (100) to the last (95) projects ~97.5 at t=10, but
        // the middle low dips to 90 -- well below that line, violating it as a support trendline.
        let nodes = vec![
            node(0, 100.0, false),
            node(5, 105.0, true),
            node(10, 90.0, false),
            node(15, 102.0, true),
            node(20, 95.0, false),
        ];
        let detector = ChartPatternDetector::new(0.1);
        let candidates = detector.scan(&nodes);
        assert!(!candidates.iter().any(
            |c| c.kind == ChartPatternKind::AutoTrendline && c.nodes.iter().all(|n| !n.is_high)
        ));
    }

    #[test]
    fn test_evict_overlaps_keeps_only_highest_confidence_within_same_kind() {
        // A longer alternating sequence so multiple overlapping 4-node triangle/wedge windows
        // are genuinely detected and compete against each other for eviction.
        let nodes = vec![
            node(0, 130.0, true),
            node(10, 70.0, false),
            node(20, 120.0, true),
            node(30, 80.0, false),
            node(40, 110.0, true),
            node(50, 90.0, false),
        ];
        let detector = ChartPatternDetector::new(50.0);
        let candidates = detector.scan(&nodes);

        // Within any single kind, no two surviving candidates may share a node timestamp range.
        for kind in [
            ChartPatternKind::Triangle,
            ChartPatternKind::RisingWedge,
            ChartPatternKind::FallingWedge,
        ] {
            let same_kind: Vec<&ChartPatternCandidate> =
                candidates.iter().filter(|c| c.kind == kind).collect();
            for (i, a) in same_kind.iter().enumerate() {
                for b in same_kind.iter().skip(i + 1) {
                    let (a_start, a_end) = a.node_range();
                    let (b_start, b_end) = b.node_range();
                    assert!(
                        a_end < b_start || b_end < a_start,
                        "overlapping candidates of the same kind must have been evicted"
                    );
                }
            }
        }

        // Different kinds are allowed to overlap (e.g. an auto-trendline and a triangle sharing
        // nodes describe different information), so the result set is non-empty and mixed.
        assert!(!candidates.is_empty());
    }

    #[test]
    fn test_triangle_confirms_on_breakout() {
        let nodes = vec![
            node(0, 110.0, true),
            node(10, 90.0, false),
            node(20, 105.0, true),
            node(30, 95.0, false),
        ];
        let detector = ChartPatternDetector::new(50.0);
        let mut candidates = detector.scan(&nodes);
        let triangle = candidates
            .iter_mut()
            .find(|c| c.kind == ChartPatternKind::Triangle)
            .unwrap();

        // Still inside both lines: stays Forming.
        let inside = Bar::new(35, 100.0, 100.5, 99.5, 100.0, 1.0);
        assert_eq!(triangle.update_state(&inside), PatternState::Forming);

        // Breaks decisively above the upper line.
        let breakout = Bar::new(40, 130.0, 130.5, 129.5, 130.0, 1.0);
        assert_eq!(triangle.update_state(&breakout), PatternState::Confirmed);

        // Terminal: a later bar cannot change a Confirmed pattern back to Forming.
        let after = Bar::new(50, 50.0, 50.5, 49.5, 50.0, 1.0);
        assert_eq!(triangle.update_state(&after), PatternState::Confirmed);
    }

    #[test]
    fn test_reversal_one_two_three_confirms_and_invalidates() {
        let confirm_nodes = vec![
            node(0, 100.0, false),
            node(10, 110.0, true),
            node(20, 95.0, false),
        ];
        let mut confirm_candidate = ChartPatternDetector::new(1.0)
            .scan(&confirm_nodes)
            .into_iter()
            .find(|c| c.kind == ChartPatternKind::ReversalOneTwoThree)
            .unwrap();
        let breaks_below_n3 = Bar::new(30, 90.0, 90.5, 89.5, 90.0, 1.0);
        assert_eq!(
            confirm_candidate.update_state(&breaks_below_n3),
            PatternState::Confirmed
        );

        let mut invalidate_candidate = ChartPatternDetector::new(1.0)
            .scan(&confirm_nodes)
            .into_iter()
            .find(|c| c.kind == ChartPatternKind::ReversalOneTwoThree)
            .unwrap();
        let reclaims_above_n2 = Bar::new(30, 115.0, 115.5, 114.5, 115.0, 1.0);
        assert_eq!(
            invalidate_candidate.update_state(&reclaims_above_n2),
            PatternState::Invalidated
        );
    }
}