ferrochart_core/transform/
renko.rs1use crate::error::{Error, Result};
4use crate::frame::SeriesKind;
5use crate::plugin::{InputBar, SeriesTransform, TransformOutput};
6
7use super::{bar_kind, element, emit, fresh_volume, positive};
8
9#[derive(Clone, Copy, Debug, PartialEq)]
11enum BoxSize {
12 Fixed(f64),
13 Atr(usize),
15}
16
17#[derive(Clone, Copy, Debug, PartialEq)]
19struct Grid {
20 anchor: f64,
21 size: f64,
22 top: i64,
23 bot: i64,
24}
25
26#[derive(Clone, Copy, Debug, PartialEq)]
27struct State {
28 grid: Option<Grid>,
29 count: usize,
31 tr_sum: f64,
32 prev_close: Option<f64>,
33 volume: f64,
35}
36
37const START: State = State {
38 grid: None,
39 count: 0,
40 tr_sum: 0.0,
41 prev_close: None,
42 volume: 0.0,
43};
44
45#[derive(Clone, Debug)]
73pub struct Renko {
74 size: BoxSize,
75 kind: SeriesKind,
76 state: State,
77}
78
79impl Renko {
80 pub fn fixed(size: f64) -> Result<Self> {
86 Ok(Self {
87 size: BoxSize::Fixed(positive(size, "the brick size must be positive")?),
88 kind: SeriesKind::Candlestick,
89 state: START,
90 })
91 }
92
93 pub fn atr(n: usize) -> Result<Self> {
99 if n == 0 {
100 return Err(Error::InvalidArgument("the ATR period must be at least 1"));
101 }
102 Ok(Self {
103 size: BoxSize::Atr(n),
104 kind: SeriesKind::Candlestick,
105 state: START,
106 })
107 }
108
109 pub fn with_kind(mut self, kind: SeriesKind) -> Result<Self> {
115 self.kind = bar_kind(kind)?;
116 Ok(self)
117 }
118
119 pub fn brick_size(&self) -> Option<f64> {
121 self.state.grid.map(|g| g.size)
122 }
123
124 fn step(&self, s: &mut State, bar: InputBar, out: &mut TransformOutput) {
125 let c = bar.close;
126 s.volume += bar.volume;
127 let Some(g) = s.grid.as_mut() else {
128 match self.size {
129 BoxSize::Fixed(size) => {
130 s.grid = Some(Grid {
131 anchor: c,
132 size,
133 top: 0,
134 bot: 0,
135 });
136 }
137 BoxSize::Atr(n) => {
138 let tr = match s.prev_close {
139 None => bar.high - bar.low,
140 Some(p) => (bar.high - bar.low)
141 .max((bar.high - p).abs())
142 .max((bar.low - p).abs()),
143 };
144 s.count += 1;
145 s.tr_sum += tr;
146 s.prev_close = Some(c);
147 if s.count >= n && s.tr_sum > 0.0 {
148 s.grid = Some(Grid {
149 anchor: c,
150 size: s.tr_sum / s.count as f64,
151 top: 0,
152 bot: 0,
153 });
154 }
155 }
156 }
157 return;
158 };
159 let level = |k: i64| g.anchor + k as f64 * g.size;
160 loop {
161 let (open, close) = if c >= level(g.top + 1) {
162 let x = (level(g.top), level(g.top + 1));
163 g.bot = g.top;
164 g.top += 1;
165 x
166 } else if c <= level(g.bot - 1) {
167 let x = (level(g.bot), level(g.bot - 1));
168 g.top = g.bot;
169 g.bot -= 1;
170 x
171 } else {
172 break;
173 };
174 let v = core::mem::replace(&mut s.volume, fresh_volume(bar.volume));
175 if !emit(out, element(open, close, v, 0)) {
176 break;
177 }
178 }
179 }
180}
181
182impl SeriesTransform for Renko {
183 fn name(&self) -> &'static str {
184 "renko"
185 }
186
187 fn output_kind(&self) -> SeriesKind {
188 self.kind
189 }
190
191 fn push(&mut self, bar: InputBar, out: &mut TransformOutput) {
192 let mut s = self.state;
193 self.step(&mut s, bar, out);
194 self.state = s;
195 }
196
197 fn peek(&self, bar: InputBar, out: &mut TransformOutput) {
198 let mut s = self.state;
199 self.step(&mut s, bar, out);
200 }
201
202 fn reset(&mut self) {
203 self.state = START;
204 }
205}
206
207#[cfg(test)]
208#[allow(clippy::float_cmp)]
209mod tests {
210 use super::*;
211 use crate::transform::tests::{oc, run, tick};
212
213 #[test]
214 fn bricks_continue_with_one_box_and_reverse_with_two() {
215 let mut r = Renko::fixed(1.0).unwrap();
216 let bars: Vec<_> = [10.0, 11.5, 12.0, 10.9, 10.0, 9.0, 6.4]
217 .iter()
218 .enumerate()
219 .map(|(i, &p)| tick(i as i64, p))
220 .collect();
221 let out = run(&mut r, &bars);
222 assert_eq!(
223 oc(&out),
224 [
225 (10.0, 11.0),
226 (11.0, 12.0),
227 (11.0, 10.0),
229 (10.0, 9.0),
230 (9.0, 8.0),
231 (8.0, 7.0),
232 ]
233 );
234 let v: Vec<f64> = out.iter().map(|b| b.volume).collect();
236 assert_eq!(v, [2.0, 1.0, 2.0, 1.0, 1.0, 0.0]);
237 }
238
239 #[test]
240 fn atr_size_is_fixed_after_n_inputs() {
241 let mut r = Renko::atr(2).unwrap();
242 let bars = [
243 InputBar {
244 time: 0,
245 open: 10.0,
246 high: 11.0,
247 low: 10.0,
248 close: 10.5,
249 volume: f64::NAN,
250 },
251 InputBar {
252 time: 1,
253 open: 10.5,
254 high: 13.5,
255 low: 10.5,
256 close: 13.0,
257 volume: f64::NAN,
258 },
259 tick(2, 15.0),
260 tick(3, 100.0),
261 ];
262 let out = run(&mut r, &bars[..3]);
264 assert_eq!(oc(&out), [(13.0, 15.0)]);
265 assert!(out[0].volume.is_nan());
266 let out = run(&mut r, &bars);
267 assert_eq!(out.len(), 1 + 42);
268 assert_eq!(r.brick_size(), Some(2.0));
269 }
270}