ferrochart_core/plugin/mod.rs
1//! Plugin interfaces: indicators, custom
2//! series, layer plugins and series transforms, and [`MinMaxIndex`] for
3//! plugins' range queries.
4//!
5//! Core schedules indicator computation, so the [`Indicator`] trait lives
6//! here; `ferrochart-indicators` implements the built-in indicators. Each
7//! output of an indicator is an ordinary value series of the chart
8//! ([`crate::Chart::indicator_series`]); [`Indicator::update`] writes its
9//! values straight into those series' storage through [`IndicatorOutputs`].
10
11use crate::chart::BandOptions;
12use crate::data::{DataChange, PaneId, Timestamp};
13use crate::geom::Rgba;
14use crate::series::Source;
15
16mod custom;
17mod layer;
18mod min_max;
19mod transform;
20
21pub use custom::{AxisMode, CustomSeries, SeriesCtx};
22pub(crate) use custom::{CustomChange, CustomStore};
23pub use layer::{LayerCtx, LayerPlugin, LayerPosition};
24pub use min_max::MinMaxIndex;
25pub use transform::{MAX_OUTPUT_PER_CALL, SeriesTransform, TransformBar, TransformOutput};
26
27/// Where an indicator's outputs are shown.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum Placement {
30 /// On the pane of the source series, sharing its price scale.
31 Overlay,
32 /// On a new pane below the others.
33 NewPane,
34 /// On an existing pane.
35 Pane(PaneId),
36 /// On the pane of the source's volume series, on the volume's scale (as
37 /// high as the bars); a new pane when the source has no volume series.
38 Volume,
39}
40
41/// How an indicator output is drawn.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub enum OutputKind {
44 /// A line (a `Line` series).
45 Line,
46 /// Bars from 0 (a `Histogram` series).
47 Histogram,
48 /// Dots (a `Points` series), e.g. Parabolic SAR.
49 Points,
50}
51
52/// One output of an indicator.
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct OutputSpec {
55 /// Short name, e.g. `"signal"`.
56 pub name: &'static str,
57 /// How it is drawn.
58 pub kind: OutputKind,
59 /// Default color; `None` picks one from the chart's palette.
60 pub color: Option<Rgba>,
61 /// Display shift in bars (`SeriesOptions::shift`): positive values are
62 /// drawn later (Ichimoku's leading spans), negative ones earlier.
63 pub shift: i32,
64 /// Fill from this output to output `.0` (a band), e.g. between
65 /// Bollinger's upper and lower lines; see
66 /// [`Chart::indicator_bands`](crate::Chart::indicator_bands).
67 pub fill_to: Option<(usize, BandOptions)>,
68}
69
70impl OutputSpec {
71 /// A line output with no default color and no shift.
72 ///
73 /// # Examples
74 ///
75 /// ```
76 /// use ferrochart_core::plugin::{OutputKind, OutputSpec};
77 ///
78 /// let spec = OutputSpec::line("sma");
79 /// assert_eq!((spec.kind, spec.shift), (OutputKind::Line, 0));
80 /// ```
81 pub const fn line(name: &'static str) -> Self {
82 Self {
83 name,
84 kind: OutputKind::Line,
85 color: None,
86 shift: 0,
87 fill_to: None,
88 }
89 }
90
91 /// A histogram output with no default color and no shift.
92 pub const fn histogram(name: &'static str) -> Self {
93 Self {
94 name,
95 kind: OutputKind::Histogram,
96 color: None,
97 shift: 0,
98 fill_to: None,
99 }
100 }
101}
102
103/// One bar of an indicator's source.
104#[derive(Clone, Copy, Debug, PartialEq)]
105pub struct InputBar {
106 /// Bar time (UTC milliseconds).
107 pub time: Timestamp,
108 /// Open (single-value sources: the value).
109 pub open: f64,
110 /// High.
111 pub high: f64,
112 /// Low.
113 pub low: f64,
114 /// Close.
115 pub close: f64,
116 /// Volume; NaN when the source has none.
117 pub volume: f64,
118}
119
120/// An indicator's source series, slot by slot: slot `i` is logical index
121/// `first + i` of the time axis, over the logical indices the source covers.
122#[derive(Clone, Copy)]
123pub struct IndicatorInput<'a> {
124 store: Source<'a>,
125 index: &'a crate::data::TimeIndex,
126 first: i64,
127 len: usize,
128}
129
130impl<'a> IndicatorInput<'a> {
131 pub(crate) fn new(store: Source<'a>, index: &'a crate::data::TimeIndex) -> Self {
132 let (first, end) = store.span().unwrap_or((0, 0));
133 Self {
134 store,
135 index,
136 first,
137 len: usize::try_from(end - first).unwrap_or(0),
138 }
139 }
140
141 /// Logical index of slot 0.
142 pub(crate) fn first(&self) -> i64 {
143 self.first
144 }
145
146 /// Number of slots.
147 pub fn len(&self) -> usize {
148 self.len
149 }
150
151 /// Whether there are no slots.
152 pub fn is_empty(&self) -> bool {
153 self.len == 0
154 }
155
156 /// The bar at `slot`; `None` for a gap bar or a slot out of range.
157 pub fn bar(&self, slot: usize) -> Option<InputBar> {
158 if slot >= self.len {
159 return None;
160 }
161 let j = self.first + i64::try_from(slot).ok()?;
162 let [open, high, low, close] = self.store.bar_at(j)?;
163 Some(InputBar {
164 time: self.index.time_at(j)?,
165 open,
166 high,
167 low,
168 close,
169 volume: self.store.volume_at(j).unwrap_or(f64::NAN),
170 })
171 }
172
173 /// Whether the source has volume.
174 pub fn has_volume(&self) -> bool {
175 self.store.has_volume()
176 }
177}
178
179/// Where [`Indicator::update`] writes: for every output, the values of slots
180/// `start()..len()` of the input, all NaN before the call.
181#[derive(Clone, Debug, Default)]
182pub struct IndicatorOutputs {
183 start: usize,
184 len: usize,
185 /// Columns in use; `cols` keeps more (with their capacity) for
186 /// indicators with more outputs, so alternating ones do not allocate.
187 active: usize,
188 cols: Vec<Vec<f64>>,
189}
190
191impl IndicatorOutputs {
192 /// Prepares `outputs` columns for slots `start..len`, keeping capacity.
193 pub(crate) fn reset(&mut self, outputs: usize, start: usize, len: usize) {
194 self.start = start.min(len);
195 self.len = len;
196 if self.cols.len() < outputs {
197 self.cols.resize_with(outputs, Vec::new);
198 }
199 self.active = outputs;
200 for c in &mut self.cols[..outputs] {
201 c.clear();
202 c.resize(len - self.start, f64::NAN);
203 }
204 }
205
206 /// Releases the memory of a full recomputation, keeping room for the
207 /// real-time path (no allocation per tick).
208 pub(crate) fn shrink(&mut self) {
209 for c in &mut self.cols {
210 c.clear();
211 c.shrink_to(64);
212 }
213 }
214
215 pub(crate) fn columns(&self) -> &[Vec<f64>] {
216 &self.cols[..self.active]
217 }
218
219 /// First slot to write.
220 pub fn start(&self) -> usize {
221 self.start
222 }
223
224 /// Number of slots of the input.
225 pub fn len(&self) -> usize {
226 self.len
227 }
228
229 /// Whether there are no slots to write.
230 pub fn is_empty(&self) -> bool {
231 self.start >= self.len
232 }
233
234 /// Values of output `o` for slots `start()..len()`; empty for an output
235 /// that does not exist.
236 pub fn column(&mut self, o: usize) -> &mut [f64] {
237 self.cols[..self.active]
238 .get_mut(o)
239 .map_or(&mut [], Vec::as_mut_slice)
240 }
241}
242
243/// A technical indicator, computed incrementally by
244/// the chart when its source series changes.
245///
246/// `update` gets the source and what changed:
247///
248/// - [`DataChange::Replace`] and [`DataChange::Prepend`]: recompute
249/// everything (`out.start()` is 0);
250/// - [`DataChange::Append`]: the last `count` slots are new
251/// (`out.start() == len − count`);
252/// - [`DataChange::UpdateLast`]: the last slot changed
253/// (`out.start() == len − 1`).
254///
255/// `Append` and `UpdateLast` must be O(1) per slot and must not allocate
256/// (`update_last` is a hot path). Gap bars (`input.bar(i) == None`)
257/// should give NaN.
258pub trait Indicator: Send {
259 /// Display name, e.g. `"SMA 20"`.
260 fn name(&self) -> &str;
261 /// The outputs, in the order of `out.column(o)`.
262 fn outputs(&self) -> &[OutputSpec];
263 /// Where the outputs go by default.
264 fn default_placement(&self) -> Placement;
265 /// Number of leading valid bars whose outputs are NaN.
266 fn warmup(&self) -> usize;
267 /// Whether the indicator reads volume; `add_indicator` refuses sources
268 /// without it.
269 fn needs_volume(&self) -> bool {
270 false
271 }
272 /// Updates the outputs for `change`; see the trait docs.
273 fn update(
274 &mut self,
275 input: &IndicatorInput<'_>,
276 change: DataChange,
277 out: &mut IndicatorOutputs,
278 );
279}