1#![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
50pub 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
105const 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
123fn 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
172fn 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
192pub 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
210pub 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
226pub 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
242pub 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
258pub 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
274pub 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
290pub 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
306pub 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
326pub 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
348pub 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
368pub 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
387pub 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 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
430pub 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
456pub 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
477pub 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
489fn 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
511pub 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
531pub 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
547pub 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
563pub 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
586pub 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
602pub 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
618pub 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
634pub 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
655pub 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
671pub 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
686pub 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
702pub 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
718pub 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
734pub 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
750pub 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}