Skip to main content

Chart

Struct Chart 

Source
pub struct Chart {
    pub state: ChartState,
    pub config: ChartConfig,
    pub chart_options: ChartOptions,
    pub marks: Vec<Marker>,
    pub timescale_marks: Vec<Marker>,
    /* private fields */
}
Expand description

Interactive financial chart widget for egui.

Chart is the core rendering and interaction engine for displaying OHLCV financial data. It handles all aspects of chart visualization including candlestick/bar/line rendering, pan/zoom interactions, crosshair display, drawing tool integration, and indicator overlays.

§Creating a Chart

Use Chart::new or Chart::with_config to construct, then call Chart::show each frame to render:

use egui_charts::widget::Chart;
use egui_charts::model::BarData;

let mut chart = Chart::new(bar_data);

egui::CentralPanel::default().show(ctx, |ui| {
    let response = chart.show(ui);
    // response can be used for additional interaction handling
});

§Supported Chart Types

  • Candles – Standard Japanese candlestick chart
  • Bars – OHLC bar chart
  • Line – Close-price line chart
  • Area – Filled area under the close-price line
  • Renko – Fixed-size brick chart (set brick size with Chart::set_renko_brick_size)
  • Kagi – Reversal-based chart (set reversal amount with Chart::set_kagi_reversal_amount)

§Interaction Features

  • Pan: Click and drag to scroll through history (with kinetic scrolling)
  • Zoom: Mouse wheel to zoom in/out, pinch-to-zoom on trackpads
  • Box zoom: Drag-select a region to zoom into (when zoom mode is active)
  • Price scale drag: Drag the price axis to scale vertically
  • Crosshair: Hover to see price/time at cursor position
  • Keyboard shortcuts: Arrow keys, Home/End, +/- for navigation
  • Double-click: Reset zoom on price or time axis

§Architecture

Chart owns a ChartState (data + coordinate systems) and a ChartConfig (visual styling). Rendering is delegated to specialized modules in crate::chart::rendering, while interaction logic lives in crate::chart::state.

Fields§

§state: ChartState

Backend state holding OHLCV data and coordinate system (time scale, price range).

§config: ChartConfig

Visual configuration controlling colors, padding, grid visibility, and more.

§chart_options: ChartOptions

Chart behavior options (bar spacing, scroll/zoom constraints, time scale settings).

§marks: Vec<Marker>

Bar marks (annotations on chart bars, e.g., trade signals)

§timescale_marks: Vec<Marker>

Timescale marks (annotations on the time axis)

Implementations§

Source§

impl Chart

Source

pub fn handle_tracking_mode(&mut self, ui: &Ui, response: &Response)

Manage tracking mode — auto-scroll to the latest bar while active.

Tracking mode keeps the chart viewport anchored to real-time data. It exits automatically based on the configured TrackingModeExitMode: on mouse leave, on next tap, or on touch end. Any manual scroll/zoom/drag also deactivates it.

Source

pub fn handle_keyboard_shortcuts( &mut self, ui: &Ui, response: &Response, chart_width: f32, chart_rect_min_x: f32, )

Process keyboard shortcuts when the chart has focus.

KeyAction
Left/RightPan by configured pan_amount bars
+/-Zoom in/out by zoom_step centered on chart
HomeScroll to latest (real-time) data
FFit all data into the viewport
PageUp/PageDownZoom in/out by 3x zoom_step

Shortcuts are only active when chart_options.keyboard.enabled is true and the chart response has focus.

Source

pub fn request_focus_if_needed(&self, response: &mut Response)

Automatically request keyboard focus when the pointer hovers over the chart, so keyboard shortcuts work without an explicit click.

Source

pub fn set_panning_cursor(&self, ui: &Ui, response: &Response)

Display a grabbing cursor while the user is actively dragging (panning) the chart.

Source§

impl Chart

Source

pub fn handle_mouse_wheel( &mut self, ui: &Ui, response: &Response, chart_width: f32, chart_rect_min_x: f32, price_axis_rect: Rect, ) -> Option<f32>

Handle mouse wheel events for time-axis zoom, price-axis zoom, and horizontal pan.

Returns Some(delta_y) when the wheel was over the price axis, signaling that price zoom should be applied downstream (deferred to avoid borrow conflicts).

Source

pub fn handle_pinch_zoom( &mut self, ui: &Ui, response: &Response, chart_width: f32, chart_rect_min_x: f32, )

Handles pinch-to-zoom for touch/trackpad gestures

This uses egui’s multi-touch zoom_delta which is provided by trackpad pinch gestures and mobile two-finger pinch.

Source

pub fn handle_drag_pan( &mut self, ui: &Ui, response: &Response, price_axis_rect: Rect, time_axis_rect: Rect, chart_rect_min_x: f32, has_active_drawing_tool: bool, )

Handle drag-to-pan, price-axis scaling, and time-axis drag-zoom.

When the drag starts on the main chart area, horizontal movement pans the time axis. Starting on the price axis enables price scale dragging. Starting on the time axis enables drag-to-zoom the time scale. Also tracks velocity for kinetic scrolling continuation after release.

Source

pub fn apply_kinetic_scroll(&mut self, ui: &Ui)

Advance the kinetic scrolling animation by one frame.

Applies the current velocity to the right-offset, then damps the velocity using the configured damping coefficient. Stops when velocity drops below the minimum threshold. Requests a repaint to keep the animation running.

Source

pub fn handle_double_click( &mut self, response: &Response, price_axis_rect: Rect, time_axis_rect: Rect, )

Reset axes on double-click: time axis jumps to latest, price axis re-enables auto-scale.

Source

pub fn handle_box_zoom( &mut self, ui: &Ui, response: &Response, chart_rect: Rect, chart_width: f32, zoom_mode_active: bool, ) -> bool

Handle box-zoom interaction (left-click drag when zoom mode is active).

On press, starts tracking the selection rectangle. On release, either zooms into the rectangle (Zoom mode) or measures price/bar delta (Measure mode). Returns true if a zoom was successfully applied this frame.

Source

pub fn execute_box_zoom( &mut self, start: Pos2, end: Pos2, chart_rect: Rect, chart_width: f32, ) -> bool

Execute box-zoom: compute new bar spacing and right-offset to fill the viewport with the selected region, and apply price zoom to match the vertical selection.

Returns false if the selection rectangle is too small (< 20px in either dimension).

Source

pub fn apply_price_zoom( &mut self, pending_price_zoom: Option<f32>, response: &Response, chart_rect: Rect, adjusted_min: f64, adjusted_max: f64, ) -> (f64, f64)

Apply deferred price-axis zoom from mouse wheel or price-axis drag.

Called after all input processing to avoid mutable borrow conflicts. Updates the chart’s price range and returns the new (min, max).

Source

pub fn apply_timescale_config(&mut self, chart_width: f32)

Apply pending timescale configuration: width, initial visible bars, lock-on-resize behavior, and pending start-index jumps.

Source§

impl Chart

Source

pub fn handle_drawings( &self, ui: &mut Ui, drawing_manager: &mut DrawingManager, cursor_modes: &mut CursorModeState, response: &Response, price_rect: Rect, adjusted_min: f64, adjusted_max: f64, painter: &Painter, last_close_price: Option<f64>, timescale: &TimeScale, )

Handles drawing tool interaction and rendering

This is the main entry point for drawing handling, coordinating:

  • Coordinate transformations between screen and chart space
  • Active drawing tool interactions (click, drag, multi-point)
  • Drawing selection and manipulation
  • Cursor mode effects (Eraser)
§Arguments
  • cursor_modes - Mutable reference to cursor mode state (passed separately to avoid borrow conflicts)
  • last_close_price - The most recent close price (for position drawings P&L)
Source

pub fn render_eraser_highlight( &self, painter: &Painter, drawing_manager: &DrawingManager, cursor_modes: &CursorModeState, )

Render eraser highlight for hovered drawing

Source§

impl Chart

Source

pub fn new(data: BarData) -> Self

Creates a new chart with default configuration.

Initializes the chart with the provided OHLCV data and sensible defaults: candlestick chart type, default bar spacing, data validation enabled, and tracking mode off.

§Arguments
  • data – The OHLCV bar data to display
§Example
let chart = Chart::new(bar_data);
Source

pub fn with_config(data: BarData, config: ChartConfig) -> Self

Creates a new chart with a custom visual configuration.

Use this when you need to control colors, padding, grid visibility, volume display, and other visual aspects from the start.

§Arguments
  • data – The OHLCV bar data to display
  • config – Custom visual configuration (colors, padding, feature flags)
Source

pub fn with_chart_options(self, options: ChartOptions) -> Self

Sets chart behavior options (builder pattern).

Controls bar spacing, scroll/zoom constraints, right offset, and time scale behavior. Applies the time scale options immediately.

Source

pub fn visible_bars(self, count: usize) -> Self

Sets the desired number of visible bars (builder pattern).

The actual bar spacing is computed during rendering to fit count bars in the available width. Also sets the start index to show the latest count bars by default.

Source

pub fn start_idx(self, index: usize) -> Self

Sets the starting bar index for the visible range (builder pattern).

Index 0 is the oldest bar in the data. Use this to start the chart at a specific point in history rather than at the latest data.

Source

pub fn get_visible_bars(&self) -> usize

Returns the number of bars currently visible in the chart area.

This value is computed from the bar spacing and widget width during rendering. Returns 100 as a fallback if the chart has not been rendered yet.

Source

pub fn get_start_idx(&self) -> usize

Returns the current starting bar index of the visible range.

Useful for syncing chart position with external app state or persisting the user’s scroll position across sessions.

Source

pub fn config(self, config: ChartConfig) -> Self

Sets a custom visual configuration (builder pattern).

Controls colors, padding, grid visibility, volume display, and other visual aspects. See ChartConfig for the full list of options.

Source

pub fn update_data(&mut self, data: BarData) -> bool

Updates the chart’s OHLCV data for live/streaming scenarios.

Call this each time new bars arrive or the latest bar’s close price changes. If the chart is near the live edge and shift_visible_range_on_new_bar is enabled in chart options, the viewport automatically scrolls to keep the latest bar visible.

Returns true if the chart auto-scrolled to follow the live edge, false if the viewport position was unchanged (user is scrolled back in history).

§Data Validation

When validation is enabled (default), new bars are checked for anomalies (duplicate timestamps, suspicious price changes). Validation warnings are logged but do not reject data.

Source

pub fn update_config(&mut self, config: ChartConfig)

Replaces the visual configuration on a persistent chart instance.

Use this when reconfiguring a long-lived chart (e.g., after the user changes settings). For initial construction prefer Chart::config.

Source

pub fn set_visible_bars(&mut self, count: usize)

Updates the desired number of visible bars on a persistent chart instance.

Only triggers a recalculation if count differs from the current value. The new bar spacing is applied on the next frame.

Source

pub fn set_start_idx(&mut self, index: usize)

Updates the starting bar index on a persistent chart instance.

Only triggers an update if index differs from the current value. The viewport shift is applied on the next frame.

Source

pub fn set_chart_type(&mut self, chart_type: ChartType)

Sets the chart type (Candles, Bars, Line, Area, Renko, Kagi).

Takes effect on the next rendered frame. For Renko/Kagi charts, also set the brick/reversal size with Chart::set_renko_brick_size or Chart::set_kagi_reversal_amount.

Source

pub fn enable_tracking_mode(&mut self)

Enables tracking mode, which automatically scrolls to keep the latest bar visible.

When enabled, the chart immediately scrolls to the live edge and stays there as new data arrives. Disable with Chart::disable_tracking_mode.

Source

pub fn disable_tracking_mode(&mut self)

Disables tracking mode, allowing the user to scroll freely through history.

Source

pub fn toggle_tracking_mode(&mut self)

Toggles tracking mode on or off.

Source

pub fn is_tracking_mode_active(&self) -> bool

Returns whether tracking mode is currently active

Source

pub fn enable_validation(&mut self)

Enables data validation for incoming bar data.

When enabled, calls to Chart::update_data check new bars for anomalies such as duplicate timestamps or suspicious price spikes. Validation is enabled by default on new charts.

Source

pub fn disable_validation(&mut self)

Disables data validation, skipping anomaly checks on new bars.

Source

pub fn set_validator(&mut self, validator: DataValidator)

Replaces the data validator with a custom-configured one.

Use this to adjust thresholds for duplicate detection or price-spike sensitivity beyond what the default DataValidator provides.

Source

pub fn is_validation_enabled(&self) -> bool

Returns true if data validation is currently enabled.

Source

pub fn chart_type(&self) -> ChartType

Returns the current chart type (Candles, Bars, Line, Area, Renko, or Kagi).

Source

pub fn set_renko_brick_size(&mut self, brick_size: f64)

Sets the Renko brick size in price units.

Each Renko brick represents a fixed price movement of this size. Only affects rendering when the chart type is ChartType::Renko.

Source

pub fn renko_brick_size(&self) -> f64

Returns the current Renko brick size in price units.

Source

pub fn set_kagi_reversal_amount(&mut self, reversal_amount: f64)

Sets the Kagi reversal amount in price units.

A new Kagi line segment is drawn when price reverses by at least this amount. Only affects rendering when the chart type is ChartType::Kagi.

Source

pub fn kagi_reversal_amount(&self) -> f64

Returns the current Kagi reversal amount in price units.

Source

pub fn data(&self) -> &BarData

Returns a reference to the chart’s current OHLCV data.

Useful for progressive/historical loading where you need to inspect the existing data range before prepending or appending bars.

Source

pub fn calculate_visible_bars(&self, width: f32) -> usize

Calculates how many bars fit in the given pixel width at the current bar spacing.

Source

pub fn calculate_bar_spacing(&self, width: f32, visible_bars: usize) -> f32

Calculates the bar spacing (pixels per bar) needed to fit the desired number of bars in the given pixel width.

Source

pub fn get_rendered_price_range(&self) -> (f64, f64)

Get the price range used for actual rendering (includes zoom adjustments)

This is useful for external code that needs to use the same coordinate system as the rendered chart (e.g., selection dots, hit testing).

Source

pub fn get_rendered_price_rect(&self) -> Rect

Get the price rect used for actual rendering

This is the actual screen rect where candles are drawn, useful for external code that needs to draw overlays (e.g., selection dots).

Source

pub fn get_rendered_volume_rect(&self) -> Rect

Get the volume rect used for actual rendering

This is the actual screen rect where volume bars are drawn, useful for external code that needs to draw overlays (e.g., selection dots).

Source

pub fn get_rendered_indicator_panes(&self) -> &[RenderedIndicatorPane]

Get the rendered indicator pane info for hit testing

This returns information about each rendered indicator pane, useful for external code that needs to do hit testing on indicator lines.

Source§

impl Chart

Source

pub fn calculate_layout_rects(&self, widget_rect: Rect) -> ChartLayoutRects

Calculate the layout sub-rects for a given widget rect.

Given the overall widget area, this computes where the price chart, volume bars, and legend/OHLC header will be drawn. Useful for external hit-testing, overlay placement, or custom drawing on top of specific chart regions.

The layout respects current config flags like show_ohlc_info, show_time_labels, and show_volume.

Source

pub fn set_zoom_mode(&mut self, active: bool)

Activates or deactivates box-zoom mode.

When active, left-click drag draws a selection rectangle and zooms into that region. The mode auto-deactivates after a successful zoom operation (check with Chart::zoom_was_applied).

Source

pub fn zoom_was_applied(&self) -> bool

Returns true if a box-zoom was completed in the most recent frame.

Use this to auto-deactivate zoom mode in your toolbar after the user completes a zoom selection.

Source

pub fn set_symbol(&mut self, symbol: &str)

Sets the trading symbol displayed in the chart legend (e.g., “BTCUSD”, “AAPL”).

Source

pub fn set_timeframe_label(&mut self, timeframe: &str)

Sets the timeframe label displayed in the chart legend (e.g., “1H”, “1D”, “1W”).

Source

pub fn set_crosshair_style(&mut self, style: CrosshairStyle)

Sets the crosshair rendering style (Full, Dot, or Arrow).

Use this to connect a toolbar cursor-type selector to the chart. The style controls how the crosshair lines and labels are drawn when the user hovers over the chart area.

Source

pub fn apply_series_settings(&mut self, settings: &SeriesSettings)

Apply series settings to chart colors and price source.

Copies candlestick colors (bullish/bearish fill, border, wick) and the price source field from the given SeriesSettings into the chart’s ChartConfig. Call this when the user changes series appearance in a settings dialog.

Source

pub fn show_with_drawings( &mut self, ui: &mut Ui, drawing_manager: Option<&mut DrawingManager>, ) -> Response

Renders the chart with mouse interactions and optional drawing tools.

This is the mid-level rendering method. Use this when you have drawing tools but no separate-pane indicators. For the simplest case, use Chart::show. For full functionality, use Chart::show_with_indicators.

Source

pub fn show_with_indicators( &mut self, ui: &mut Ui, drawing_manager: Option<&mut DrawingManager>, indicators: Option<&IndicatorRegistry>, ) -> Response

Renders the chart with indicators and drawing tools.

This is the most feature-complete rendering method. Overlay indicators (moving averages, Bollinger Bands, etc.) are drawn on the main price chart. Separate-pane indicators (RSI, MACD, Stochastic) are rendered in dedicated panels below the main chart with aligned x-axes.

After rendering, use Chart::get_rendered_indicator_panes to access indicator pane layout information for hit testing.

§Arguments
  • ui – The egui UI to render into
  • drawing_manager – Optional drawing tool manager for trend lines, etc.
  • indicators – Optional indicator registry containing computed indicators
Source

pub fn show_with_indicators_plot( &mut self, ui: &mut Ui, drawing_manager: Option<&mut DrawingManager>, indicators: Option<&IndicatorRegistry>, ) -> Response

Renders the chart with indicators using simple per-bar x-positioning.

Unlike Chart::show_with_indicators, which uses aligned coordinate parameters from the main chart’s time scale, this method creates indicator panes with basic visible-range positioning. It is simpler but may not perfectly align indicator data points with the main chart when the user scrolls or zooms. Prefer Chart::show_with_indicators for production use.

Source

pub fn show(&mut self, ui: &mut Ui) -> Response

Renders the chart with standard mouse interactions.

This is the simplest way to display a chart. It handles pan, zoom, crosshair, keyboard shortcuts, and all visual elements configured in ChartConfig. No drawing tools or separate-pane indicators are rendered.

Returns an egui::Response for additional interaction handling.

§Example
egui::CentralPanel::default().show(ctx, |ui| {
    let response = chart.show(ui);
    if response.hovered() {
        // Chart is being hovered
    }
});
Source

pub fn set_synced_crosshair_bar_idx(&mut self, bar_idx: Option<f64>)

Sets an external crosshair position from a synced chart (in bar-index coordinates).

When set to Some(idx), a crosshair is drawn at the given bar index even if the user is not hovering over this chart. Pass None to clear it. This is the receiver side of multi-chart crosshair synchronization.

Source

pub fn get_hover_bar_idx(&self) -> Option<f64>

Returns the bar index that the user was hovering over in the last frame.

Returns None if the cursor was not over the chart. This is the emitter side of multi-chart crosshair synchronization: read this value and pass it to Chart::set_synced_crosshair_bar_idx on other charts.

Source

pub fn apply_synced_time_scale(&mut self, bar_spacing: f32, right_offset: f32)

Applies time-scale state from another chart for synchronized scrolling/zooming.

Sets both bar spacing and right offset to match the source chart so that both charts display the same time range. Use together with Chart::get_time_scale_state on the source chart.

Source

pub fn get_time_scale_state(&self) -> (f32, f32)

Returns the current time-scale state as (bar_spacing, right_offset).

This is the emitter side of multi-chart time-scale synchronization. Pass the returned values to Chart::apply_synced_time_scale on other charts to keep them scrolled/zoomed in unison.

Source

pub fn get_chart_mapping(&self) -> ChartMapping

Get a ChartMapping for coordinate conversions.

Returns a mapping constructed from the last rendered frame’s parameters (price rect, bar spacing, right offset, price range). This is used for converting between screen coordinates and data coordinates, particularly for drawing tool restoration and hit testing.

Auto Trait Implementations§

§

impl Freeze for Chart

§

impl RefUnwindSafe for Chart

§

impl Send for Chart

§

impl Sync for Chart

§

impl Unpin for Chart

§

impl UnsafeUnpin for Chart

§

impl UnwindSafe 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.