ferrochart_core/plugin/transform.rs
1//! Series transforms: input bars in, a new
2//! OHLC-like series out (Renko, Range Bars, Kagi, Point & Figure). The
3//! built-in transforms are in [`crate::transform`].
4
5use crate::frame::SeriesKind;
6
7use super::InputBar;
8
9/// One output element of a [`SeriesTransform`].
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct TransformBar {
12 /// Open (Kagi / P&F: where the line or column starts).
13 pub open: f64,
14 /// High.
15 pub high: f64,
16 /// Low.
17 pub low: f64,
18 /// Close (Kagi / P&F: where the line or column ends).
19 pub close: f64,
20 /// Volume; NaN when the input has none.
21 pub volume: f64,
22 /// Kagi: 1 thick (yang) / 0 thin (yin) at the end of the line; P&F: 1 X
23 /// / 0 O; otherwise 0.
24 pub flag: u8,
25}
26
27/// Elements one `push` or `peek` call may write.
28pub const MAX_OUTPUT_PER_CALL: usize = 65_536;
29
30/// Reused output buffer of a [`SeriesTransform`] call; clearing keeps the
31/// capacity, so a warmed-up buffer does not allocate.
32#[derive(Debug, Default)]
33pub struct TransformOutput {
34 bars: Vec<TransformBar>,
35 /// Why the last call stopped early.
36 pub(crate) failed: Option<crate::Error>,
37}
38
39impl TransformOutput {
40 /// Adds an element. Returns `false` when the call already wrote
41 /// [`MAX_OUTPUT_PER_CALL`] elements or memory ran out: the transform
42 /// should stop, and core reports the error.
43 pub fn push(&mut self, bar: TransformBar) -> bool {
44 if self.failed.is_some() {
45 return false;
46 }
47 if self.bars.len() >= MAX_OUTPUT_PER_CALL {
48 self.failed = Some(crate::Error::InvalidArgument(
49 "a transform input produced too many elements (box size too small)",
50 ));
51 return false;
52 }
53 if self.bars.try_reserve(1).is_err() {
54 self.failed = Some(crate::Error::OutOfMemory);
55 return false;
56 }
57 self.bars.push(bar);
58 true
59 }
60
61 /// The elements written since the last clear.
62 pub fn as_slice(&self) -> &[TransformBar] {
63 &self.bars
64 }
65
66 pub(crate) fn clear(&mut self) {
67 self.bars.clear();
68 self.failed = None;
69 }
70
71 /// `Err` if the last call stopped early.
72 pub(crate) fn check(&self) -> crate::Result<()> {
73 self.failed.clone().map_or(Ok(()), Err)
74 }
75}
76
77/// Turns input bars into a new series, with the peek/push model of
78/// indicators: the output is the elements `push` wrote for every
79/// input but the last (finished, never changed again) followed by what
80/// `peek` writes for the last input (the elements it would finish and the
81/// ones still forming). Gap bars are never passed in.
82///
83/// # Examples
84///
85/// ```
86/// use ferrochart_core::frame::SeriesKind;
87/// use ferrochart_core::plugin::{InputBar, SeriesTransform, TransformBar, TransformOutput};
88///
89/// /// One element per input whose close moved by at least 1 since the last one.
90/// #[derive(Default)]
91/// struct Steps {
92/// last: Option<f64>,
93/// }
94///
95/// impl Steps {
96/// fn step(last: Option<f64>, bar: &InputBar) -> Option<TransformBar> {
97/// let from = last?;
98/// ((bar.close - from).abs() >= 1.0).then(|| TransformBar {
99/// open: from,
100/// high: from.max(bar.close),
101/// low: from.min(bar.close),
102/// close: bar.close,
103/// volume: f64::NAN,
104/// flag: 0,
105/// })
106/// }
107/// }
108///
109/// impl SeriesTransform for Steps {
110/// fn name(&self) -> &str {
111/// "steps"
112/// }
113/// fn output_kind(&self) -> SeriesKind {
114/// SeriesKind::Candlestick
115/// }
116/// fn push(&mut self, bar: InputBar, out: &mut TransformOutput) {
117/// match Self::step(self.last, &bar) {
118/// Some(b) => {
119/// out.push(b);
120/// self.last = Some(bar.close);
121/// }
122/// None if self.last.is_none() => self.last = Some(bar.close),
123/// None => {}
124/// }
125/// }
126/// fn peek(&self, bar: InputBar, out: &mut TransformOutput) {
127/// if let Some(b) = Self::step(self.last, &bar) {
128/// out.push(b);
129/// }
130/// }
131/// fn reset(&mut self) {
132/// self.last = None;
133/// }
134/// }
135/// ```
136pub trait SeriesTransform: Send {
137 /// Name, e.g. `"renko"`.
138 fn name(&self) -> &str;
139 /// How the output is drawn: `Candlestick`, `OhlcBar`, `Kagi` or
140 /// `PointFigure`.
141 fn output_kind(&self) -> SeriesKind;
142 /// Commits `bar` and writes the elements it finishes.
143 fn push(&mut self, bar: InputBar, out: &mut TransformOutput);
144 /// Writes, without changing the state, the elements `bar` would finish
145 /// and the ones still forming if it were the last input.
146 fn peek(&self, bar: InputBar, out: &mut TransformOutput);
147 /// Forgets all inputs.
148 fn reset(&mut self);
149 /// Point & Figure: the price height of one box, to stack the X/O marks.
150 fn box_size(&self) -> Option<f64> {
151 None
152 }
153}