Skip to main content

ferrochart_indicators/
lib.rs

1//! Incremental technical indicators for FerroChart.
2//!
3//! Every function returns a [`Builtin`] that implements
4//! [`ferrochart_core::plugin::Indicator`]; attach it with
5//! [`Chart::add_indicator`](ferrochart_core::Chart::add_indicator). The
6//! formulas, seeds and warmups are specified in `docs/book/src/indicators.md`; all
7//! indicators are tested against a numpy reference implementation, and those
8//! TA-Lib has against TA-Lib.
9//!
10//! ```
11//! use ferrochart_core::chart::SeriesOptions;
12//! use ferrochart_core::frame::SeriesKind;
13//! use ferrochart_core::plugin::Placement;
14//! use ferrochart_core::testing::random_walk;
15//! use ferrochart_core::chart::SeriesData;
16//! use ferrochart_core::{Chart, ChartOptions};
17//! use ferrochart_indicators::{Source, macd, sma};
18//!
19//! let mut chart = Chart::new(ChartOptions::default());
20//! let candles = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
21//! chart.set_data(candles, SeriesData::Ohlc(random_walk(7, 500, 0, 60_000)?))?;
22//! chart.add_indicator(candles, Box::new(sma(20, Source::Close)?), Placement::Overlay)?;
23//! chart.add_indicator(candles, Box::new(macd(12, 26, 9, Source::Close)?), Placement::NewPane)?;
24//! # Ok::<(), ferrochart_core::Error>(())
25//! ```
26#![forbid(unsafe_code)]
27
28mod calc;
29mod kernel;
30pub mod named;
31mod runner;
32
33use ferrochart_core::chart::BandOptions;
34use ferrochart_core::data::DataChange;
35use ferrochart_core::geom::Rgba;
36use ferrochart_core::plugin::{
37    Indicator, IndicatorInput, IndicatorOutputs, OutputKind, OutputSpec, Placement,
38};
39use ferrochart_core::{Error, Result};
40
41use calc::{
42    AdxCalc, AroonCalc, AtrCalc, BollCalc, Calc, CciCalc, ChangeCalc, CmfCalc, DemaCalc,
43    DonchianCalc, EmaCalc, HmaCalc, IchimokuCalc, KeltnerCalc, MacdCalc, MfiCalc, ObvCalc, RsiCalc,
44    SarCalc, SmaCalc, StochCalc, StochRsiCalc, SuperTrendCalc, TemaCalc, TrixCalc, VolumeMaCalc,
45    VwapCalc, VwmaCalc, WillrCalc, WmaCalc,
46};
47pub use calc::{Source, VwapAnchor};
48use runner::{Factory, Runner};
49
50/// A built-in indicator, ready for
51/// [`Chart::add_indicator`](ferrochart_core::Chart::add_indicator).
52pub struct Builtin {
53    name: String,
54    outputs: Vec<OutputSpec>,
55    placement: Placement,
56    warmup: usize,
57    volume: bool,
58    runner: Runner,
59}
60
61impl std::fmt::Debug for Builtin {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.debug_struct("Builtin")
64            .field("name", &self.name)
65            .field("outputs", &self.outputs)
66            .finish_non_exhaustive()
67    }
68}
69
70impl Indicator for Builtin {
71    fn name(&self) -> &str {
72        &self.name
73    }
74
75    fn outputs(&self) -> &[OutputSpec] {
76        &self.outputs
77    }
78
79    fn default_placement(&self) -> Placement {
80        self.placement
81    }
82
83    fn warmup(&self) -> usize {
84        self.warmup
85    }
86
87    fn needs_volume(&self) -> bool {
88        self.volume
89    }
90
91    fn update(
92        &mut self,
93        input: &IndicatorInput<'_>,
94        change: DataChange,
95        out: &mut IndicatorOutputs,
96    ) {
97        match change {
98            DataChange::Append { count } => self.runner.append(input, count, out),
99            DataChange::UpdateLast => self.runner.update_last(input, out),
100            DataChange::Replace | DataChange::Prepend { .. } => self.runner.full(input, out),
101        }
102    }
103}
104
105/// Default colors.
106const BLUE: u32 = 0x0029_62FF;
107const ORANGE: u32 = 0x00FF_9800;
108const PURPLE: u32 = 0x009C_27B0;
109const GREEN: u32 = 0x0026_A69A;
110const RED: u32 = 0x00EF_5350;
111const GRAY: u32 = 0x0078_7B86;
112
113const fn out(name: &'static str, color: u32) -> OutputSpec {
114    OutputSpec {
115        name,
116        kind: OutputKind::Line,
117        color: Some(Rgba::hex(color)),
118        shift: 0,
119        fill_to: None,
120    }
121}
122
123/// An upper line filled to the lower one (output 2) with the default color.
124fn upper_band() -> OutputSpec {
125    OutputSpec {
126        fill_to: Some((2, BandOptions::default())),
127        ..out("upper", BLUE)
128    }
129}
130
131struct Def {
132    name: String,
133    outputs: Vec<OutputSpec>,
134    placement: Placement,
135    warmup: usize,
136    volume: bool,
137}
138
139fn build(def: Def, factory: Factory) -> Builtin {
140    Builtin {
141        name: def.name,
142        outputs: def.outputs,
143        placement: def.placement,
144        warmup: def.warmup,
145        volume: def.volume,
146        runner: Runner::new(factory),
147    }
148}
149
150fn factory<C: Calc + 'static>(f: impl Fn() -> C + Send + 'static) -> Factory {
151    Box::new(move || Box::new(f()) as Box<dyn Calc>)
152}
153
154fn period(n: usize, min: usize) -> Result<usize> {
155    if n >= min {
156        Ok(n)
157    } else if min == 1 {
158        Err(Error::InvalidArgument("periods must be at least 1"))
159    } else {
160        Err(Error::InvalidArgument("the period is too short"))
161    }
162}
163
164fn factor(x: f64) -> Result<f64> {
165    if x.is_finite() && x > 0.0 {
166        Ok(x)
167    } else {
168        Err(Error::InvalidArgument("multipliers must be finite and > 0"))
169    }
170}
171
172/// Single-output overlay on a price.
173fn overlay<C: Calc + 'static>(
174    name: String,
175    output: &'static str,
176    warmup: usize,
177    volume: bool,
178    f: impl Fn() -> C + Send + 'static,
179) -> Builtin {
180    build(
181        Def {
182            name,
183            outputs: vec![out(output, BLUE)],
184            placement: Placement::Overlay,
185            warmup,
186            volume,
187        },
188        factory(f),
189    )
190}
191
192// ---- 1. moving averages ------------------------------------------------------
193
194/// Simple moving average (`docs/book/src/indicators.md`, SMA).
195///
196/// # Errors
197///
198/// [`Error::InvalidArgument`] if `n` is 0.
199pub fn sma(n: usize, source: Source) -> Result<Builtin> {
200    let n = period(n, 1)?;
201    Ok(overlay(
202        format!("SMA {n}"),
203        "sma",
204        n - 1,
205        false,
206        move || SmaCalc::new(n, source),
207    ))
208}
209
210/// Exponential moving average with an SMA seed (`docs/book/src/indicators.md`, EMA).
211///
212/// # Errors
213///
214/// [`Error::InvalidArgument`] if `n` is 0.
215pub fn ema(n: usize, source: Source) -> Result<Builtin> {
216    let n = period(n, 1)?;
217    Ok(overlay(
218        format!("EMA {n}"),
219        "ema",
220        n - 1,
221        false,
222        move || EmaCalc::new(n, source),
223    ))
224}
225
226/// Linearly weighted moving average (`docs/book/src/indicators.md`, WMA).
227///
228/// # Errors
229///
230/// [`Error::InvalidArgument`] if `n` is 0.
231pub fn wma(n: usize, source: Source) -> Result<Builtin> {
232    let n = period(n, 1)?;
233    Ok(overlay(
234        format!("WMA {n}"),
235        "wma",
236        n - 1,
237        false,
238        move || WmaCalc::new(n, source),
239    ))
240}
241
242/// Hull moving average (`docs/book/src/indicators.md`, HMA).
243///
244/// # Errors
245///
246/// [`Error::InvalidArgument`] if `n` is less than 2.
247pub fn hma(n: usize, source: Source) -> Result<Builtin> {
248    let n = period(n, 2)?;
249    Ok(overlay(
250        format!("HMA {n}"),
251        "hma",
252        n + n.isqrt() - 2,
253        false,
254        move || HmaCalc::new(n, source),
255    ))
256}
257
258/// Volume-weighted moving average (`docs/book/src/indicators.md`, VWMA).
259///
260/// # Errors
261///
262/// [`Error::InvalidArgument`] if `n` is 0.
263pub fn vwma(n: usize, source: Source) -> Result<Builtin> {
264    let n = period(n, 1)?;
265    Ok(overlay(
266        format!("VWMA {n}"),
267        "vwma",
268        n - 1,
269        true,
270        move || VwmaCalc::new(n, source),
271    ))
272}
273
274/// Double exponential moving average (`docs/book/src/indicators.md`, DEMA).
275///
276/// # Errors
277///
278/// [`Error::InvalidArgument`] if `n` is 0.
279pub fn dema(n: usize, source: Source) -> Result<Builtin> {
280    let n = period(n, 1)?;
281    Ok(overlay(
282        format!("DEMA {n}"),
283        "dema",
284        2 * (n - 1),
285        false,
286        move || DemaCalc::new(n, source),
287    ))
288}
289
290/// Triple exponential moving average (`docs/book/src/indicators.md`, TEMA).
291///
292/// # Errors
293///
294/// [`Error::InvalidArgument`] if `n` is 0.
295pub fn tema(n: usize, source: Source) -> Result<Builtin> {
296    let n = period(n, 1)?;
297    Ok(overlay(
298        format!("TEMA {n}"),
299        "tema",
300        3 * (n - 1),
301        false,
302        move || TemaCalc::new(n, source),
303    ))
304}
305
306/// Moving average of the volume, on the volume's pane and scale
307/// (`docs/book/src/indicators.md`, Volume MA).
308///
309/// # Errors
310///
311/// [`Error::InvalidArgument`] if `n` is 0.
312pub fn volume_ma(n: usize) -> Result<Builtin> {
313    let n = period(n, 1)?;
314    Ok(build(
315        Def {
316            name: format!("Volume MA {n}"),
317            outputs: vec![out("vma", ORANGE)],
318            placement: Placement::Volume,
319            warmup: n - 1,
320            volume: true,
321        },
322        factory(move || VolumeMaCalc::new(n)),
323    ))
324}
325
326// ---- 2. channels -------------------------------------------------------------
327
328/// Bollinger bands: upper, mid, lower (`docs/book/src/indicators.md`, BOLL).
329///
330/// # Errors
331///
332/// [`Error::InvalidArgument`] if `n` is 0 or `k` is not finite and positive.
333pub fn boll(n: usize, k: f64, source: Source) -> Result<Builtin> {
334    let n = period(n, 1)?;
335    let k = factor(k)?;
336    Ok(build(
337        Def {
338            name: format!("BOLL {n} {k}"),
339            outputs: vec![upper_band(), out("mid", ORANGE), out("lower", BLUE)],
340            placement: Placement::Overlay,
341            warmup: n - 1,
342            volume: false,
343        },
344        factory(move || BollCalc::new(n, k, source)),
345    ))
346}
347
348/// Keltner channel: upper, mid, lower (`docs/book/src/indicators.md`, Keltner).
349///
350/// # Errors
351///
352/// [`Error::InvalidArgument`] for a zero period or a multiplier that is not
353/// finite and positive.
354pub fn keltner(n: usize, m: f64, atr_n: usize) -> Result<Builtin> {
355    let (n, atr_n, m) = (period(n, 1)?, period(atr_n, 1)?, factor(m)?);
356    Ok(build(
357        Def {
358            name: format!("Keltner {n} {m} {atr_n}"),
359            outputs: vec![upper_band(), out("mid", ORANGE), out("lower", BLUE)],
360            placement: Placement::Overlay,
361            warmup: (n - 1).max(atr_n),
362            volume: false,
363        },
364        factory(move || KeltnerCalc::new(n, m, atr_n)),
365    ))
366}
367
368/// Donchian channel: upper, mid, lower (`docs/book/src/indicators.md`, Donchian).
369///
370/// # Errors
371///
372/// [`Error::InvalidArgument`] if `n` is 0.
373pub fn donchian(n: usize) -> Result<Builtin> {
374    let n = period(n, 1)?;
375    Ok(build(
376        Def {
377            name: format!("Donchian {n}"),
378            outputs: vec![out("upper", BLUE), out("mid", ORANGE), out("lower", BLUE)],
379            placement: Placement::Overlay,
380            warmup: n - 1,
381            volume: false,
382        },
383        factory(move || DonchianCalc::new(n)),
384    ))
385}
386
387/// Ichimoku cloud: tenkan, kijun, `span_a`, `span_b` (drawn `shift` bars
388/// later), chikou (drawn `shift` bars earlier) (`docs/book/src/indicators.md`,
389/// Ichimoku).
390///
391/// # Errors
392///
393/// [`Error::InvalidArgument`] for a zero period or shift.
394pub fn ichimoku(tenkan: usize, kijun: usize, senkou: usize, shift: usize) -> Result<Builtin> {
395    let (t, k, s) = (period(tenkan, 1)?, period(kijun, 1)?, period(senkou, 1)?);
396    let shift = period(shift, 1)?;
397    let d = i32::try_from(shift).map_err(|_| Error::InvalidArgument("the shift is too large"))?;
398    let shifted = |name, color, by| OutputSpec {
399        shift: by,
400        ..out(name, color)
401    };
402    Ok(build(
403        Def {
404            name: format!("Ichimoku {t} {k} {s} {shift}"),
405            outputs: vec![
406                out("tenkan", BLUE),
407                out("kijun", RED),
408                OutputSpec {
409                    // The cloud: green where span A is above span B, red below.
410                    fill_to: Some((
411                        3,
412                        BandOptions {
413                            fill: Some(Rgba::hex(GREEN).with_alpha(0x33)),
414                            fill_crossed: Some(Rgba::hex(RED).with_alpha(0x33)),
415                        },
416                    )),
417                    ..shifted("span_a", GREEN, d)
418                },
419                shifted("span_b", RED, d),
420                shifted("chikou", PURPLE, -d),
421            ],
422            placement: Placement::Overlay,
423            warmup: (s - 1).max(k - 1).max(t - 1),
424            volume: false,
425        },
426        factory(move || IchimokuCalc::new(t, k, s)),
427    ))
428}
429
430/// Parabolic SAR, as TA-Lib computes it (`docs/book/src/indicators.md`, SAR).
431///
432/// # Errors
433///
434/// [`Error::InvalidArgument`] unless `0 < af_start ≤ af_max` and
435/// `af_step > 0`, all finite.
436pub fn sar(af_start: f64, af_step: f64, af_max: f64) -> Result<Builtin> {
437    let (a, s, m) = (factor(af_start)?, factor(af_step)?, factor(af_max)?);
438    if a > m {
439        return Err(Error::InvalidArgument("af_start must not exceed af_max"));
440    }
441    Ok(build(
442        Def {
443            name: format!("SAR {a} {s} {m}"),
444            outputs: vec![OutputSpec {
445                kind: OutputKind::Points,
446                ..out("sar", BLUE)
447            }],
448            placement: Placement::Overlay,
449            warmup: 1,
450            volume: false,
451        },
452        factory(move || SarCalc::new(a, s, m)),
453    ))
454}
455
456/// `SuperTrend`: the lower band in up trends (`long`), the upper band in down
457/// trends (`short`) (`docs/book/src/indicators.md`, `SuperTrend`).
458///
459/// # Errors
460///
461/// [`Error::InvalidArgument`] for a zero period or a multiplier that is not
462/// finite and positive.
463pub fn supertrend(atr_n: usize, m: f64) -> Result<Builtin> {
464    let (n, m) = (period(atr_n, 1)?, factor(m)?);
465    Ok(build(
466        Def {
467            name: format!("SuperTrend {n} {m}"),
468            outputs: vec![out("long", GREEN), out("short", RED)],
469            placement: Placement::Overlay,
470            warmup: n,
471            volume: false,
472        },
473        factory(move || SuperTrendCalc::new(n, m)),
474    ))
475}
476
477/// Volume-weighted average price from `anchor` on (`docs/book/src/indicators.md`, VWAP).
478/// `utc_offset_ms` moves the session boundaries.
479///
480/// # Errors
481///
482/// None at the moment; `Result` for consistency with the other indicators.
483pub fn vwap(anchor: VwapAnchor, utc_offset_ms: i64) -> Result<Builtin> {
484    Ok(overlay("VWAP".into(), "vwap", 0, true, move || {
485        VwapCalc::new(anchor, utc_offset_ms)
486    }))
487}
488
489// ---- 3. oscillators ----------------------------------------------------------
490
491/// Single-output oscillator on a new pane.
492fn oscillator<C: Calc + 'static>(
493    name: String,
494    outputs: Vec<OutputSpec>,
495    warmup: usize,
496    volume: bool,
497    f: impl Fn() -> C + Send + 'static,
498) -> Builtin {
499    build(
500        Def {
501            name,
502            outputs,
503            placement: Placement::NewPane,
504            warmup,
505            volume,
506        },
507        factory(f),
508    )
509}
510
511/// MACD: macd, signal, hist (`docs/book/src/indicators.md`, MACD).
512///
513/// # Errors
514///
515/// [`Error::InvalidArgument`] for a zero period.
516pub fn macd(fast: usize, slow: usize, signal: usize, source: Source) -> Result<Builtin> {
517    let (f, s, g) = (period(fast, 1)?, period(slow, 1)?, period(signal, 1)?);
518    let hist = OutputSpec {
519        color: Some(Rgba::hex(GRAY)),
520        ..OutputSpec::histogram("hist")
521    };
522    Ok(oscillator(
523        format!("MACD {f} {s} {g}"),
524        vec![out("macd", BLUE), out("signal", ORANGE), hist],
525        f.max(s) + g - 2,
526        false,
527        move || MacdCalc::new(f, s, g, source),
528    ))
529}
530
531/// Relative strength index (`docs/book/src/indicators.md`, RSI).
532///
533/// # Errors
534///
535/// [`Error::InvalidArgument`] if `n` is 0.
536pub fn rsi(n: usize, source: Source) -> Result<Builtin> {
537    let n = period(n, 1)?;
538    Ok(oscillator(
539        format!("RSI {n}"),
540        vec![out("rsi", PURPLE)],
541        n,
542        false,
543        move || RsiCalc::new(n, source),
544    ))
545}
546
547/// Stochastic oscillator: %K, %D (`docs/book/src/indicators.md`, Stoch).
548///
549/// # Errors
550///
551/// [`Error::InvalidArgument`] for a zero period.
552pub fn stoch(k: usize, smooth_k: usize, d: usize) -> Result<Builtin> {
553    let (k, sk, d) = (period(k, 1)?, period(smooth_k, 1)?, period(d, 1)?);
554    Ok(oscillator(
555        format!("Stoch {k} {sk} {d}"),
556        vec![out("k", BLUE), out("d", ORANGE)],
557        k + sk + d - 3,
558        false,
559        move || StochCalc::new(k, sk, d),
560    ))
561}
562
563/// Stochastic RSI: %K, %D (`docs/book/src/indicators.md`, `StochRSI`).
564///
565/// # Errors
566///
567/// [`Error::InvalidArgument`] for a zero period.
568pub fn stochrsi(
569    rsi_n: usize,
570    stoch_n: usize,
571    smooth_k: usize,
572    d: usize,
573    source: Source,
574) -> Result<Builtin> {
575    let (r, s) = (period(rsi_n, 1)?, period(stoch_n, 1)?);
576    let (sk, d) = (period(smooth_k, 1)?, period(d, 1)?);
577    Ok(oscillator(
578        format!("StochRSI {r} {s} {sk} {d}"),
579        vec![out("k", BLUE), out("d", ORANGE)],
580        r + s + sk + d - 3,
581        false,
582        move || StochRsiCalc::new(r, s, sk, d, source),
583    ))
584}
585
586/// Commodity channel index (`docs/book/src/indicators.md`, CCI).
587///
588/// # Errors
589///
590/// [`Error::InvalidArgument`] if `n` is 0.
591pub fn cci(n: usize) -> Result<Builtin> {
592    let n = period(n, 1)?;
593    Ok(oscillator(
594        format!("CCI {n}"),
595        vec![out("cci", BLUE)],
596        n - 1,
597        false,
598        move || CciCalc::new(n),
599    ))
600}
601
602/// Williams %R (`docs/book/src/indicators.md`, Williams %R).
603///
604/// # Errors
605///
606/// [`Error::InvalidArgument`] if `n` is 0.
607pub fn willr(n: usize) -> Result<Builtin> {
608    let n = period(n, 1)?;
609    Ok(oscillator(
610        format!("%R {n}"),
611        vec![out("wr", PURPLE)],
612        n - 1,
613        false,
614        move || WillrCalc::new(n),
615    ))
616}
617
618/// Money flow index (`docs/book/src/indicators.md`, MFI).
619///
620/// # Errors
621///
622/// [`Error::InvalidArgument`] if `n` is 0.
623pub fn mfi(n: usize) -> Result<Builtin> {
624    let n = period(n, 1)?;
625    Ok(oscillator(
626        format!("MFI {n}"),
627        vec![out("mfi", PURPLE)],
628        n,
629        true,
630        move || MfiCalc::new(n),
631    ))
632}
633
634/// ADX with the directional indicators: adx, `plus_di`, `minus_di`
635/// (`docs/book/src/indicators.md`, ADX / DMI).
636///
637/// # Errors
638///
639/// [`Error::InvalidArgument`] if `n` is 0.
640pub fn adx(n: usize) -> Result<Builtin> {
641    let n = period(n, 1)?;
642    Ok(oscillator(
643        format!("ADX {n}"),
644        vec![
645            out("adx", ORANGE),
646            out("plus_di", GREEN),
647            out("minus_di", RED),
648        ],
649        2 * n - 1,
650        false,
651        move || AdxCalc::new(n),
652    ))
653}
654
655/// Average true range (`docs/book/src/indicators.md`, ATR).
656///
657/// # Errors
658///
659/// [`Error::InvalidArgument`] if `n` is 0.
660pub fn atr(n: usize) -> Result<Builtin> {
661    let n = period(n, 1)?;
662    Ok(oscillator(
663        format!("ATR {n}"),
664        vec![out("atr", RED)],
665        n,
666        false,
667        move || AtrCalc::new(n),
668    ))
669}
670
671/// On-balance volume (`docs/book/src/indicators.md`, OBV).
672///
673/// # Errors
674///
675/// None at the moment; `Result` for consistency with the other indicators.
676pub fn obv() -> Result<Builtin> {
677    Ok(oscillator(
678        "OBV".into(),
679        vec![out("obv", BLUE)],
680        0,
681        true,
682        ObvCalc::default,
683    ))
684}
685
686/// Chaikin money flow (`docs/book/src/indicators.md`, CMF).
687///
688/// # Errors
689///
690/// [`Error::InvalidArgument`] if `n` is 0.
691pub fn cmf(n: usize) -> Result<Builtin> {
692    let n = period(n, 1)?;
693    Ok(oscillator(
694        format!("CMF {n}"),
695        vec![out("cmf", GREEN)],
696        n - 1,
697        true,
698        move || CmfCalc::new(n),
699    ))
700}
701
702/// Rate of change in percent (`docs/book/src/indicators.md`, ROC).
703///
704/// # Errors
705///
706/// [`Error::InvalidArgument`] if `n` is 0.
707pub fn roc(n: usize, source: Source) -> Result<Builtin> {
708    let n = period(n, 1)?;
709    Ok(oscillator(
710        format!("ROC {n}"),
711        vec![out("roc", BLUE)],
712        n,
713        false,
714        move || ChangeCalc::roc(n, source),
715    ))
716}
717
718/// Momentum (`docs/book/src/indicators.md`, Momentum).
719///
720/// # Errors
721///
722/// [`Error::InvalidArgument`] if `n` is 0.
723pub fn momentum(n: usize, source: Source) -> Result<Builtin> {
724    let n = period(n, 1)?;
725    Ok(oscillator(
726        format!("MOM {n}"),
727        vec![out("mom", BLUE)],
728        n,
729        false,
730        move || ChangeCalc::momentum(n, source),
731    ))
732}
733
734/// TRIX (`docs/book/src/indicators.md`, TRIX).
735///
736/// # Errors
737///
738/// [`Error::InvalidArgument`] if `n` is 0.
739pub fn trix(n: usize, source: Source) -> Result<Builtin> {
740    let n = period(n, 1)?;
741    Ok(oscillator(
742        format!("TRIX {n}"),
743        vec![out("trix", RED)],
744        3 * (n - 1) + 1,
745        false,
746        move || TrixCalc::new(n, source),
747    ))
748}
749
750/// Aroon: up, down (`docs/book/src/indicators.md`, Aroon).
751///
752/// # Errors
753///
754/// [`Error::InvalidArgument`] if `n` is 0.
755pub fn aroon(n: usize) -> Result<Builtin> {
756    let n = period(n, 1)?;
757    Ok(oscillator(
758        format!("Aroon {n}"),
759        vec![out("up", GREEN), out("down", RED)],
760        n,
761        false,
762        move || AroonCalc::new(n),
763    ))
764}