1use crate::aes::Aesthetic;
8use crate::coord::Coord;
9use crate::data::{DataFrame, Value};
10use crate::position::identity::PositionIdentity;
11use crate::position::Position;
12use crate::render::backend::{DrawBackend, LineStyle, Linetype, RectStyle};
13use crate::render::RenderError;
14use crate::scale::ScaleSet;
15use crate::stat::identity::StatIdentity;
16use crate::stat::Stat;
17use crate::theme::Theme;
18
19use super::{Geom, GeomParams};
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
23pub enum CandleStyle {
24 #[default]
26 Filled,
27 Hollow,
30}
31
32pub struct GeomCandlestick {
35 pub style: CandleStyle,
37 pub up: (u8, u8, u8),
39 pub down: (u8, u8, u8),
41 pub width: f64,
43 pub line_width: f64,
44 pub alpha: f64,
45}
46
47impl Default for GeomCandlestick {
48 fn default() -> Self {
49 GeomCandlestick {
50 style: CandleStyle::Filled,
51 up: (0x0c, 0xa6, 0x78),
52 down: (0xe0, 0x31, 0x31),
53 width: 0.6,
54 line_width: 1.0,
55 alpha: 1.0,
56 }
57 }
58}
59
60pub struct GeomOhlc {
63 pub open_tick: bool,
65 pub up: (u8, u8, u8),
66 pub down: (u8, u8, u8),
67 pub width: f64,
69 pub line_width: f64,
70 pub alpha: f64,
71}
72
73impl Default for GeomOhlc {
74 fn default() -> Self {
75 GeomOhlc {
76 open_tick: true,
77 up: (0x0c, 0xa6, 0x78),
78 down: (0xe0, 0x31, 0x31),
79 width: 0.6,
80 line_width: 1.4,
81 alpha: 1.0,
82 }
83 }
84}
85
86fn ohlc_required() -> Vec<Aesthetic> {
87 vec![
88 Aesthetic::X,
89 Aesthetic::Open,
90 Aesthetic::High,
91 Aesthetic::Low,
92 Aesthetic::Close,
93 ]
94}
95
96fn ohlc_setup(data: &mut DataFrame) {
98 for (src, dst) in [("low", "ymin"), ("high", "ymax")] {
99 if !data.has_column(dst) {
100 if let Some(c) = data.column(src) {
101 let c = c.to_vec();
102 data.add_column(dst.to_string(), c);
103 }
104 }
105 }
106}
107
108struct Period {
110 nx: f64,
111 open: f64,
112 high: f64,
113 low: f64,
114 close: f64,
115 up: bool,
116 up_from_prev: bool,
118}
119
120fn for_each_period(
123 data: &DataFrame,
124 scales: &ScaleSet,
125 width: f64,
126 backend: &mut dyn DrawBackend,
127 mut draw: impl FnMut(&Period, f64, &mut dyn DrawBackend) -> Result<(), RenderError>,
128) -> Result<(), RenderError> {
129 let col = |n: &str| {
130 data.column(n)
131 .ok_or_else(|| RenderError::MissingAesthetic(n.into()))
132 };
133 let (x_col, h_col, l_col, c_col) = (col("x")?, col("high")?, col("low")?, col("close")?);
134 let o_col = data.column("open").unwrap_or(c_col);
136 let x_scale = scales.get(&Aesthetic::X);
137 let y_scale = scales.get(&Aesthetic::Y);
138 let my = |v: f64| y_scale.map(|s| s.map(&Value::Float(v))).unwrap_or(0.0);
139 let half = if x_scale.map(|s| s.is_discrete()).unwrap_or(false) {
140 let n = x_scale.map(|s| s.breaks().len()).unwrap_or(1).max(1) as f64;
141 width / n / 2.0
142 } else {
143 super::continuous_bar_half_width(
144 x_col.iter().filter_map(|v| x_scale.map(|s| s.map(v))),
145 width,
146 0.01,
147 )
148 };
149 let nx_of = |i: usize| x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.5);
151 let mut order: Vec<usize> = (0..data.nrows()).collect();
152 order.sort_by(|&a, &b| nx_of(a).total_cmp(&nx_of(b)));
153 let mut prev_close: Option<f64> = None;
154 for i in order {
155 let (Some(o), Some(h), Some(l), Some(c)) = (
156 o_col[i].as_f64(),
157 h_col[i].as_f64(),
158 l_col[i].as_f64(),
159 c_col[i].as_f64(),
160 ) else {
161 continue;
162 };
163 let p = Period {
164 nx: nx_of(i),
165 open: my(o),
166 high: my(h),
167 low: my(l),
168 close: my(c),
169 up: c >= o,
170 up_from_prev: c >= prev_close.unwrap_or(o),
171 };
172 prev_close = Some(c);
173 let x = super::tip_value(&x_col[i]);
174 let f = |v: &Value| super::tip_value(v);
175 let tip = if data.has_column("open") {
176 format!(
177 "{x} — O {} H {} L {} C {}",
178 f(&o_col[i]),
179 f(&h_col[i]),
180 f(&l_col[i]),
181 f(&c_col[i])
182 )
183 } else {
184 format!(
185 "{x} — H {} L {} C {}",
186 f(&h_col[i]),
187 f(&l_col[i]),
188 f(&c_col[i])
189 )
190 };
191 let series =
192 super::series_key(data, i).or_else(|| Some(if p.up { "up" } else { "down" }.into()));
193 super::set_mark(
194 backend,
195 Some(tip),
196 Some(x),
197 series,
198 super::raw_value(&c_col[i]),
199 );
200 super::set_mark_formatted(
201 backend,
202 scales,
203 Some(&x_col[i]),
204 &Aesthetic::Y,
205 Some(&c_col[i]),
206 );
207 draw(&p, half, backend)?;
208 }
209 super::clear_mark(backend);
210 Ok(())
211}
212
213impl Geom for GeomCandlestick {
214 fn draw(
215 &self,
216 data: &DataFrame,
217 coord: &dyn Coord,
218 scales: &ScaleSet,
219 _theme: &Theme,
220 backend: &mut dyn DrawBackend,
221 ) -> Result<(), RenderError> {
222 let area = backend.plot_area();
223 for_each_period(data, scales, self.width, backend, |p, half, b| {
224 let rising = match self.style {
225 CandleStyle::Filled => p.up,
226 CandleStyle::Hollow => p.up_from_prev,
227 };
228 let color = if rising { self.up } else { self.down };
229 let wick = [
230 coord.transform((p.nx, p.low), &area),
231 coord.transform((p.nx, p.high), &area),
232 ];
233 b.draw_line(
234 &wick,
235 &LineStyle {
236 color,
237 alpha: self.alpha,
238 width: self.line_width,
239 linetype: Linetype::Solid,
240 ..Default::default()
241 },
242 )?;
243 let (x0, y0) = coord.transform((p.nx - half, p.open.max(p.close)), &area);
244 let (x1, y1) = coord.transform((p.nx + half, p.open.min(p.close)), &area);
245 let (top, bottom) = (y0.min(y1), y0.max(y1).max(y0.min(y1) + 1.0));
247 let hollow = self.style == CandleStyle::Hollow && p.up;
249 b.draw_rect(
250 (x0.min(x1), top),
251 (x0.max(x1), bottom),
252 &RectStyle {
253 fill: if hollow {
254 Some((255, 255, 255))
255 } else {
256 Some(color)
257 },
258 stroke: Some(color),
259 stroke_width: if hollow {
260 self.line_width
261 } else {
262 self.line_width * 0.5
263 },
264 alpha: self.alpha,
265 clip: true,
266 corner_radius: 0.0,
267 },
268 )
269 })
270 }
271
272 fn required_aes(&self) -> Vec<Aesthetic> {
273 ohlc_required()
274 }
275 fn default_stat(&self) -> Box<dyn Stat> {
276 Box::new(StatIdentity)
277 }
278 fn default_position(&self) -> Box<dyn Position> {
279 Box::new(PositionIdentity)
280 }
281 fn default_params(&self) -> GeomParams {
282 GeomParams::default()
283 }
284 fn name(&self) -> &str {
285 "candlestick"
286 }
287 fn setup_data(&self, data: &mut DataFrame, _warnings: &mut Vec<String>) {
288 ohlc_setup(data);
289 }
290}
291
292impl GeomOhlc {
293 pub fn hlc() -> Self {
295 GeomOhlc {
296 open_tick: false,
297 ..Default::default()
298 }
299 }
300}
301
302impl Geom for GeomOhlc {
303 fn draw(
304 &self,
305 data: &DataFrame,
306 coord: &dyn Coord,
307 scales: &ScaleSet,
308 _theme: &Theme,
309 backend: &mut dyn DrawBackend,
310 ) -> Result<(), RenderError> {
311 let area = backend.plot_area();
312 for_each_period(data, scales, self.width, backend, |p, half, b| {
313 let style = LineStyle {
314 color: if p.up { self.up } else { self.down },
315 alpha: self.alpha,
316 width: self.line_width,
317 linetype: Linetype::Solid,
318 ..Default::default()
319 };
320 let t = |x: f64, y: f64| coord.transform((x, y), &area);
321 b.draw_line(&[t(p.nx, p.low), t(p.nx, p.high)], &style)?;
322 if self.open_tick {
323 b.draw_line(&[t(p.nx - half, p.open), t(p.nx, p.open)], &style)?;
324 }
325 b.draw_line(&[t(p.nx, p.close), t(p.nx + half, p.close)], &style)
326 })
327 }
328
329 fn required_aes(&self) -> Vec<Aesthetic> {
330 let mut req = ohlc_required();
331 if !self.open_tick {
332 req.retain(|a| *a != Aesthetic::Open);
333 }
334 req
335 }
336 fn default_stat(&self) -> Box<dyn Stat> {
337 Box::new(StatIdentity)
338 }
339 fn default_position(&self) -> Box<dyn Position> {
340 Box::new(PositionIdentity)
341 }
342 fn default_params(&self) -> GeomParams {
343 GeomParams::default()
344 }
345 fn name(&self) -> &str {
346 if self.open_tick {
347 "ohlc"
348 } else {
349 "hlc"
350 }
351 }
352 fn setup_data(&self, data: &mut DataFrame, _warnings: &mut Vec<String>) {
353 ohlc_setup(data);
354 }
355}