Skip to main content

Chart

Struct Chart 

Source
pub struct Chart { /* private fields */ }
Expand description

A financial chart.

§Examples

use ferrochart_core::{Chart, ChartOptions};
use ferrochart_core::chart::{SeriesData, SeriesOptions};
use ferrochart_core::frame::{Invalidation, SeriesKind};
use ferrochart_core::geom::SizeCss;
use ferrochart_core::testing::{random_walk, MonoMeasurer};

let mut chart = Chart::new(ChartOptions::default());
chart.resize(SizeCss { w: 800.0, h: 450.0 }, 1.0);
let pane = chart.main_pane();
let candles = chart.add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())?;
chart.add_series(pane, SeriesKind::Volume, SeriesOptions::volume_of(candles))?;
chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 500, 0, 60_000)?))?;

assert_ne!(chart.needs_redraw(), Invalidation::None);
chart.build_frame(0.0, &MonoMeasurer);
assert!(!chart.frame().layers[1].cmds.is_empty());
assert_eq!(chart.needs_redraw(), Invalidation::None);

Implementations§

Source§

impl Chart

Source

pub fn new(options: ChartOptions) -> Self

Creates an empty chart with one pane.

Source

pub fn resize(&mut self, size: SizeCss, dpr: f32)

Sets the size in CSS pixels and the device pixel ratio. All geometry is computed in physical pixels (size × dpr). Non-finite or non-positive values are ignored.

Source

pub fn main_pane(&self) -> PaneId

The top pane (the pane every chart starts with, unless it was removed).

Source

pub fn add_pane(&mut self, opts: PaneOptions) -> PaneId

Adds a pane below the existing ones.

§Examples
use ferrochart_core::{Chart, ChartOptions};
use ferrochart_core::chart::{SeriesData, SeriesOptions};
use ferrochart_core::frame::SeriesKind;
use ferrochart_core::geom::SizeCss;
use ferrochart_core::pane::PaneOptions;
use ferrochart_core::testing::{random_walk, MonoMeasurer};

let mut chart = Chart::new(ChartOptions::default());
chart.resize(SizeCss { w: 800.0, h: 600.0 }, 1.0);
let candles = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
// Volume in its own pane, a quarter of the height of the main pane.
let below = chart.add_pane(PaneOptions { stretch_factor: 0.25 });
chart.add_series(below, SeriesKind::Volume, SeriesOptions::volume_of(candles))?;
chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 500, 0, 60_000)?))?;
chart.build_frame(0.0, &MonoMeasurer);

let main = chart.pane_layout(chart.main_pane()).unwrap();
let vol = chart.pane_layout(below).unwrap();
assert!(vol.plot.y > main.plot.bottom());
assert!((main.plot.h / vol.plot.h - 4.0).abs() < 0.1);
Source

pub fn remove_pane(&mut self, id: PaneId) -> Result<()>

Removes a pane and the series in it (removing the candlestick series also removes its volume series, wherever it is).

§Errors

Error::UnknownId if the pane does not exist, Error::InvalidArgument for the last remaining pane.

Source

pub fn panes(&self) -> impl Iterator<Item = PaneId> + '_

The panes from top to bottom.

Source

pub fn pane_layout(&self, id: PaneId) -> Option<PaneLayout>

Rectangles of a pane in the last built layout; None for unknown ids.

Source

pub fn pane_stretch(&self, id: PaneId) -> Option<f32>

The stretch factor of a pane; None for unknown ids.

Source

pub fn set_pane_stretch(&mut self, id: PaneId, stretch: f32) -> Result<()>

Sets the stretch factor of a pane (dragging a separator changes the factors of the two panes next to it).

§Errors

Error::UnknownId if the pane does not exist, Error::InvalidArgument if stretch is not finite and positive.

Source

pub fn visible_price_range(&self, id: PaneId) -> Option<(f64, f64)>

Prices at the bottom and the top of pane id’s plot area in the last built layout (display values in the relative modes); None for an unknown pane or before the first frame. Hosts copy it to a ferrochart-plot side panel that shares the price axis.

use ferrochart_core::chart::{SeriesData, SeriesOptions};
use ferrochart_core::frame::SeriesKind;
use ferrochart_core::geom::SizeCss;
use ferrochart_core::testing::{random_walk, MonoMeasurer};
use ferrochart_core::{Chart, ChartOptions};

let mut chart = Chart::new(ChartOptions::default());
let pane = chart.main_pane();
assert_eq!(chart.visible_price_range(pane), None);
let id = chart.add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())?;
chart.set_data(id, SeriesData::Ohlc(random_walk(1, 100, 0, 60_000)?))?;
chart.resize(SizeCss { w: 400.0, h: 300.0 }, 1.0);
chart.build_frame(0.0, &MonoMeasurer);
let (lo, hi) = chart.visible_price_range(pane).unwrap();
assert!(lo < hi);
Source

pub fn add_candlestick(&mut self) -> Result<SeriesId>

Adds a candlestick series on the main pane with the default options: add_series(main_pane(), SeriesKind::Candlestick, SeriesOptions::default()).

§Errors

As Chart::add_series.

§Examples
use ferrochart_core::testing::random_walk;
use ferrochart_core::{Chart, ChartOptions};

let mut chart = Chart::new(ChartOptions::default());
let candles = chart.add_candlestick()?;
chart.add_volume(candles)?;
chart.set_data(candles, random_walk(1, 500, 0, 60_000)?)?;
Source

pub fn add_volume(&mut self, source: SeriesId) -> Result<SeriesId>

Adds a volume histogram of source’s volume column on the main pane: add_series(main_pane(), SeriesKind::Volume, SeriesOptions::volume_of(source)).

§Errors

As Chart::add_series (Error::UnknownId if source does not exist).

Source

pub fn add_series( &mut self, pane: PaneId, kind: SeriesKind, opts: SeriesOptions, ) -> Result<SeriesId>

Adds a series to a pane.

All series share one time axis, the union of their times. A series that skips bars of the axis is drawn across them (line-like series) or leaves gaps (histograms, OHLC series).

§Errors
  • Error::UnknownId if pane does not exist;
  • Error::InvalidArgument for a volume series whose opts.source is not an OHLC or transform series of this chart, for Custom, Kagi and PointFigure (added with their own methods), and for any series but volume when the chart has a transform series.
§Examples
use ferrochart_core::{Chart, ChartOptions};
use ferrochart_core::chart::SeriesOptions;
use ferrochart_core::data::ValueColumns;
use ferrochart_core::chart::SeriesData;
use ferrochart_core::frame::SeriesKind;

let mut chart = Chart::new(ChartOptions::default());
let line = chart.add_series(chart.main_pane(), SeriesKind::Line, SeriesOptions::default())?;
chart.set_data(line, SeriesData::Value(ValueColumns {
    time: vec![0, 60_000, 120_000],
    value: vec![1.0, f64::NAN, 3.0], // NaN: a gap
    color: None,
}))?;
Source

pub fn series_options(&self, id: SeriesId) -> Option<&SeriesOptions>

The options of a series; None for an unknown id.

Source

pub fn series_kind(&self, id: SeriesId) -> Option<SeriesKind>

The kind of a series; None for an unknown id.

Source

pub fn series_pane(&self, id: SeriesId) -> Option<PaneId>

The pane of a series; None for an unknown id.

Source

pub fn set_series_options( &mut self, id: SeriesId, opts: SeriesOptions, ) -> Result<()>

Changes the options of a series (colors, line style, labels, shift, …), e.g. for applyOptions of the lightweight-charts compatibility layer. The data is kept.

§Errors
§Examples
use ferrochart_core::chart::SeriesOptions;
use ferrochart_core::frame::SeriesKind;
use ferrochart_core::geom::Rgba;
use ferrochart_core::{Chart, ChartOptions};

let mut chart = Chart::new(ChartOptions::default());
let line = chart.add_series(chart.main_pane(), SeriesKind::Line, SeriesOptions::default())?;
let mut opts = *chart.series_options(line).unwrap();
opts.color = Some(Rgba::hex(0x00FF_6D00));
chart.set_series_options(line, opts)?;
assert_eq!(chart.series_options(line).unwrap().color, Some(Rgba::hex(0x00FF_6D00)));
Source

pub fn remove_series(&mut self, id: SeriesId) -> Result<()>

Removes a series and its data. Removing an OHLC series also removes the volume series that read it.

§Errors

Error::UnknownId if the series does not exist.

Source

pub fn set_data( &mut self, id: SeriesId, data: impl Into<SeriesData>, ) -> Result<()>

Replaces all data of a series.

The time axis becomes the union of the new times and the times of the other series: times the other series do not have are added (a time between existing bars rebuilds the axis and reports WarningKind::TimeAxisMerged), and bars only this series had are removed.

§Errors

Error::UnknownId, Error::InvalidArgument (wrong series or data kind), and the data validation errors (Error::LengthMismatch, Error::InvalidOhlc, Error::TimeNotIncreasing). The chart is unchanged on error.

Source

pub fn append( &mut self, id: SeriesId, data: impl Into<SeriesData>, ) -> Result<()>

Appends points after the last one. Times the axis does not have yet are added to it.

§Errors

As set_data; additionally the times must come after the last point, and volume must be present exactly when the series has it.

Source

pub fn prepend( &mut self, id: SeriesId, data: impl Into<SeriesData>, ) -> Result<()>

Inserts older points before the first one (history loading). Existing points keep their logical indices unless a time falls between existing bars of the axis.

§Errors

As append, with times before the first point.

Source

pub fn update_last( &mut self, id: SeriesId, bar: BarUpdate, ) -> Result<DataChange>

Real-time update. Replaces the last point if bar.time equals its time (no allocation), appends one if it is later. Returns the applied change. Value series (line, area, baseline, histogram) take bar.close as the value and ignore the other fields. For a transform series bar is an input and the result is the change of the output (Append { count: 0 } if the output did not change); replacing the last input does not allocate while the number of forming elements stays the same.

§Errors

Error::UnknownId, Error::InvalidArgument (a volume series), Error::TimeNotIncreasing (time before the last point), and the validation errors.

Source

pub fn add_transform_series( &mut self, pane: PaneId, t: Box<dyn SeriesTransform>, opts: SeriesOptions, ) -> Result<SeriesId>

Adds a transform series to a pane: the data given to it with set_data, append, prepend and update_last is its input, and its output elements, at synthetic times, are the time axis. See crate::transform for the built-in transforms.

§Errors
  • Error::UnknownId if pane does not exist;
  • Error::InvalidArgument if the chart already has a series other than volume (a chart has at most one transform series and no time-based series next to it), if the output kind is not Candlestick, OhlcBar, Kagi or PointFigure, or if a PointFigure transform has no positive box size.
§Examples
use ferrochart_core::chart::{SeriesData, SeriesOptions};
use ferrochart_core::data::BarUpdate;
use ferrochart_core::frame::SeriesKind;
use ferrochart_core::testing::{random_walk, MonoMeasurer};
use ferrochart_core::transform::{Kagi, Reversal};
use ferrochart_core::{Chart, ChartOptions};

let mut chart = Chart::new(ChartOptions::default());
let pane = chart.main_pane();
let kagi = chart.add_transform_series(
    pane,
    Box::new(Kagi::new(Reversal::Percent(2.0))?),
    SeriesOptions::default(),
)?;
let bars = random_walk(1, 5_000, 0, 60_000)?;
let last = *bars.time.last().unwrap();
chart.set_data(kagi, SeriesData::Ohlc(bars))?;
// Far fewer lines than input bars.
assert!(chart.data_view().time_index().len() < 1_000);
// Real-time input.
let tick = BarUpdate { time: last + 60_000, open: 100.0, high: 100.0, low: 100.0, close: 100.0, volume: Some(1.0) };
chart.update_last(kagi, tick)?;
// No time-based series next to it.
assert!(chart.add_series(pane, SeriesKind::Line, SeriesOptions::default()).is_err());
chart.build_frame(0.0, &MonoMeasurer);
Source

pub fn add_custom_series( &mut self, pane: PaneId, series: Box<dyn CustomSeries>, opts: SeriesOptions, ) -> Result<SeriesId>

Adds a custom series to a pane. Its current data is taken as a Replace; later changes go through update_custom. See CustomSeries for an example.

§Errors

Error::UnknownId if pane does not exist; Error::InvalidArgument if the chart has a transform series; Error::TimeNotIncreasing if the plugin’s times are not strictly increasing (the series is not added); Error::OutOfMemory.

Source

pub fn custom_series<T: CustomSeries>(&self, id: SeriesId) -> Option<&T>

The plugin of custom series id as T; None for an unknown id, another kind of series or another type.

Source

pub fn update_custom<T: CustomSeries>( &mut self, id: SeriesId, f: impl FnOnce(&mut T) -> DataChange, ) -> Result<()>

Changes the data of custom series id: f modifies the plugin and returns what changed, and core updates the time axis, generation and change log. DataChange::UpdateLast keeping the last time does not allocate. A change that does not match the data (wrong count, the last time moved) is applied as a Replace.

§Errors
Source

pub fn create_price_line( &mut self, series: SeriesId, opts: PriceLineOptions, ) -> Result<PriceLineId>

Adds a price line to a series. Its price is in the series’ units, so on a relative scale it moves with the series.

§Errors

Error::UnknownId if the series does not exist; Error::InvalidArgument for a volume series or a price that is not finite.

§Examples

See PriceLineOptions.

Source

pub fn update_price_line( &mut self, id: PriceLineId, opts: PriceLineOptions, ) -> Result<()>

Replaces the options of a price line.

§Errors

Error::UnknownId if the price line does not exist; Error::InvalidArgument for a price that is not finite.

§Examples
use ferrochart_core::chart::{PriceLineOptions, SeriesOptions};
use ferrochart_core::frame::SeriesKind;
use ferrochart_core::{Chart, ChartOptions};

let mut chart = Chart::new(ChartOptions::default());
let id = chart.add_series(chart.main_pane(), SeriesKind::Line, SeriesOptions::default())?;
let line = chart.create_price_line(id, PriceLineOptions { price: 1.0, ..Default::default() })?;
chart.update_price_line(line, PriceLineOptions { price: 2.0, ..Default::default() })?;
assert_eq!(chart.price_line(line).map(|o| o.price), Some(2.0));
Source

pub fn price_line(&self, id: PriceLineId) -> Option<&PriceLineOptions>

Options of a price line; None if it does not exist.

Source

pub fn remove_price_line(&mut self, id: PriceLineId) -> Result<()>

Removes a price line.

§Errors

Error::UnknownId if it does not exist.

Source

pub fn add_indicator( &mut self, source: SeriesId, ind: Box<dyn Indicator>, placement: Placement, ) -> Result<IndicatorId>

Attaches an indicator to source. Each output becomes a value series (indicator_series) on the pane placement names; the chart keeps them up to date as the source changes, incrementally for append and update_last.

§Errors

Error::UnknownId for an unknown source or pane; Error::InvalidArgument for a volume source, an indicator without outputs, or one that needs volume on a source without it.

§Examples

A minimal indicator: the close, doubled.

use ferrochart_core::chart::SeriesOptions;
use ferrochart_core::data::DataChange;
use ferrochart_core::frame::SeriesKind;
use ferrochart_core::plugin::{
    Indicator, IndicatorInput, IndicatorOutputs, OutputSpec, Placement,
};
use ferrochart_core::testing::random_walk;
use ferrochart_core::chart::SeriesData;
use ferrochart_core::{Chart, ChartOptions};

struct Double;
impl Indicator for Double {
    fn name(&self) -> &str { "double" }
    fn outputs(&self) -> &[OutputSpec] {
        const OUT: [OutputSpec; 1] = [OutputSpec::line("double")];
        &OUT
    }
    fn default_placement(&self) -> Placement { Placement::NewPane }
    fn warmup(&self) -> usize { 0 }
    fn update(&mut self, input: &IndicatorInput<'_>, _: DataChange, out: &mut IndicatorOutputs) {
        let start = out.start();
        for (i, v) in out.column(0).iter_mut().enumerate() {
            if let Some(b) = input.bar(start + i) {
                *v = 2.0 * b.close;
            }
        }
    }
}

let mut chart = Chart::new(ChartOptions::default());
let candles = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 50, 0, 60_000)?))?;
let id = chart.add_indicator(candles, Box::new(Double), Placement::NewPane)?;
assert_eq!(chart.indicator_series(id).map(<[_]>::len), Some(1));
assert_eq!(chart.panes().count(), 2);
Source

pub fn remove_indicator(&mut self, id: IndicatorId) -> Result<()>

Removes an indicator, its output series, the indicators attached to them, and the pane add_indicator created for it if it is now empty.

§Errors

Error::UnknownId if it does not exist.

Source

pub fn indicator_series(&self, id: IndicatorId) -> Option<&[SeriesId]>

The output series of an indicator, in the order of its outputs; None if it does not exist.

Source

pub fn indicator_bands(&self, id: IndicatorId) -> Option<&[BandId]>

The bands an indicator’s OutputSpec::fill_to created, e.g. to change their colors with set_band_options; None if it does not exist. They are removed with the indicator.

§Examples
use ferrochart_core::chart::{BandOptions, SeriesData, SeriesOptions};
use ferrochart_core::frame::SeriesKind;
use ferrochart_core::geom::Rgba;
use ferrochart_core::plugin::{Indicator, IndicatorInput, IndicatorOutputs, OutputSpec, Placement};
use ferrochart_core::data::DataChange;
use ferrochart_core::testing::random_walk;
use ferrochart_core::{Chart, ChartOptions};

/// The high and the low, filled between.
struct Range([OutputSpec; 2]);
impl Indicator for Range {
    fn name(&self) -> &str { "range" }
    fn outputs(&self) -> &[OutputSpec] { &self.0 }
    fn default_placement(&self) -> Placement { Placement::Overlay }
    fn warmup(&self) -> usize { 0 }
    fn update(&mut self, input: &IndicatorInput<'_>, _: DataChange, out: &mut IndicatorOutputs) {
        let start = out.start();
        for k in 0..2 {
            for (i, v) in out.column(k).iter_mut().enumerate() {
                if let Some(b) = input.bar(start + i) {
                    *v = if k == 0 { b.high } else { b.low };
                }
            }
        }
    }
}

let mut chart = Chart::new(ChartOptions::default());
let candles = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 50, 0, 60_000)?))?;
let high = OutputSpec { fill_to: Some((1, BandOptions::default())), ..OutputSpec::line("high") };
let id = chart.add_indicator(candles, Box::new(Range([high, OutputSpec::line("low")])), Placement::Overlay)?;
let band = chart.indicator_bands(id).unwrap()[0];
chart.set_band_options(band, BandOptions { fill: Some(Rgba::hex(0x0026_A69A).with_alpha(0x30)), fill_crossed: None })?;
Source

pub fn set_markers( &mut self, series: SeriesId, markers: Vec<Marker>, ) -> Result<()>

Replaces the markers of a series. They are kept sorted by time (stable, so markers on the same bar stack in the given order).

§Errors

Error::UnknownId if the series does not exist; Error::InvalidArgument for a volume series.

§Examples

See Marker.

Source

pub fn markers(&self, series: SeriesId) -> Option<&[Marker]>

Markers of a series, sorted by time; None if it does not exist.

Source

pub fn time_scale(&mut self) -> &mut TimeScale

The (global) time scale.

Source

pub fn price_scale( &mut self, pane: PaneId, side: ScaleSide, ) -> Option<&mut PriceScale>

A price scale of a pane; None if it does not exist (for now every pane has only its right scale).

Source

pub fn fit_content(&mut self)

Shows all bars.

Source

pub fn scroll_to_realtime(&mut self)

Scrolls so that the last bar is visible with the configured ChartOptions::right_offset.

Source

pub fn needs_redraw(&self) -> Invalidation

What needs to be redrawn. The host only builds a frame when this is not None; without interaction or new data, nothing is redrawn.

Source

pub fn frame(&self) -> &Frame

The last built frame.

Source

pub fn data_view(&self) -> ChartDataView<'_>

Read-only view of the chart data for renderers.

Source

pub fn layout(&self) -> Layout

The last built layout.

Source

pub fn set_reveal(&mut self, reveal: Option<Reveal>)

Shows the data gradually: with Some, series, indicators, bands, markers, drawings and pane plugin layers are clipped to the left progress of each pane, while grid and axes are drawn whole and the price scale still fits all visible data; price lines, value labels and the crosshair wait for progress 1. None (the default) shows everything. The host moves the progress over time.

use ferrochart_core::chart::{Chart, ChartOptions};
use ferrochart_core::frame::Reveal;

let mut chart = Chart::new(ChartOptions::default());
chart.set_reveal(Some(Reveal { progress: 0.5, pen: None }));
assert_eq!(chart.reveal().map(|r| r.progress), Some(0.5));
chart.set_reveal(None);
assert!(chart.reveal().is_none());
Source

pub fn reveal(&self) -> Option<Reveal>

The gradual display set by set_reveal.

Source

pub fn heap_bytes(&self) -> usize

Heap bytes held by the chart’s series data: columns, LOD pyramid and time index. Used by the memory benchmark (P2).

Source

pub fn drain_events(&mut self) -> impl Iterator<Item = ChartEvent> + '_

Takes all pending events.

Source

pub fn build_frame(&mut self, now_ms: f64, text: &dyn TextMeasurer)

Builds the frame for the current state. Call when needs_redraw is not None, then read it with frame and data_view.

now_ms drives kinetic scrolling; it must use the same clock as the time_ms of input events (see interaction).

Every layer is always rebuilt, so the frame is complete for any renderer; only the revisions of layers whose content changed are bumped: Cursor bumps only the overlay.

Source

pub fn drawings(&mut self) -> &mut DrawingManager

The drawings.

Source

pub fn add_band( &mut self, upper: SeriesId, lower: SeriesId, opts: BandOptions, ) -> Result<BandId>

Adds a band: the area between two single-value series of the same pane, filled with opts.fill where upper is at or above lower and opts.fill_crossed where it is below. Bands are drawn after the volume and before the other series of the pane, and are removed with either series. See BandOptions for an example.

§Errors

Error::UnknownId if a series does not exist; Error::InvalidArgument unless both are single-value series (line, area, baseline, histogram, points) on the same pane and different.

Source

pub fn set_band_options(&mut self, id: BandId, opts: BandOptions) -> Result<()>

Changes the colors of a band.

§Errors

Error::UnknownId if it does not exist.

Source

pub fn band_options(&self, id: BandId) -> Option<&BandOptions>

The colors of a band; None if it does not exist.

Source

pub fn remove_band(&mut self, id: BandId) -> Result<()>

Removes a band.

§Errors

Error::UnknownId if it does not exist.

Source

pub fn add_layer( &mut self, pane: Option<PaneId>, plugin: Box<dyn LayerPlugin>, ) -> Result<LayerPluginId>

Adds a layer plugin to a pane, or to the whole chart (pane: None), drawn after the plugins added before it. See LayerPlugin for an example.

§Errors

Error::UnknownId if the pane does not exist; Error::OutOfMemory.

Source

pub fn remove_layer(&mut self, id: LayerPluginId) -> Result<()>

Removes a layer plugin. Plugins of a pane are also removed with the pane.

§Errors

Error::UnknownId if it does not exist.

Source

pub fn invalidate_layer(&mut self, id: LayerPluginId) -> Result<()>

Requests a redraw after a layer plugin’s own content changed.

§Errors

Error::UnknownId if it does not exist.

Source

pub fn set_native_kinds(&mut self, kinds: &[&'static str])

Declares the custom series kinds the renderer draws natively (Renderer::native_kinds); for them the frame holds a DrawCmd::Custom instead of the plugin’s primitives. Host helpers call it before every frame; it does nothing (and does not allocate) when the kinds are unchanged.

Source§

impl Chart

Source

pub fn crosshair_mode(&self) -> CrosshairMode

The current crosshair mode.

Source

pub fn set_crosshair_mode(&mut self, mode: CrosshairMode)

Sets the crosshair mode.

Source

pub fn is_animating(&self) -> bool

Whether kinetic scrolling is running (the host keeps requesting frames).

Source

pub fn handle_input(&mut self, event: InputEvent) -> InputResult

Handles an input event. Coordinates are CSS pixels; regions refer to the layout of the last built frame.

§Examples
use ferrochart_core::chart::{SeriesData, SeriesOptions};
use ferrochart_core::frame::SeriesKind;
use ferrochart_core::geom::{PointCss, SizeCss};
use ferrochart_core::interaction::{Button, InputEvent, Modifiers};
use ferrochart_core::testing::{random_walk, MonoMeasurer};
use ferrochart_core::{Chart, ChartOptions};

let mut chart = Chart::new(ChartOptions::default());
chart.resize(SizeCss { w: 800.0, h: 400.0 }, 1.0);
let id = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
chart.set_data(id, SeriesData::Ohlc(random_walk(1, 1000, 0, 60_000)?))?;
chart.build_frame(0.0, &MonoMeasurer);

let before = chart.time_scale().visible_range();
let mods = Modifiers::default();
let at = |x| PointCss { x, y: 200.0 };
chart.handle_input(InputEvent::PointerDown { id: 0, pos: at(400.0), button: Button::Left, mods, time_ms: 0.0 });
chart.handle_input(InputEvent::PointerMove { id: 0, pos: at(460.0), mods, time_ms: 16.0 });
chart.handle_input(InputEvent::PointerUp { id: 0, pos: at(460.0), button: Button::Left, mods, time_ms: 500.0 });
// Dragging right by 60 px shows bars 10 bars earlier (6 px spacing).
let after = chart.time_scale().visible_range();
assert!((before.0 - after.0 - 10.0).abs() < 1e-9);
Source§

impl Chart

Source

pub fn save_state(&self) -> ChartState

Saves the view, layout and drawings.

Source

pub fn load_state(&mut self, s: ChartState) -> Result<()>

Loads a state saved by save_state into a chart with the same number of panes. The drawings replace the current ones (with DrawingRemoved/DrawingCreated events and new ids); the undo history is cleared.

§Errors

Error::InvalidArgument, with the chart unchanged, for a newer version, a different number of panes, a non-finite or non-positive spacing or offset, invalid margins or range, or a drawing that DrawingManager::add would refuse.

Source§

impl Chart

Source

pub fn take_drawing_sync_ops(&mut self, out: &mut Vec<DrawingSyncOp>)

Takes the drawing operations this chart sent and the host has not taken yet (oldest first, at most MAX_OPS), e.g. to forward them to charts in other workers with Chart::apply_drawing_sync. A new ChartEvent::DrawingSync is reported for the next operation.

§Examples
use ferrochart_core::drawing::{Anchor, DrawingData};
use ferrochart_core::sync::{DrawingSyncOp, SyncGroup, SyncOptions};
use ferrochart_core::{Chart, ChartOptions};

let group = SyncGroup::new();
let mut a = Chart::new(ChartOptions::default());
a.join_sync(&group, SyncOptions { drawings: true, ..SyncOptions::default() });
let line = DrawingData::new("horizontal_line", vec![Anchor { time: 0, price: 100.0 }]);
let pane = a.main_pane();
a.drawings().add(pane, &line)?;
let mut ops = Vec::new();
a.take_drawing_sync_ops(&mut ops);
assert!(matches!(ops[..], [DrawingSyncOp::Add { .. }]));

// A chart in another worker (here: not in the group) applies them.
let mut b = Chart::new(ChartOptions::default());
for op in ops {
    b.apply_drawing_sync(op)?;
}
assert_eq!(b.drawings().ids().count(), 1);
Source

pub fn apply_drawing_sync(&mut self, op: DrawingSyncOp) -> Result<()>

Applies a drawing operation of another chart, e.g. one the host forwarded from another worker. Received drawings go to the main pane; the change is not undoable and is not sent again. An Add of a key the chart already has updates that drawing.

§Errors
Source

pub fn drawing_sync_state(&self) -> Vec<DrawingSyncOp>

The synced drawings of this chart as Add operations, bottom to top: the full state for Chart::load_drawing_sync_state on a chart that joins from another worker.

Source

pub fn load_drawing_sync_state(&mut self, state: &[DrawingSyncOp]) -> Result<()>

Makes the synced drawings match state (from Chart::drawing_sync_state): synced drawings not in it are removed, the others added or updated. Not undoable, not sent again.

§Errors

Error::InvalidArgument if an operation is not an Add, a key repeats, or a drawing cannot be built; the chart is unchanged.

Source§

impl Chart

Source

pub fn join_sync(&mut self, group: &SyncGroup, opts: SyncOptions)

Joins group (leaving the current one, if any), sharing what opts selects. The chart takes over the group’s current crosshair and range at its next frame. With SyncOptions::drawings it first takes over the group’s drawings, then shares its own (of the main pane).

§Examples
use ferrochart_core::sync::{SyncGroup, SyncOptions};
use ferrochart_core::{Chart, ChartOptions};

let group = SyncGroup::new();
let mut charts: Vec<Chart> = (0..4).map(|_| Chart::new(ChartOptions::default())).collect();
for chart in &mut charts {
    chart.join_sync(&group, SyncOptions::default());
}
assert_eq!(charts[0].sync_options(), Some(SyncOptions::default()));
Source

pub fn leave_sync(&mut self)

Leaves the group; the chart’s crosshair is removed from the others.

Source

pub fn sync_options(&self) -> Option<SyncOptions>

What the chart shares, None outside a group.

Source

pub fn apply_sync(&mut self, msg: SyncMessage)

Applies a message from another chart, e.g. one the host forwarded from a ChartEvent::Sync of a chart in another worker. It is not posted again. A range is ignored while the chart has no data.

§Examples
use ferrochart_core::sync::SyncMessage;
use ferrochart_core::frame::Invalidation;
use ferrochart_core::{Chart, ChartOptions};

let mut chart = Chart::new(ChartOptions::default());
chart.apply_sync(SyncMessage::Crosshair { time: Some(1_700_000_000_000) });
assert_ne!(chart.needs_redraw(), Invalidation::None);

Auto Trait Implementations§

§

impl !Freeze for Chart

§

impl !RefUnwindSafe for Chart

§

impl !Sync for Chart

§

impl !UnwindSafe for Chart

§

impl Forget for Chart

§

impl Move for Chart

§

impl Send for Chart

§

impl Unpin for Chart

§

impl UnsafeUnpin for Chart

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.