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
use std::collections::{HashMap, VecDeque};

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

/// Stochastic Oscillator: %K and %D.
///
/// `%K = 100 * (close - LL) / (HH - LL)` over the last `k_period` bars, `50` for a window without
/// range, clamped to `0..=100`; `%D = SMA(d_period)` of %K. `value` and `extra["percent_k"]`: %K,
/// the raw ("fast") one, not smoothed; `extra["percent_d"]`: %D.
///
/// First output: with the `k_period + d_period - 1`-th bar. [`Indicator::reset`] clears the
/// windows.
pub struct StochasticEngine {
    k_period: usize,
    d_period: usize,
    bars: VecDeque<Bar>,
    raw_ks: VecDeque<f64>,
    alerts: Vec<IndicatorAlert>,
}

impl StochasticEngine {
    pub fn new(k_period: usize, d_period: usize) -> Self {
        Self {
            k_period,
            d_period,
            bars: VecDeque::new(),
            raw_ks: VecDeque::new(),
            alerts: Vec::new(),
        }
    }
}

impl Indicator for StochasticEngine {
    fn name(&self) -> &str {
        "stochastic"
    }

    fn warmup_period(&self) -> usize {
        self.k_period + self.d_period
    }

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

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

        if self.bars.len() < self.k_period {
            return None;
        }

        let highest_high = self.bars.iter().map(|b| b.high).fold(f64::MIN, f64::max);
        let lowest_low = self.bars.iter().map(|b| b.low).fold(f64::MAX, f64::min);

        let k = if (highest_high - lowest_low).abs() > 1e-8 {
            ((bar.close - lowest_low) / (highest_high - lowest_low)) * 100.0
        } else {
            50.0
        }
        .clamp(0.0, 100.0);

        self.raw_ks.push_back(k);
        if self.raw_ks.len() > self.d_period {
            self.raw_ks.pop_front();
        }

        self.alerts.clear();
        if self.raw_ks.len() < self.d_period {
            return None;
        }

        let d = (self.raw_ks.iter().sum::<f64>() / self.d_period as f64).clamp(0.0, 100.0);

        let mut extra = HashMap::new();
        extra.insert("percent_k".to_string(), k);
        extra.insert("percent_d".to_string(), d);

        if k <= 20.0 && d <= 20.0 {
            self.alerts.push(IndicatorAlert::new(
                "stoch_oversold",
                format!("Stochastic Oversold (%K: {:.1}, %D: {:.1})", k, d),
                0.80,
            ));
        } else if k >= 80.0 && d >= 80.0 {
            self.alerts.push(IndicatorAlert::new(
                "stoch_overbought",
                format!("Stochastic Overbought (%K: {:.1}, %D: {:.1})", k, d),
                0.80,
            ));
        }

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

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

/// Rate of Change in percent.
///
/// `ROC = 100 * (close - close_{t-period}) / close_{t-period}`, `0` for a non-positive past close;
/// `extra["abs_momentum"]` is the plain difference. First output: with the `period + 1`-th bar.
/// [`Indicator::reset`] clears the window.
pub struct RocEngine {
    period: usize,
    closes: VecDeque<f64>,
    alerts: Vec<IndicatorAlert>,
}

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

impl Indicator for RocEngine {
    fn name(&self) -> &str {
        "roc"
    }

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

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

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

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

        let past_close = *self.closes.front().unwrap();
        let roc = if past_close > 0.0 {
            ((bar.close - past_close) / past_close) * 100.0
        } else {
            0.0
        };

        let mut extra = HashMap::new();
        extra.insert("abs_momentum".to_string(), bar.close - past_close);

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

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

/// Ultimate Oscillator over three windows.
///
/// Per bar `BP = close - min(low, prev_close)` and `TR = max(high, prev_close) - min(low,
/// prev_close)`; `A_n = sum(BP) / sum(TR)` over the last `n` bars (`0` without range), and
/// `UO = 100 * (4 A_period1 + 2 A_period2 + A_period3) / 7`, clamped to `0..=100`.
///
/// First output: with the `period3 + 1`-th bar. [`Indicator::reset`] clears the window.
pub struct UltimateOscillatorEngine {
    period1: usize,
    period2: usize,
    period3: usize,
    bars: VecDeque<Bar>,
    alerts: Vec<IndicatorAlert>,
}

impl UltimateOscillatorEngine {
    pub fn new(period1: usize, period2: usize, period3: usize) -> Self {
        Self {
            period1,
            period2,
            period3,
            bars: VecDeque::new(),
            alerts: Vec::new(),
        }
    }
}

impl Indicator for UltimateOscillatorEngine {
    fn name(&self) -> &str {
        "ultimate_oscillator"
    }

    fn warmup_period(&self) -> usize {
        self.period3 + 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.period3 + 1 {
            self.bars.pop_front();
        }

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

        self.bars.make_contiguous();
        let calc_bp_tr_sums = |p: usize| -> (f64, f64) {
            let slice = &self.bars.as_slices().0;
            let len = slice.len();
            let window_slice = &slice[len - p - 1..];
            let mut sum_bp = 0.0f64;
            let mut sum_tr = 0.0f64;
            for pair in window_slice.windows(2) {
                let prev_c = pair[0].close;
                let b = &pair[1];
                let min_l_pc = b.low.min(prev_c);
                let max_h_pc = b.high.max(prev_c);
                let bp = b.close - min_l_pc;
                let tr = max_h_pc - min_l_pc;
                sum_bp += bp;
                sum_tr += tr;
            }
            (sum_bp, sum_tr)
        };

        let (bp1, tr1) = calc_bp_tr_sums(self.period1);
        let (bp2, tr2) = calc_bp_tr_sums(self.period2);
        let (bp3, tr3) = calc_bp_tr_sums(self.period3);

        let r1 = if tr1 > 0.0 { bp1 / tr1 } else { 0.0 };
        let r2 = if tr2 > 0.0 { bp2 / tr2 } else { 0.0 };
        let r3 = if tr3 > 0.0 { bp3 / tr3 } else { 0.0 };

        let uo = ((4.0 * r1 + 2.0 * r2 + r3) / 7.0) * 100.0;
        Some(IndicatorOutput::new(uo.clamp(0.0, 100.0)))
    }

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

/// Awesome Oscillator: `SMA(fast_period) - SMA(slow_period)` of the median price
/// `(high + low) / 2`.
///
/// First output: with the `slow_period`-th bar. [`Indicator::reset`] clears the window.
pub struct AwesomeOscillatorEngine {
    fast_period: usize,
    slow_period: usize,
    hl2_series: VecDeque<f64>,
    alerts: Vec<IndicatorAlert>,
}

impl AwesomeOscillatorEngine {
    pub fn new(fast_period: usize, slow_period: usize) -> Self {
        Self {
            fast_period,
            slow_period,
            hl2_series: VecDeque::new(),
            alerts: Vec::new(),
        }
    }
}

impl Indicator for AwesomeOscillatorEngine {
    fn name(&self) -> &str {
        "awesome_oscillator"
    }

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

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

    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
        let hl2 = (bar.high + bar.low) / 2.0;
        self.hl2_series.push_back(hl2);
        if self.hl2_series.len() > self.slow_period {
            self.hl2_series.pop_front();
        }

        self.alerts.clear();
        if self.hl2_series.len() < self.slow_period {
            return None;
        }

        let len = self.hl2_series.len();
        let fast_sma: f64 = self
            .hl2_series
            .iter()
            .skip(len - self.fast_period)
            .sum::<f64>()
            / self.fast_period as f64;
        let slow_sma: f64 = self.hl2_series.iter().sum::<f64>() / self.slow_period as f64;

        let ao = fast_sma - slow_sma;
        Some(IndicatorOutput::new(ao))
    }

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

/// Percentage Price Oscillator.
///
/// `PPO = 100 * (EMA(fast) - EMA(slow)) / EMA(slow)`, `0` for a non-positive slow average; both
/// averages are seeded with the first close and run from the first bar, and the line is published
/// from the `slow_period`-th bar on. `extra["signal"]` is an EMA over the published PPO values,
/// seeded with the first, and `extra["hist"]` is `PPO - signal`.
///
/// First output: with the `slow_period`-th bar. [`Indicator::reset`] clears all averages.
pub struct PpoEngine {
    fast_period: usize,
    slow_period: usize,
    signal_period: usize,
    fast_ema: Option<f64>,
    slow_ema: Option<f64>,
    signal_ema: Option<f64>,
    count: usize,
    alerts: Vec<IndicatorAlert>,
}

impl PpoEngine {
    pub fn new(fast_period: usize, slow_period: usize, signal_period: usize) -> Self {
        Self {
            fast_period,
            slow_period,
            signal_period,
            fast_ema: None,
            slow_ema: None,
            signal_ema: None,
            count: 0,
            alerts: Vec::new(),
        }
    }
}

impl Indicator for PpoEngine {
    fn name(&self) -> &str {
        "ppo"
    }

    fn warmup_period(&self) -> usize {
        self.slow_period + self.signal_period
    }

    fn reset(&mut self) {
        self.fast_ema = None;
        self.slow_ema = None;
        self.signal_ema = None;
        self.count = 0;
        self.alerts.clear();
    }

    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
        self.count += 1;
        let k_fast = 2.0 / (self.fast_period as f64 + 1.0);
        let k_slow = 2.0 / (self.slow_period as f64 + 1.0);
        let k_sig = 2.0 / (self.signal_period as f64 + 1.0);

        self.fast_ema = Some(match self.fast_ema {
            Some(prev) => bar.close * k_fast + prev * (1.0 - k_fast),
            None => bar.close,
        });

        self.slow_ema = Some(match self.slow_ema {
            Some(prev) => bar.close * k_slow + prev * (1.0 - k_slow),
            None => bar.close,
        });

        self.alerts.clear();
        if self.count < self.slow_period {
            return None;
        }

        let fast = self.fast_ema.unwrap();
        let slow = self.slow_ema.unwrap();
        let ppo_line = if slow > 0.0 {
            ((fast - slow) / slow) * 100.0
        } else {
            0.0
        };

        let sig = match self.signal_ema {
            Some(prev) => ppo_line * k_sig + prev * (1.0 - k_sig),
            None => ppo_line,
        };
        self.signal_ema = Some(sig);

        let hist = ppo_line - sig;

        let mut extra = HashMap::new();
        extra.insert("signal".to_string(), sig);
        extra.insert("hist".to_string(), hist);

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

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

/// Chande Momentum Oscillator.
///
/// Over the last `period` changes of the close,
/// `CMO = 100 * (sum(up) - sum(down)) / (sum(up) + sum(down))`, `0` when nothing moved.
///
/// First output: with the `period + 1`-th bar. [`Indicator::reset`] clears the windows.
#[derive(Debug, Clone)]
pub struct CmoEngine {
    period: usize,
    prev_close: Option<f64>,
    gains: VecDeque<f64>,
    losses: VecDeque<f64>,
}

impl CmoEngine {
    pub fn new(period: usize) -> Self {
        Self {
            period: period.max(1),
            prev_close: None,
            gains: VecDeque::with_capacity(period),
            losses: VecDeque::with_capacity(period),
        }
    }
}

impl Indicator for CmoEngine {
    fn name(&self) -> &str {
        "cmo"
    }

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

    fn reset(&mut self) {
        self.prev_close = None;
        self.gains.clear();
        self.losses.clear();
    }

    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
        let prev = match self.prev_close {
            Some(p) => p,
            None => {
                self.prev_close = Some(bar.close);
                return None;
            }
        };

        let diff = bar.close - prev;
        self.prev_close = Some(bar.close);

        let gain = if diff > 0.0 { diff } else { 0.0 };
        let loss = if diff < 0.0 { diff.abs() } else { 0.0 };

        self.gains.push_back(gain);
        self.losses.push_back(loss);

        if self.gains.len() > self.period {
            self.gains.pop_front();
            self.losses.pop_front();
        }

        if self.gains.len() < self.period {
            return None;
        }

        let sum_gain: f64 = self.gains.iter().sum();
        let sum_loss: f64 = self.losses.iter().sum();
        let denom = sum_gain + sum_loss;

        let cmo_val = if denom > 1e-8 {
            (100.0 * (sum_gain - sum_loss) / denom).clamp(-100.0, 100.0)
        } else {
            0.0
        };

        Some(IndicatorOutput::new(cmo_val))
    }

    fn alerts(&self) -> Vec<IndicatorAlert> {
        Vec::new()
    }
}

/// Elder Ray: bull and bear power against an EMA of the close.
///
/// The EMA is the shared [`crate::indicator::smoothing::Ema`] of `period` with its first-sample
/// seed, running from the first bar; `bull = high - EMA`, `bear = low - EMA`. `value` and
/// `extra["bull_power"]`: bull power; `extra["bear_power"]` and `extra["ema"]`.
///
/// First output: with the `period`-th bar. [`Indicator::reset`] clears the average.
pub struct ElderRayEngine {
    ema_period: usize,
    ema: crate::indicator::smoothing::Ema,
    count: usize,
}

impl ElderRayEngine {
    pub fn new(ema_period: usize) -> Self {
        Self {
            ema_period: ema_period.max(1),
            ema: crate::indicator::smoothing::Ema::new(ema_period),
            count: 0,
        }
    }
}

impl Indicator for ElderRayEngine {
    fn name(&self) -> &str {
        "elder_ray"
    }

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

    fn reset(&mut self) {
        self.ema.reset();
        self.count = 0;
    }

    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
        self.count += 1;
        let ema_val = self.ema.update(bar.close)?;

        if self.count < self.ema_period {
            return None;
        }

        let bull_power = bar.high - ema_val;
        let bear_power = bar.low - ema_val;

        let mut extra = HashMap::new();
        extra.insert("bull_power".to_string(), bull_power);
        extra.insert("bear_power".to_string(), bear_power);
        extra.insert("ema".to_string(), ema_val);

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

    fn alerts(&self) -> Vec<IndicatorAlert> {
        Vec::new()
    }
}