1use std::fmt;
4
5use crate::color::Rgba;
6use crate::series::{Candle, Change, OutOfOrder, Point, Series, fold_extent};
7use crate::time::{TimeZone, Timestamp};
8use crate::viewport::Viewport;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct SeriesId(pub(crate) usize);
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
16pub struct PaneId(pub(crate) usize);
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum Mark {
21 Line,
23 Area,
25 Bars,
27 Candles,
29 Ohlc,
31 Volume,
33}
34
35impl Mark {
36 fn holds_points(self) -> bool {
37 matches!(self, Mark::Line | Mark::Area | Mark::Bars)
38 }
39}
40
41#[derive(Clone, Copy, Debug, PartialEq)]
43pub enum YRange {
44 Auto,
46 AutoFromZero,
48 Fixed(f64, f64),
50}
51
52#[derive(Clone, Debug, PartialEq)]
54pub struct Pane {
55 pub weight: f32,
57 pub y_range: YRange,
59 pub title: Option<String>,
61}
62
63impl Pane {
64 pub fn new(weight: f32) -> Pane {
66 Pane { weight, y_range: YRange::Auto, title: None }
67 }
68}
69
70#[derive(Clone, Copy, Debug, PartialEq)]
72pub struct SeriesStyle {
73 pub color: Rgba,
75 pub width: f32,
77 pub show_last_value: bool,
79}
80
81impl SeriesStyle {
82 pub fn new(color: Rgba) -> SeriesStyle {
84 SeriesStyle { color, width: 1.5, show_last_value: false }
85 }
86
87 pub fn with_last_value(mut self) -> SeriesStyle {
89 self.show_last_value = true;
90 self
91 }
92
93 pub fn with_width(mut self, width: f32) -> SeriesStyle {
95 self.width = width;
96 self
97 }
98}
99
100#[derive(Clone, Copy, Debug, PartialEq)]
102pub struct Theme {
103 pub background: Rgba,
105 pub grid: Rgba,
107 pub axis: Rgba,
109 pub text: Rgba,
111 pub up: Rgba,
113 pub down: Rgba,
115 pub tag_text: Rgba,
117}
118
119impl Theme {
120 pub const fn dark() -> Theme {
122 Theme {
123 background: Rgba::TRANSPARENT,
124 grid: Rgba::hex(0x2a2e39),
125 axis: Rgba::hex(0x50535e),
126 text: Rgba::hex(0xb2b5be),
127 up: Rgba::hex(0x26a69a),
128 down: Rgba::hex(0xef5350),
129 tag_text: Rgba::hex(0x101114),
130 }
131 }
132
133 pub const fn light() -> Theme {
135 Theme {
136 background: Rgba::hex(0xffffff),
137 grid: Rgba::hex(0xe6e8ee),
138 axis: Rgba::hex(0xb4b8c2),
139 text: Rgba::hex(0x3b3f4a),
140 up: Rgba::hex(0x089981),
141 down: Rgba::hex(0xf23645),
142 tag_text: Rgba::hex(0xffffff),
143 }
144 }
145}
146
147impl Default for Theme {
148 fn default() -> Self {
149 Theme::dark()
150 }
151}
152
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub enum ChartError {
156 UnknownSeries(SeriesId),
158 UnknownPane(PaneId),
160 WrongKind(SeriesId),
163 OutOfOrder(OutOfOrder),
165}
166
167impl fmt::Display for ChartError {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 match self {
170 ChartError::UnknownSeries(id) => write!(f, "unknown series {}", id.0),
171 ChartError::UnknownPane(id) => write!(f, "unknown pane {}", id.0),
172 ChartError::WrongKind(id) => write!(f, "series {} holds a different kind of data", id.0),
173 ChartError::OutOfOrder(e) => e.fmt(f),
174 }
175 }
176}
177
178impl std::error::Error for ChartError {}
179
180impl From<OutOfOrder> for ChartError {
181 fn from(e: OutOfOrder) -> Self {
182 ChartError::OutOfOrder(e)
183 }
184}
185
186#[derive(Clone, Debug)]
187pub(crate) enum Data {
188 Points(Series<Point>),
189 Candles(Series<Candle>),
190 VolumeOf(SeriesId),
191}
192
193#[derive(Clone, Debug)]
194pub(crate) struct Entry {
195 pub(crate) name: String,
196 pub(crate) pane: PaneId,
197 pub(crate) mark: Mark,
198 pub(crate) style: SeriesStyle,
199 pub(crate) data: Data,
200 pub(crate) visible: bool,
201}
202
203#[derive(Clone, Debug)]
210pub struct Chart {
211 pub(crate) panes: Vec<Pane>,
212 pub(crate) entries: Vec<Entry>,
213 pub(crate) viewport: Viewport,
214 pub(crate) theme: Theme,
215 pub(crate) tz: TimeZone,
216 capacity: usize,
217 revision: u64,
218}
219
220impl Default for Chart {
221 fn default() -> Self {
222 Chart::new()
223 }
224}
225
226impl Chart {
227 pub const MAIN: PaneId = PaneId(0);
229
230 pub fn new() -> Chart {
232 Chart {
233 panes: vec![Pane::new(3.0)],
234 entries: Vec::new(),
235 viewport: Viewport::default(),
236 theme: Theme::default(),
237 tz: TimeZone::Utc,
238 capacity: 100_000,
239 revision: 0,
240 }
241 }
242
243 fn touch(&mut self) {
244 self.revision += 1;
245 }
246
247 pub fn revision(&self) -> u64 {
249 self.revision
250 }
251
252 pub fn theme(&self) -> &Theme {
254 &self.theme
255 }
256
257 pub fn set_theme(&mut self, theme: Theme) {
259 self.theme = theme;
260 self.touch();
261 }
262
263 pub fn time_zone(&self) -> TimeZone {
265 self.tz
266 }
267
268 pub fn set_time_zone(&mut self, tz: TimeZone) {
270 self.tz = tz;
271 self.touch();
272 }
273
274 pub fn set_default_capacity(&mut self, capacity: usize) {
276 self.capacity = capacity.max(1);
277 }
278
279 pub fn add_pane(&mut self, pane: Pane) -> PaneId {
281 self.panes.push(pane);
282 self.touch();
283 PaneId(self.panes.len() - 1)
284 }
285
286 pub fn pane(&self, id: PaneId) -> Option<&Pane> {
288 self.panes.get(id.0)
289 }
290
291 pub fn pane_mut(&mut self, id: PaneId) -> Option<&mut Pane> {
293 self.touch();
294 self.panes.get_mut(id.0)
295 }
296
297 pub fn pane_count(&self) -> usize {
299 self.panes.len()
300 }
301
302 pub fn add_series(&mut self, pane: PaneId, name: impl Into<String>, mark: Mark, style: SeriesStyle) -> Result<SeriesId, ChartError> {
305 if pane.0 >= self.panes.len() {
306 return Err(ChartError::UnknownPane(pane));
307 }
308 let data = match mark {
309 Mark::Line | Mark::Area | Mark::Bars => Data::Points(Series::with_capacity(self.capacity)),
310 Mark::Candles | Mark::Ohlc => Data::Candles(Series::with_capacity(self.capacity)),
311 Mark::Volume => return Err(ChartError::WrongKind(SeriesId(self.entries.len()))),
312 };
313 Ok(self.push_entry(Entry { name: name.into(), pane, mark, style, data, visible: true }))
314 }
315
316 fn push_entry(&mut self, entry: Entry) -> SeriesId {
317 self.entries.push(entry);
318 self.touch();
319 SeriesId(self.entries.len() - 1)
320 }
321
322 pub fn add_line(&mut self, pane: PaneId, name: impl Into<String>, color: Rgba) -> Result<SeriesId, ChartError> {
324 self.add_series(pane, name, Mark::Line, SeriesStyle::new(color))
325 }
326
327 pub fn add_candles(&mut self, pane: PaneId, name: impl Into<String>) -> Result<SeriesId, ChartError> {
329 self.add_series(pane, name, Mark::Candles, SeriesStyle::new(self.theme.text).with_last_value())
330 }
331
332 pub fn add_volume(&mut self, pane: PaneId, candles: SeriesId) -> Result<SeriesId, ChartError> {
335 if pane.0 >= self.panes.len() {
336 return Err(ChartError::UnknownPane(pane));
337 }
338 match self.entries.get(candles.0).map(|e| &e.data) {
339 Some(Data::Candles(_)) => {}
340 Some(_) => return Err(ChartError::WrongKind(candles)),
341 None => return Err(ChartError::UnknownSeries(candles)),
342 }
343 let name = format!("{} volume", self.entries[candles.0].name);
344 let style = SeriesStyle::new(self.theme.text);
345 Ok(self.push_entry(Entry { name, pane, mark: Mark::Volume, style, data: Data::VolumeOf(candles), visible: true }))
346 }
347
348 pub fn series_ids(&self) -> impl Iterator<Item = SeriesId> + use<> {
350 (0..self.entries.len()).map(SeriesId)
351 }
352
353 pub fn series_count(&self) -> usize {
355 self.entries.len()
356 }
357
358 pub fn name(&self, id: SeriesId) -> Option<&str> {
360 self.entries.get(id.0).map(|e| e.name.as_str())
361 }
362
363 pub fn mark(&self, id: SeriesId) -> Option<Mark> {
365 self.entries.get(id.0).map(|e| e.mark)
366 }
367
368 pub fn style(&self, id: SeriesId) -> Option<&SeriesStyle> {
370 self.entries.get(id.0).map(|e| &e.style)
371 }
372
373 pub fn set_style(&mut self, id: SeriesId, style: SeriesStyle) -> Result<(), ChartError> {
375 let e = self.entries.get_mut(id.0).ok_or(ChartError::UnknownSeries(id))?;
376 e.style = style;
377 self.touch();
378 Ok(())
379 }
380
381 pub fn set_mark(&mut self, id: SeriesId, mark: Mark) -> Result<(), ChartError> {
384 let e = self.entries.get_mut(id.0).ok_or(ChartError::UnknownSeries(id))?;
385 let ok = match e.data {
386 Data::Points(_) => mark.holds_points(),
387 Data::Candles(_) => matches!(mark, Mark::Candles | Mark::Ohlc),
388 Data::VolumeOf(_) => mark == Mark::Volume,
389 };
390 if !ok {
391 return Err(ChartError::WrongKind(id));
392 }
393 e.mark = mark;
394 self.touch();
395 Ok(())
396 }
397
398 pub fn set_visible(&mut self, id: SeriesId, visible: bool) -> Result<(), ChartError> {
400 let e = self.entries.get_mut(id.0).ok_or(ChartError::UnknownSeries(id))?;
401 e.visible = visible;
402 self.touch();
403 Ok(())
404 }
405
406 pub fn points(&self, id: SeriesId) -> Option<&Series<Point>> {
408 match &self.entries.get(id.0)?.data {
409 Data::Points(s) => Some(s),
410 _ => None,
411 }
412 }
413
414 pub fn candles(&self, id: SeriesId) -> Option<&Series<Candle>> {
416 match &self.entries.get(id.0)?.data {
417 Data::Candles(s) => Some(s),
418 Data::VolumeOf(src) => self.candles(*src),
419 _ => None,
420 }
421 }
422
423 fn points_series_mut(&mut self, id: SeriesId) -> Result<&mut Series<Point>, ChartError> {
424 match &mut self.entries.get_mut(id.0).ok_or(ChartError::UnknownSeries(id))?.data {
425 Data::Points(s) => Ok(s),
426 _ => Err(ChartError::WrongKind(id)),
427 }
428 }
429
430 fn candle_series_mut(&mut self, id: SeriesId) -> Result<&mut Series<Candle>, ChartError> {
431 match &mut self.entries.get_mut(id.0).ok_or(ChartError::UnknownSeries(id))?.data {
432 Data::Candles(s) => Ok(s),
433 _ => Err(ChartError::WrongKind(id)),
434 }
435 }
436
437 pub fn points_mut(&mut self, id: SeriesId) -> Result<&mut Series<Point>, ChartError> {
439 self.touch();
440 self.points_series_mut(id)
441 }
442
443 pub fn candles_mut(&mut self, id: SeriesId) -> Result<&mut Series<Candle>, ChartError> {
445 self.touch();
446 self.candle_series_mut(id)
447 }
448
449 fn after_data_change(&mut self) {
450 self.touch();
451 if self.viewport.is_following()
452 && let Some(latest) = self.latest_time()
453 {
454 self.viewport.follow_to(latest);
455 }
456 }
457
458 pub fn push_point(&mut self, id: SeriesId, point: Point) -> Result<Change, ChartError> {
460 let change = self.points_series_mut(id)?.push(point)?;
461 self.after_data_change();
462 Ok(change)
463 }
464
465 pub fn push_candle(&mut self, id: SeriesId, candle: Candle) -> Result<Change, ChartError> {
467 let change = self.candle_series_mut(id)?.push(candle)?;
468 self.after_data_change();
469 Ok(change)
470 }
471
472 pub fn apply_trade(&mut self, id: SeriesId, time: Timestamp, price: f64, size: f64, interval_ms: i64) -> Result<Change, ChartError> {
474 let change = self.candle_series_mut(id)?.apply_trade(time, price, size, interval_ms)?;
475 self.after_data_change();
476 Ok(change)
477 }
478
479 pub fn set_points(&mut self, id: SeriesId, points: Vec<Point>) -> Result<(), ChartError> {
481 self.points_series_mut(id)?.replace_all(points);
482 self.after_data_change();
483 Ok(())
484 }
485
486 pub fn set_candles(&mut self, id: SeriesId, candles: Vec<Candle>) -> Result<(), ChartError> {
488 self.candle_series_mut(id)?.replace_all(candles);
489 self.after_data_change();
490 Ok(())
491 }
492
493 pub fn latest_time(&self) -> Option<Timestamp> {
495 self.entries
496 .iter()
497 .filter_map(|e| match &e.data {
498 Data::Points(s) => s.last().map(|p| p.time),
499 Data::Candles(s) => s.last().map(|c| c.time + s.interval().unwrap_or(0)),
500 Data::VolumeOf(_) => None,
501 })
502 .max()
503 }
504
505 pub fn earliest_time(&self) -> Option<Timestamp> {
507 self.entries
508 .iter()
509 .filter_map(|e| match &e.data {
510 Data::Points(s) => s.first().map(|p| p.time),
511 Data::Candles(s) => s.first().map(|c| c.time),
512 Data::VolumeOf(_) => None,
513 })
514 .min()
515 }
516
517 pub fn viewport(&self) -> &Viewport {
519 &self.viewport
520 }
521
522 pub fn viewport_mut(&mut self) -> &mut Viewport {
524 self.touch();
525 &mut self.viewport
526 }
527
528 pub fn show_latest(&mut self, span: i64) {
530 let end = self.latest_time().unwrap_or(0);
531 self.viewport.set_range(end - span, end);
532 self.viewport.set_following(true);
533 self.viewport.follow_to(end);
534 self.touch();
535 }
536
537 pub fn fit_all(&mut self) {
539 if let (Some(a), Some(b)) = (self.earliest_time(), self.latest_time()) {
540 self.viewport.set_range(a, b.max(a + 1));
541 self.viewport.set_following(true);
542 self.viewport.follow_to(b);
543 }
544 self.touch();
545 }
546
547 fn refollow_if_at_edge(&mut self) {
548 if let Some(latest) = self.latest_time()
549 && self.viewport.end() >= latest
550 {
551 self.viewport.set_following(true);
552 self.viewport.follow_to(latest);
553 }
554 }
555
556 pub fn pan_pixels(&mut self, dx: f64, width: f64) {
559 self.viewport.pan_pixels(dx, width);
560 self.refollow_if_at_edge();
561 self.touch();
562 }
563
564 pub fn zoom_at(&mut self, factor: f64, x: f64, width: f64) {
567 if self.viewport.is_following() {
568 self.viewport.zoom(factor, 1.0);
569 if let Some(latest) = self.latest_time() {
570 self.viewport.follow_to(latest);
571 }
572 } else {
573 self.viewport.zoom_at_pixel(factor, x, width);
574 self.refollow_if_at_edge();
575 }
576 self.touch();
577 }
578
579 pub(crate) fn entry_extent(&self, e: &Entry, start: Timestamp, end: Timestamp) -> Option<(f64, f64)> {
580 match &e.data {
581 Data::Points(s) => {
582 let ext = s.extent(start, end)?;
583 Some(if e.mark == Mark::Bars { (ext.0.min(0.0), ext.1.max(0.0)) } else { ext })
584 }
585 Data::Candles(s) => s.extent(start, end),
586 Data::VolumeOf(src) => {
587 let s = self.candles(*src)?;
588 fold_extent(s.range(start, end).map(|c| (0.0, c.volume)))
589 }
590 }
591 }
592}
593
594#[cfg(test)]
595mod tests {
596 use super::*;
597
598 #[test]
599 fn kinds_are_checked() {
600 let mut c = Chart::new();
601 let line = c.add_line(Chart::MAIN, "price", Rgba::hex(0xffffff)).unwrap();
602 let candles = c.add_candles(Chart::MAIN, "BTC").unwrap();
603 assert_eq!(c.push_candle(line, Candle::from_trade(0, 1.0, 1.0)), Err(ChartError::WrongKind(line)));
604 assert_eq!(c.push_point(candles, Point::new(0, 1.0)), Err(ChartError::WrongKind(candles)));
605 assert_eq!(c.add_volume(Chart::MAIN, line), Err(ChartError::WrongKind(line)));
606 assert_eq!(c.add_line(PaneId(9), "x", Rgba::hex(0)), Err(ChartError::UnknownPane(PaneId(9))));
607 let vol = c.add_volume(Chart::MAIN, candles).unwrap();
608 assert_eq!(c.name(vol), Some("BTC volume"));
609 assert_eq!(c.set_mark(line, Mark::Candles), Err(ChartError::WrongKind(line)));
610 c.set_mark(line, Mark::Area).unwrap();
611 c.push_candle(candles, Candle::new(60, 1.0, 2.0, 0.5, 1.5, 7.0)).unwrap();
612 assert_eq!(c.candles(vol).unwrap().len(), 1);
613 }
614
615 #[test]
616 fn live_data_scrolls_while_following() {
617 let mut c = Chart::new();
618 let line = c.add_line(Chart::MAIN, "p", Rgba::hex(0xffffff)).unwrap();
619 c.viewport_mut().set_right_margin(0.0);
620 c.show_latest(1000);
621 for t in 0..=5000 {
622 c.push_point(line, Point::new(t, t as f64)).unwrap();
623 }
624 assert_eq!((c.viewport().start(), c.viewport().end()), (4000, 5000));
625 c.pan_pixels(100.0, 1000.0);
626 assert!(!c.viewport().is_following());
627 c.push_point(line, Point::new(5001, 0.0)).unwrap();
628 assert_eq!(c.viewport().end(), 4900);
629 c.pan_pixels(-200.0, 1000.0);
630 assert!(c.viewport().is_following());
631 assert_eq!(c.viewport().end(), 5001);
632 }
633
634 #[test]
635 fn revision_bumps() {
636 let mut c = Chart::new();
637 let r0 = c.revision();
638 let id = c.add_line(Chart::MAIN, "p", Rgba::hex(0)).unwrap();
639 c.push_point(id, Point::new(1, 1.0)).unwrap();
640 assert!(c.revision() > r0);
641 }
642}