kestrel-chartkit 0.11.3

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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use std::collections::{HashMap, VecDeque};

use crate::indicator::{Indicator, IndicatorAlert, IndicatorOutput};
use crate::model::Bar;

/// Directional Movement Index: +DI and -DI over plain sums.
///
/// Per bar from the second one on, +DM, -DM and TR as in [`super::adx::Adx`]. Unlike the ADX they
/// are **summed** over the last `period` bars rather than Wilder-smoothed:
/// `+DI = 100 * sum(+DM) / sum(TR)`, `-DI = 100 * sum(-DM) / sum(TR)` (0 without range).
///
/// `value`: `+DI - -DI` — the difference of the two lines, **not** the directional index DX that
/// [`super::adx::Adx`] computes. `extra["plus_di"]` and `extra["minus_di"]` (each clamped to
/// `0..=100`) and `extra["di_diff"]`. Alerts fire when one line leads the other by more than 10.
///
/// First output: with the `period + 1`-th bar. [`Indicator::reset`] clears the windows.
pub struct DmiEngine {
    period: usize,
    prev_bar: Option<Bar>,
    plus_dms: VecDeque<f64>,
    minus_dms: VecDeque<f64>,
    trs: VecDeque<f64>,
    alerts: Vec<IndicatorAlert>,
}

impl DmiEngine {
    pub fn new(period: usize) -> Self {
        Self {
            period,
            prev_bar: None,
            plus_dms: VecDeque::new(),
            minus_dms: VecDeque::new(),
            trs: VecDeque::new(),
            alerts: Vec::new(),
        }
    }
}

impl Indicator for DmiEngine {
    fn name(&self) -> &str {
        "dmi"
    }

    fn warmup_period(&self) -> usize {
        self.period + 1
    }

    fn reset(&mut self) {
        self.prev_bar = None;
        self.plus_dms.clear();
        self.minus_dms.clear();
        self.trs.clear();
        self.alerts.clear();
    }

    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
        if let Some(ref prev) = self.prev_bar {
            let tr = (bar.high - bar.low)
                .max((bar.high - prev.close).abs())
                .max((bar.low - prev.close).abs());
            let up_move = bar.high - prev.high;
            let down_move = prev.low - bar.low;

            let plus_dm = if up_move > down_move && up_move > 0.0 {
                up_move
            } else {
                0.0
            };
            let minus_dm = if down_move > up_move && down_move > 0.0 {
                down_move
            } else {
                0.0
            };

            self.trs.push_back(tr);
            self.plus_dms.push_back(plus_dm);
            self.minus_dms.push_back(minus_dm);

            if self.trs.len() > self.period {
                self.trs.pop_front();
                self.plus_dms.pop_front();
                self.minus_dms.pop_front();
            }
        }
        self.prev_bar = Some(bar.clone());

        self.alerts.clear();
        if self.trs.len() < self.period {
            return None;
        }

        let sum_tr: f64 = self.trs.iter().sum();
        let sum_plus_dm: f64 = self.plus_dms.iter().sum();
        let sum_minus_dm: f64 = self.minus_dms.iter().sum();

        let plus_di = if sum_tr > 0.0 {
            (sum_plus_dm / sum_tr) * 100.0
        } else {
            0.0
        };
        let minus_di = if sum_tr > 0.0 {
            (sum_minus_dm / sum_tr) * 100.0
        } else {
            0.0
        };

        let mut extra = HashMap::new();
        extra.insert("plus_di".to_string(), plus_di.clamp(0.0, 100.0));
        extra.insert("minus_di".to_string(), minus_di.clamp(0.0, 100.0));
        extra.insert("di_diff".to_string(), plus_di - minus_di);

        if plus_di > minus_di + 10.0 {
            self.alerts.push(IndicatorAlert::new(
                "dmi_bullish_dominance",
                format!("+DI dominates -DI ({:.1} vs {:.1})", plus_di, minus_di),
                0.80,
            ));
        } else if minus_di > plus_di + 10.0 {
            self.alerts.push(IndicatorAlert::new(
                "dmi_bearish_dominance",
                format!("-DI dominates +DI ({:.1} vs {:.1})", minus_di, plus_di),
                0.80,
            ));
        }

        Some(IndicatorOutput::with_extra(plus_di - minus_di, extra))
    }

    fn alerts(&self) -> Vec<IndicatorAlert> {
        self.alerts.clone()
    }
}

/// Aroon: how recently the highest high and the lowest low of the last `period + 1` bars
/// occurred.
///
/// Within the window the most recent bar holding the highest high respectively the lowest low
/// counts (ties go to the later bar). With `bars_since` its distance from the current bar,
/// `Aroon Up = (period - bars_since_high) / period * 100`, `Aroon Down` likewise for the low, and
/// the oscillator is `Up - Down`.
///
/// `value`: the oscillator; `extra["aroon_up"]`, `extra["aroon_down"]` (clamped to `0..=100`) and
/// `extra["oscillator"]`. First output: with the `period + 1`-th bar. [`Indicator::reset`] clears
/// the window.
pub struct AroonEngine {
    period: usize,
    bars: VecDeque<Bar>,
    alerts: Vec<IndicatorAlert>,
}

impl AroonEngine {
    pub fn new(period: usize) -> Self {
        Self {
            period,
            bars: VecDeque::new(),
            alerts: Vec::new(),
        }
    }
}

impl Indicator for AroonEngine {
    fn name(&self) -> &str {
        "aroon"
    }

    fn warmup_period(&self) -> usize {
        self.period + 1
    }

    fn reset(&mut self) {
        self.bars.clear();
        self.alerts.clear();
    }

    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
        self.bars.push_back(bar.clone());
        if self.bars.len() > self.period + 1 {
            self.bars.pop_front();
        }

        self.alerts.clear();
        if self.bars.len() < self.period + 1 {
            return None;
        }

        let mut high_idx = 0usize;
        let mut max_high = f64::MIN;
        let mut low_idx = 0usize;
        let mut min_low = f64::MAX;

        for (i, b) in self.bars.iter().enumerate() {
            if b.high >= max_high {
                max_high = b.high;
                high_idx = i;
            }
            if b.low <= min_low {
                min_low = b.low;
                low_idx = i;
            }
        }

        let bars_since_high = self.period - high_idx;
        let bars_since_low = self.period - low_idx;

        let aroon_up = ((self.period - bars_since_high) as f64 / self.period as f64) * 100.0;
        let aroon_down = ((self.period - bars_since_low) as f64 / self.period as f64) * 100.0;
        let oscillator = aroon_up - aroon_down;

        let mut extra = HashMap::new();
        extra.insert("aroon_up".to_string(), aroon_up.clamp(0.0, 100.0));
        extra.insert("aroon_down".to_string(), aroon_down.clamp(0.0, 100.0));
        extra.insert("oscillator".to_string(), oscillator.clamp(-100.0, 100.0));

        Some(IndicatorOutput::with_extra(oscillator, extra))
    }

    fn alerts(&self) -> Vec<IndicatorAlert> {
        self.alerts.clone()
    }
}

/// Parabolic SAR.
///
/// Starts long on the first bar with `SAR = low`, `EP = high`, `AF = step`, and publishes that
/// first SAR. On every following bar the next SAR is `SAR + AF * (EP - SAR)`:
///
/// - Long: a low below it reverses to short — the SAR becomes the EP, the EP this bar's low, and
///   `AF = step`. Otherwise a new high moves the EP and raises `AF` by `step` up to `max_step`,
///   and the SAR is held at or below the previous and the current low.
/// - Short: symmetric, with highs.
///
/// The hold uses the **previous** bar's extreme only (the current one is already excluded by the
/// reversal check before it). The original rule holds the SAR beyond the extremes of the two
/// previous bars, so after a sharp two-bar move this SAR can sit closer to price.
///
/// `value`: the SAR; `extra["is_long"]` (`1`/`0`) and `extra["af"]`. First output: with the first
/// bar. [`Indicator::reset`] returns to the long start.
pub struct ParabolicSarEngine {
    step: f64,
    max_step: f64,
    is_long: bool,
    sar: f64,
    ep: f64,
    af: f64,
    prev_bar: Option<Bar>,
    alerts: Vec<IndicatorAlert>,
}

impl ParabolicSarEngine {
    pub fn new(step: f64, max_step: f64) -> Self {
        Self {
            step,
            max_step,
            is_long: true,
            sar: 0.0,
            ep: 0.0,
            af: step,
            prev_bar: None,
            alerts: Vec::new(),
        }
    }
}

impl Indicator for ParabolicSarEngine {
    fn name(&self) -> &str {
        "parabolic_sar"
    }

    fn warmup_period(&self) -> usize {
        2
    }

    fn reset(&mut self) {
        self.is_long = true;
        self.sar = 0.0;
        self.ep = 0.0;
        self.af = self.step;
        self.prev_bar = None;
        self.alerts.clear();
    }

    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
        if self.prev_bar.is_none() {
            self.prev_bar = Some(bar.clone());
            self.sar = bar.low;
            self.ep = bar.high;
            return Some(IndicatorOutput::new(self.sar));
        }

        let prev = self.prev_bar.as_ref().unwrap();
        let mut next_sar = self.sar + self.af * (self.ep - self.sar);

        self.alerts.clear();
        if self.is_long {
            if bar.low < next_sar {
                self.is_long = false;
                next_sar = self.ep;
                self.ep = bar.low;
                self.af = self.step;
                self.alerts.push(IndicatorAlert::new(
                    "psar_reversal_bearish",
                    format!("PSAR Bearish Reversal (${:.2})", next_sar),
                    0.85,
                ));
            } else {
                if bar.high > self.ep {
                    self.ep = bar.high;
                    self.af = (self.af + self.step).min(self.max_step);
                }
                next_sar = next_sar.min(prev.low).min(bar.low);
            }
        } else {
            if bar.high > next_sar {
                self.is_long = true;
                next_sar = self.ep;
                self.ep = bar.high;
                self.af = self.step;
                self.alerts.push(IndicatorAlert::new(
                    "psar_reversal_bullish",
                    format!("PSAR Bullish Reversal (${:.2})", next_sar),
                    0.85,
                ));
            } else {
                if bar.low < self.ep {
                    self.ep = bar.low;
                    self.af = (self.af + self.step).min(self.max_step);
                }
                next_sar = next_sar.max(prev.high).max(bar.high);
            }
        }

        self.sar = next_sar;
        self.prev_bar = Some(bar.clone());

        let mut extra = HashMap::new();
        extra.insert("is_long".to_string(), if self.is_long { 1.0 } else { 0.0 });
        extra.insert("af".to_string(), self.af);

        Some(IndicatorOutput::with_extra(self.sar, extra))
    }

    fn alerts(&self) -> Vec<IndicatorAlert> {
        self.alerts.clone()
    }
}

/// Supertrend: a trailing band that flips with the close.
///
/// `ATR` is the **plain mean** of the last `period` true ranges (the first `high - low`), not a
/// Wilder average. Basic bands are `(high + low) / 2 ± multiplier * ATR`. A final band only moves
/// against the trend when the previous close crossed it: the upper band takes the new basic value
/// if that is lower or the previous close was above the old band, the lower band if it is higher or
/// the previous close was below. The trend starts up and flips when the close falls below the final
/// lower band (in an uptrend) or rises above the final upper band (in a downtrend).
///
/// `value`: the lower band in an uptrend, the upper band in a downtrend; `extra["trend"]`
/// (`1`/`-1`), `extra["upper"]`, `extra["lower"]`. First output: with the `period`-th bar.
/// [`Indicator::reset`] clears the window and the bands.
pub struct SupertrendEngine {
    period: usize,
    multiplier: f64,
    trs: VecDeque<f64>,
    prev_close: Option<f64>,
    trend: i32, // 1 = Bullish, -1 = Bearish
    upper_band: f64,
    lower_band: f64,
    supertrend: f64,
    alerts: Vec<IndicatorAlert>,
}

impl SupertrendEngine {
    pub fn new(period: usize, multiplier: f64) -> Self {
        Self {
            period,
            multiplier,
            trs: VecDeque::new(),
            prev_close: None,
            trend: 1,
            upper_band: 0.0,
            lower_band: 0.0,
            supertrend: 0.0,
            alerts: Vec::new(),
        }
    }
}

impl Indicator for SupertrendEngine {
    fn name(&self) -> &str {
        "supertrend"
    }

    fn warmup_period(&self) -> usize {
        self.period
    }

    fn reset(&mut self) {
        self.trs.clear();
        self.prev_close = None;
        self.trend = 1;
        self.upper_band = 0.0;
        self.lower_band = 0.0;
        self.supertrend = 0.0;
        self.alerts.clear();
    }

    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
        let tr = if let Some(prev) = self.prev_close {
            (bar.high - bar.low)
                .max((bar.high - prev).abs())
                .max((bar.low - prev).abs())
        } else {
            bar.high - bar.low
        };

        self.trs.push_back(tr);
        if self.trs.len() > self.period {
            self.trs.pop_front();
        }

        self.alerts.clear();
        if self.trs.len() < self.period {
            self.prev_close = Some(bar.close);
            return None;
        }

        let atr = self.trs.iter().sum::<f64>() / self.period as f64;
        let hl2 = (bar.high + bar.low) / 2.0;

        let basic_upper = hl2 + self.multiplier * atr;
        let basic_lower = hl2 - self.multiplier * atr;

        let prev_close = self.prev_close.unwrap_or(bar.close);

        let final_upper = if basic_upper < self.upper_band || prev_close > self.upper_band {
            basic_upper
        } else {
            self.upper_band
        };

        let final_lower = if basic_lower > self.lower_band || prev_close < self.lower_band {
            basic_lower
        } else {
            self.lower_band
        };

        let prev_trend = self.trend;
        if self.trend == 1 && bar.close < final_lower {
            self.trend = -1;
        } else if self.trend == -1 && bar.close > final_upper {
            self.trend = 1;
        }

        self.upper_band = final_upper;
        self.lower_band = final_lower;
        self.supertrend = if self.trend == 1 {
            final_lower
        } else {
            final_upper
        };
        self.prev_close = Some(bar.close);

        if self.trend != prev_trend {
            if self.trend == 1 {
                self.alerts.push(IndicatorAlert::new(
                    "supertrend_bullish",
                    format!("Supertrend Bullish Flip (${:.2})", self.supertrend),
                    0.90,
                ));
            } else {
                self.alerts.push(IndicatorAlert::new(
                    "supertrend_bearish",
                    format!("Supertrend Bearish Flip (${:.2})", self.supertrend),
                    0.90,
                ));
            }
        }

        let mut extra = HashMap::new();
        extra.insert("trend".to_string(), self.trend as f64);
        extra.insert("upper".to_string(), final_upper);
        extra.insert("lower".to_string(), final_lower);

        Some(IndicatorOutput::with_extra(self.supertrend, extra))
    }

    fn alerts(&self) -> Vec<IndicatorAlert> {
        self.alerts.clone()
    }
}

/// Ichimoku Kinko Hyo: tenkan-sen, kijun-sen and the two cloud spans.
///
/// A line's value is the midpoint of the highest high and the lowest low over its window:
/// `tenkan` over `tenkan_p` bars, `kijun` over `kijun_p`, `senkou_b` over `senkou_b_p`, and
/// `senkou_a = (tenkan + kijun) / 2`. The spans are published **unshifted**, on the bar they are
/// computed for; drawing them `kijun_p` bars ahead, as the cloud is usually shown, is left to the
/// consumer. There is no chikou span.
///
/// `value`: `tenkan - kijun`; `extra` carries all four lines. First output: with the
/// `senkou_b_p`-th bar. [`Indicator::reset`] clears the window.
pub struct IchimokuEngine {
    tenkan_p: usize,
    kijun_p: usize,
    senkou_b_p: usize,
    bars: VecDeque<Bar>,
    alerts: Vec<IndicatorAlert>,
}

impl IchimokuEngine {
    pub fn new(tenkan_p: usize, kijun_p: usize, senkou_b_p: usize) -> Self {
        Self {
            tenkan_p,
            kijun_p,
            senkou_b_p,
            bars: VecDeque::new(),
            alerts: Vec::new(),
        }
    }
}

impl Indicator for IchimokuEngine {
    fn name(&self) -> &str {
        "ichimoku"
    }

    fn warmup_period(&self) -> usize {
        self.senkou_b_p
    }

    fn reset(&mut self) {
        self.bars.clear();
        self.alerts.clear();
    }

    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
        self.bars.push_back(bar.clone());
        if self.bars.len() > self.senkou_b_p {
            self.bars.pop_front();
        }

        self.alerts.clear();
        if self.bars.len() < self.senkou_b_p {
            return None;
        }

        let calc_midpoint = |slice: &[Bar]| -> f64 {
            let h = slice.iter().map(|b| b.high).fold(f64::MIN, f64::max);
            let l = slice.iter().map(|b| b.low).fold(f64::MAX, f64::min);
            (h + l) / 2.0
        };

        self.bars.make_contiguous();
        let slice = self.bars.as_slices().0;
        let len = slice.len();
        let tenkan = calc_midpoint(&slice[len - self.tenkan_p..]);
        let kijun = calc_midpoint(&slice[len - self.kijun_p..]);
        let senkou_a = (tenkan + kijun) / 2.0;
        let senkou_b = calc_midpoint(slice);

        let mut extra = HashMap::new();
        extra.insert("tenkan".to_string(), tenkan);
        extra.insert("kijun".to_string(), kijun);
        extra.insert("senkou_a".to_string(), senkou_a);
        extra.insert("senkou_b".to_string(), senkou_b);

        if bar.close > senkou_a && bar.close > senkou_b {
            self.alerts.push(IndicatorAlert::new(
                "ichimoku_above_cloud",
                format!(
                    "Price Above Ichimoku Cloud (SpanA ${:.2}, SpanB ${:.2})",
                    senkou_a, senkou_b
                ),
                0.85,
            ));
        } else if bar.close < senkou_a && bar.close < senkou_b {
            self.alerts.push(IndicatorAlert::new(
                "ichimoku_below_cloud",
                format!(
                    "Price Below Ichimoku Cloud (SpanA ${:.2}, SpanB ${:.2})",
                    senkou_a, senkou_b
                ),
                0.85,
            ));
        }

        Some(IndicatorOutput::with_extra(tenkan - kijun, extra))
    }

    fn alerts(&self) -> Vec<IndicatorAlert> {
        self.alerts.clone()
    }
}