Skip to main content

weirdnet_chart/
chart.rs

1//! The chart: panes, series, theme, viewport and live updates.
2
3use 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/// Identifies a series within its [`Chart`].
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct SeriesId(pub(crate) usize);
13
14/// Identifies a pane within its [`Chart`]. Pane 0 ([`Chart::MAIN`]) always exists.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
16pub struct PaneId(pub(crate) usize);
17
18/// How a series is drawn.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum Mark {
21    /// A polyline through points.
22    Line,
23    /// A polyline with the area under it filled.
24    Area,
25    /// A bar from zero per point.
26    Bars,
27    /// Candlesticks.
28    Candles,
29    /// OHLC bars (a high-low line with open and close ticks).
30    Ohlc,
31    /// Volume bars from another candle series, coloured by direction.
32    Volume,
33}
34
35impl Mark {
36    fn holds_points(self) -> bool {
37        matches!(self, Mark::Line | Mark::Area | Mark::Bars)
38    }
39}
40
41/// The vertical range of a pane.
42#[derive(Clone, Copy, Debug, PartialEq)]
43pub enum YRange {
44    /// Fit the visible data, with a little headroom.
45    Auto,
46    /// Fit the visible data and always include zero (bars and volume).
47    AutoFromZero,
48    /// A fixed `(min, max)`.
49    Fixed(f64, f64),
50}
51
52/// A horizontal band of the chart with its own y axis. All panes share the time axis.
53#[derive(Clone, Debug, PartialEq)]
54pub struct Pane {
55    /// Relative height compared with the other panes.
56    pub weight: f32,
57    /// The vertical range.
58    pub y_range: YRange,
59    /// An optional title drawn in the pane's top-left corner.
60    pub title: Option<String>,
61}
62
63impl Pane {
64    /// An auto-ranged pane with relative height `weight`.
65    pub fn new(weight: f32) -> Pane {
66        Pane { weight, y_range: YRange::Auto, title: None }
67    }
68}
69
70/// Per-series drawing options.
71#[derive(Clone, Copy, Debug, PartialEq)]
72pub struct SeriesStyle {
73    /// Line, area and bar colour. Candles, OHLC and volume use the theme's up and down colours.
74    pub color: Rgba,
75    /// Line width in backend units (pixels for GPUI).
76    pub width: f32,
77    /// Show the newest value as a tag on the y axis.
78    pub show_last_value: bool,
79}
80
81impl SeriesStyle {
82    /// A one-unit line in `color`, without a last-value tag.
83    pub fn new(color: Rgba) -> SeriesStyle {
84        SeriesStyle { color, width: 1.5, show_last_value: false }
85    }
86
87    /// The same style with a last-value tag.
88    pub fn with_last_value(mut self) -> SeriesStyle {
89        self.show_last_value = true;
90        self
91    }
92
93    /// The same style with a different line width.
94    pub fn with_width(mut self, width: f32) -> SeriesStyle {
95        self.width = width;
96        self
97    }
98}
99
100/// Colours for everything that isn't a series colour.
101#[derive(Clone, Copy, Debug, PartialEq)]
102pub struct Theme {
103    /// Filled behind the chart when not transparent.
104    pub background: Rgba,
105    /// Grid lines.
106    pub grid: Rgba,
107    /// Axis and pane border lines.
108    pub axis: Rgba,
109    /// Tick labels and titles.
110    pub text: Rgba,
111    /// Rising candles and volume.
112    pub up: Rgba,
113    /// Falling candles and volume.
114    pub down: Rgba,
115    /// Text on last-value tags.
116    pub tag_text: Rgba,
117}
118
119impl Theme {
120    /// Light text on a dark (transparent by default) background.
121    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    /// Dark text on a white background.
134    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/// Why a chart call failed.
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub enum ChartError {
156    /// No series with that id.
157    UnknownSeries(SeriesId),
158    /// No pane with that id.
159    UnknownPane(PaneId),
160    /// Points pushed to a candle series, or candles to a point series; or a volume series
161    /// pointed at something that isn't a candle series.
162    WrongKind(SeriesId),
163    /// The sample is older than the newest one in the series.
164    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/// A renderer-independent chart: panes stacked vertically over one time axis, each with
204/// its own series and y axis.
205///
206/// Push data as it arrives; [`layout`](Chart::layout) turns the visible part into a
207/// [`Scene`](crate::Scene) that a backend draws. Every change bumps
208/// [`revision`](Chart::revision).
209#[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    /// The main pane, created with the chart.
228    pub const MAIN: PaneId = PaneId(0);
229
230    /// A chart with one auto-ranged pane, the dark theme, UTC labels and 100 000-sample series.
231    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    /// Bumped on every change, including viewport and style changes.
248    pub fn revision(&self) -> u64 {
249        self.revision
250    }
251
252    /// The theme.
253    pub fn theme(&self) -> &Theme {
254        &self.theme
255    }
256
257    /// Changes the theme.
258    pub fn set_theme(&mut self, theme: Theme) {
259        self.theme = theme;
260        self.touch();
261    }
262
263    /// The time zone used for time labels.
264    pub fn time_zone(&self) -> TimeZone {
265        self.tz
266    }
267
268    /// Changes the time zone used for time labels.
269    pub fn set_time_zone(&mut self, tz: TimeZone) {
270        self.tz = tz;
271        self.touch();
272    }
273
274    /// The capacity given to series added from now on.
275    pub fn set_default_capacity(&mut self, capacity: usize) {
276        self.capacity = capacity.max(1);
277    }
278
279    /// Adds a pane below the existing ones, with relative height `weight` (the main pane has 3).
280    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    /// A pane's settings.
287    pub fn pane(&self, id: PaneId) -> Option<&Pane> {
288        self.panes.get(id.0)
289    }
290
291    /// Edits a pane's settings.
292    pub fn pane_mut(&mut self, id: PaneId) -> Option<&mut Pane> {
293        self.touch();
294        self.panes.get_mut(id.0)
295    }
296
297    /// The number of panes.
298    pub fn pane_count(&self) -> usize {
299        self.panes.len()
300    }
301
302    /// Adds a series. Volume series take their data from `candles` via
303    /// [`add_volume`](Self::add_volume) instead.
304    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    /// Adds a line series in `color` to `pane`.
323    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    /// Adds a candlestick series to `pane`, with a last-value tag.
328    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    /// Adds volume bars for the candle series `candles` to `pane` (usually a pane of its own
333    /// with [`YRange::AutoFromZero`]). The volume shares the candles' data.
334    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    /// Every series id, in the order they were added.
349    pub fn series_ids(&self) -> impl Iterator<Item = SeriesId> + use<> {
350        (0..self.entries.len()).map(SeriesId)
351    }
352
353    /// The number of series.
354    pub fn series_count(&self) -> usize {
355        self.entries.len()
356    }
357
358    /// A series' name.
359    pub fn name(&self, id: SeriesId) -> Option<&str> {
360        self.entries.get(id.0).map(|e| e.name.as_str())
361    }
362
363    /// How a series is drawn.
364    pub fn mark(&self, id: SeriesId) -> Option<Mark> {
365        self.entries.get(id.0).map(|e| e.mark)
366    }
367
368    /// A series' style.
369    pub fn style(&self, id: SeriesId) -> Option<&SeriesStyle> {
370        self.entries.get(id.0).map(|e| &e.style)
371    }
372
373    /// Changes a series' style.
374    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    /// Changes the mark of a series between kinds that hold the same data
382    /// (line, area and bars; or candles and OHLC).
383    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    /// Shows or hides a series.
399    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    /// A point series' data.
407    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    /// A candle series' data (also for a volume series, which shares it).
415    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    /// Edits a point series directly (bulk loads, capacity changes).
438    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    /// Edits a candle series directly.
444    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    /// Appends a point (or replaces the newest one with the same time).
459    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    /// Appends a candle (or replaces the newest one with the same time).
466    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    /// Folds a trade into a candle series with `interval_ms` bars.
473    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    /// Replaces a point series' contents (history loads); sorts by time.
480    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    /// Replaces a candle series' contents (history loads); sorts by time.
487    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    /// The newest sample time across all series.
494    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    /// The oldest sample time across all series.
506    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    /// The viewport.
518    pub fn viewport(&self) -> &Viewport {
519        &self.viewport
520    }
521
522    /// Edits the viewport directly.
523    pub fn viewport_mut(&mut self) -> &mut Viewport {
524        self.touch();
525        &mut self.viewport
526    }
527
528    /// Shows the last `span` milliseconds of data and follows new data.
529    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    /// Shows all data.
538    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    /// Pans for a drag of `dx` pixels across a plot `width` pixels wide (dragging right shows
557    /// earlier data). Panning back to the newest data resumes following.
558    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    /// Zooms by `factor` (below 1 zooms in) around pixel `x` of a plot `width` pixels wide.
565    /// While following, the newest data stays at the right edge.
566    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}