Skip to main content

Chart

Struct Chart 

Source
pub struct Chart { /* 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::model::BarData;
use egui_charts::widget::Chart;

let bar_data = BarData::from_bars(bars);

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

egui::CentralPanel::default().show(ui, |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_chart_type_params)
  • Kagi – Reversal-based chart (set reversal amount with Chart::set_chart_type_params)

§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

§Undo and redo

User drawing interactions and shortcuts share Chart::undo / Chart::redo with host toolbar, menu and dialog edits wrapped in Chart::user_action. Direct programmatic setters and feed/data updates do not enter this history. Use Chart::can_undo and Chart::can_redo for toolbar availability, and Chart::take_history_changed to synchronize host controls and data after restoring an interval or settings.

Implementations§

Source§

impl Chart

Source

pub fn alert_data(&self) -> Option<AlertData<'_>>

Lend loaded live bars to the alert evaluator. A paused or replaying chart cannot take over an alert’s live subscription, and loading history keeps its background reader.

Source

pub fn prepare_alert(&self, alert: &mut Alert)

Capture calculation inputs for alert creation, independently of later chart changes. Copies and edits retain the inputs already carried by the alert.

Source

pub fn alert_inputs(&self) -> AlertInputs

A snapshot for an inline alert form. Capture again when the form is shown; submitting it copies this view into the alert, so storage never needs the chart to recover its inputs.

Source

pub fn alert_value(&self, source: &AlertSource, bar: usize) -> Option<f64>

The value source has at bar bar of the main series, which AlertEngine::update takes as its value function and any other evaluator can use: the close for Price, the volume for Volume, the value of the study output at that bar for a Study named by its SeriesId in decimal, and the price of the drawing’s level at that bar for a Drawing named as Drawing::alert_source does.

None for an unknown study, output or drawing, a bar the series does not have, and a value that is not finite.

Source

pub fn alert_sources(&self) -> Vec<(AlertSource, String)>

Every output of every study and every level of every completed drawing, with the name the alert dialog shows, for AlertDialog::sources. Drawing levels are those at the newest bar.

Source§

impl Chart

Source

pub fn drawing_point_time(&self, point: &ChartPoint) -> Option<DateTime<Utc>>

UTC time behind a drawing anchor, retaining fractional and repeated-time positions. Uses the current rendered bars when its index was edited.

Source

pub fn drawing_point_at( &self, time: DateTime<Utc>, price: f64, ) -> Option<ChartPoint>

Map a UTC time and price into drawing coordinates, including times outside loaded bars. Returns None without displayed bars or for a non-finite price or projected index.

Source

pub fn save_drawings(&self) -> Result<DrawingStorage, SaveError>

Exports the current symbol’s drawings with timestamps, using the chart’s own mapping. Between bars time is interpolated; outside them the known timeframe duration or most common positive spacing among the outermost 16 bars is extended (shorter spacing breaks ties, one second if none), retaining repeated-edge ranks. Known month and year intervals step by calendar months in the display time zone. Empty charts export retained anchors; an index with no loaded mapping returns an error rather than clamping or inventing time.

Source

pub fn load_drawings( &mut self, json: &str, ) -> Result<Vec<SkippedDrawing>, LoadError>

Replaces the current symbol’s drawings from a saved file, clears chart undo history and reports skipped records. Rejects a different symbol or an unreadable file without changing the current drawings, with a LoadError that tells a file from a newer release (LoadError::UnsupportedVersion) from damaged data; each skipped record carries its SkipReason. Can run before history arrives: timestamp anchors are projected when bars load. Restored drawings do not queue writes or enter undo history. Screen coordinates follow on the next frame. Account, filesystem and cloud storage remain the host’s responsibility.

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 and tracking mode off. The bars are cleaned as by Chart::set_data.

§Arguments
  • data – The OHLCV bar data to display
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. A non-finite bar_spacing, right_offset or right_offset_pixels keeps its previous value, and a kinetic_scroll.damping_coeff outside 0.0..1.0 is replaced by the default.

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).

On price-based types indices count elements; index 0 is the oldest kept element. Otherwise 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 visible slots, counting elements on price-based types.

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 index of the visible range, counting elements on price-based types.

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

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::with_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. On price-based types index counts elements, with zero the oldest kept element.

Source

pub fn scroll_to_time(&mut self, time: DateTime<Utc>)

Scrolls the bar nearest time to the centre of the chart, keeping the zoom.

Applied on the next frame. A time outside the data shows the nearest end; with a feed, older history is requested until the time is reached or history ends. Panning, zooming, Chart::set_start_idx or tracking cancel it.

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. Price-based chart types take their sizes from Chart::set_chart_type_params. A change clears the zoom history and the series and drawing selection, keeping bar spacing and the time at the right edge. A view near the live edge stays there. On Renko, Kagi, Line Break, Point and Figure and range bar charts, indices count elements instead of bars.

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 chart_type(&self) -> ChartType

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

Source

pub fn range_bar_source(&self) -> Option<RangeBarSource>

What a Range chart’s bars are built from, or None for another chart type. The chart builds them from the trades the feed supplied, including during replay up to its cutoff, and falls back to the OHLC approximation while it holds none.

Source

pub fn set_chart_type_params(&mut self, params: ChartTypeParams)

Sets the parameters of the price-based chart types (Renko, Kagi, Range, Point and Figure, Line Break) and of the baseline.

Fixed sizes are in price units. ATR and percentage methods resolve from the loaded history when this is called, or once enough bars arrive if history is not ready. They then stay fixed through ticks, appends, corrections and prepends. Calling this again or replacing the dataset with Chart::set_data recalculates them. A size the chart cannot use is reported on the chart. On price-based types a change clears the zoom history and selection and keeps the right-edge item by time and rank.

Source

pub fn chart_type_params(&self) -> &ChartTypeParams

Returns the parameters of the price-based chart types and of the baseline.

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 price_axis_width(&self, side: PriceScaleId) -> f32

Width in points of the main price axis on side at the last frame, 0 when that axis is hidden: the configured minimum width, or wider when the labels need more room.

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 change_markers(&self, series: SeriesId) -> Option<ChangeMarkers>

Live change marker settings of a bar series, or None when disabled or absent.

Source

pub fn set_change_markers( &mut self, series: SeriesId, options: Option<ChangeMarkers>, )

Marks, for options.duration after each live update, where the close of series rose or fell against the close of the bar the update replaced: a dot at the new close with a chevron above it for a rise and below it for a fall. Each mark fades linearly to transparent over that duration, and another changed close of the same bar restarts its fade. Updates that leave the close unchanged, new bars and history mark nothing. None removes the markers.

Bar series accept change markers; unknown ids and study ids are ignored with a warning.

Source§

impl Chart

Source

pub fn copy_selected_drawings(&self) -> Result<Option<String>, SaveError>

Copy the selected drawings as versioned text for the host’s system clipboard. Returns None for an empty selection. Anchors retain timestamps across intervals.

Source

pub fn paste_drawings(&mut self, text: &str) -> Result<(), LoadError>

Paste drawing clipboard text as one undoable addition, with new identities and a three-bar offset. Copies belong to this chart’s symbol; timestamps and study panes are mapped against this chart. Selects the copies. Before changing any drawing, rejects text that is not drawing clipboard text (LoadError::NotClipboard), invalid data or a version from a newer release, drawings that could not all be read (LoadError::Skipped) and a chart without the history to place them (LoadError::NeedsHistory). The host handles the system clipboard and forwards its paste event here. Copies of a disabled tool, and copies that saving would refuse, are left out.

Source

pub fn copy_indicator(&self, id: SeriesId) -> Option<String>

Copy study id with its inputs, styles, interval visibility, placement and scale as versioned text for the host’s system clipboard. Returns None for an unknown id.

Source

pub fn paste_indicator( &mut self, text: &str, factory: &IndicatorFactory, ) -> Result<SeriesId, StudyError>

Paste study clipboard text from Self::copy_indicator, on this chart or another, as one undoable addition, and return the new study’s id. factory creates the study by its name. Hands a study pasted beyond the study cap back in crate::studies::StudyError::StudyLimitReached. Rejects other text, a name factory does not know, and inputs or styles the study does not accept, before changing the chart. Study output references need host remapping and are rejected; hosts restore those inputs through Self::add_indicator.

Source§

impl Chart

Source

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

Sets whether the crosshair follows the pointer value or snaps to visible data.

Source§

impl Chart

Source

pub fn set_data_operation_notifications(&mut self, enabled: bool)

Enables an additional ChartEvent::DataOperation for each accepted set_data or update call, in call order, including unchanged data. Disabled by default; changing this setting affects future calls and keeps already queued events. Compact state-change notifications remain available in either mode.

Invalid updates emit no operation event and increment FeedState::rejected_bars. A full replacement still emits one after dropping invalid bars, even if none remain. Unknown, removed, volume and study series accept no data and emit no operation event. During replay, updates are classified against the retained history, including future bars. Feed notifications keep their existing batch semantics; this setting observes direct calls.

Source

pub fn set_pointer_kind(&mut self, kind: Option<PointerKind>)

Overrides the input device reported by pointer events. Set this before show when the host knows the active device, including pens that egui cannot identify. None restores automatic mouse/touch detection. Update it when the active device changes.

Source

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

Drains host notifications in occurrence order. Call after show each frame.

Symbol, interval, data and series setters enqueue immediately; view and pointer changes are measured during show. Unchanged views and pointers emit nothing. Drain regularly: the newest 1024 notifications remain queued until taken; overflow is reported as EventsDropped before the retained events. A new chart’s constructor data emits no load event. This queue does not consume context, quote or selection actions.

chart.show(ui);
for event in chart.drain_events() {
    if let ChartEvent::Click { position, .. } = event {
        // Route the time and price to host-owned application state.
        let _ = (position.time, position.price);
    }
}
Source§

impl Chart

Source

pub fn feed_capabilities(&self) -> Option<&FeedCapabilities>

What the feed offers as a whole, once it has answered Datafeed::capabilities. Pass it to the interval and symbol selectors before a symbol resolves. None without a feed or before the answer.

Source

pub fn set_feed_paused(&mut self, paused: bool)

Suspends feed requests and unsubscribes while the host supplies replay bars by hand. Resuming reloads the current symbol and interval, including any trades retained by the host. Bars supplied while paused are matched by exact opening time. The feed also stays paused while the main series is removed, and follows this setting again once undo restores the series.

Source

pub fn set_symbol(&mut self, symbol: impl Into<String>)

Shows symbol from the next show. With a feed, a changed symbol clears the series and its studies, then resolves, loads and subscribes it, in one load per show however many setters ran; an unchanged one does nothing, also after an error. Drawings and markers are retained separately for each symbol. A changed symbol clears zoom history and returns its price scale to autoscaling. It also clears chart undo history, unless the host makes it inside Self::user_action: then the navigation is an undo step that restores the symbol, interval and viewport, and the steps before it stay with their own symbol. Without a feed replace the bars with set_data.

Source

pub fn forget_symbol(&mut self, symbol: &str) -> bool

Drops the cached drawings, markers and storage reader of an inactive symbol. Returns false for the current symbol or while local drawing edits await a storage read or write acknowledgement. Otherwise returns true, also for an uncached symbol. Stored documents are left in host storage and read again on the next visit. Without storage, forgotten drawings and markers are lost, including pending sync notifications.

Source

pub fn set_timeframe(&mut self, timeframe: Timeframe)

Shows bars of timeframe from the next show, by the rules of set_symbol. Without a feed it sets the legend label and the session breaks only. It is also the interval the drawings’ per-interval visibility is checked against.

Source

pub fn set_extended_hours(&mut self, extended_hours: bool)

Requests regular hours (false, the default) or regular and extended hours (true). A changed choice reloads history and replaces the live subscription on the next frame. Without a feed the host supplies the selected bars with set_data.

Source

pub fn set_conversion(&mut self, conversion: Option<String>)

Asks the feed for data in a currency or unit the host chose, such as "EUR" or "oz", or in the instrument’s own with None. The library converts nothing: the feed does, and labels the resolved instrument’s currency and unit, which the legend and scale headers show. A changed choice drops the bars, trades and depth held, ignores the replies to the previous choice and reloads, resolving through Datafeed::resolve_converted and carrying the choice in every history, trade and depth request and subscription, including those of studies on other symbols. A feed that cannot convert answers FeedError::NotSupported and the chart shows no data. A feed attached later uses it.

Source

pub fn conversion(&self) -> Option<&str>

The currency or unit chosen with set_conversion.

Source

pub fn set_dividend_adjusted(&mut self, adjusted: bool)

Requests history adjusted for dividends (true) or as traded (false, the default), when the feed supports it; comparisons are requested the same way. A changed choice reloads history and replaces the live subscription on the next frame. Without a feed the host supplies the selected bars with set_data.

Source

pub fn dividend_adjusted(&self) -> bool

Whether history is requested adjusted for dividends.

Source

pub fn reload_feed(&mut self)

Reloads the current feed key on the next frame, retaining drawings and chart history. Use after changing host-side feed settings or to retry a permanent request failure.

Source

pub fn extended_hours(&self) -> bool

Whether history and subscriptions request extended hours.

Source

pub fn symbol(&self) -> &str

The symbol the chart shows.

Source

pub fn timeframe(&self) -> Option<Timeframe>

The timeframe the chart shows. A chart built with a feed always has one; None only for a chart made with Chart::new until set_timeframe is called.

Source

pub fn instrument(&self) -> Option<&Instrument>

The feed’s description of the symbol, or metadata supplied with set_instrument.

Source

pub fn trades(&self, series: SeriesId) -> impl Iterator<Item = &Tick>

The trades of series the feed sent, oldest first, at most 100,000. Empty for any id but SeriesId::MAIN and without a feed.

Source

pub fn combined_trades(&self, series: SeriesId) -> Vec<CombinedTrade>

Combines the retained fills with explicit aggressor ids, in first-fill order. At most 100,000 entries; fills without an id stay separate. Rebuilds the view on request, including fills arriving in separate pages or frames. Per-price consumers keep using trades.

Source

pub fn set_volume_bubbles(&mut self, config: Option<VolumeBubblesConfig>)

Draws the trades the feed sends as bubbles, grouped and coloured as the config says, from the next frame, or stops with None. By default, nearby bars and price levels merge when crowded, and diameters adapt to the available screen space. A chart without a feed holds no trades and draws none, and Renko, Kagi, line break, point and figure and range charts draw none, since their x axis is not time. Sums every held trade again: call it when the settings change, not every frame.

Source

pub fn order_book(&self, series: SeriesId) -> Option<&OrderBook>

The order book of series the feed sent, if it holds one. Unavailable during candle-only replay; attach a market replay driver for recorded book state.

Source

pub fn order_queue(&self, series: SeriesId) -> Option<&OrderQueue>

Individual resting orders and their queue priority, when the feed sends order-level data. Use OrderQueue::aggregate with a minimum size for filtered ladders or heatmaps, and largest_order for the largest resting order at a level. Aggregated-only feeds return None; a lost order book has no orders until a replacement snapshot arrives. Candle-only replay hides the live queue.

Source

pub fn set_order_book_view(&mut self, view: OrderBookView)

How the heatmap’s profile and the depth ladder show the live book: which individual orders count, what a bar measures and which orders are highlighted. Its size tiers also mark the heatmap’s cells whose largest recorded order reaches one; the orders the heatmap records are those of DepthHistoryConfig::orders. Applies from the next frame. The profile key names its measure and maximum across all supplied levels, including offscreen prices, after filtering; hovering the strip shows the row’s exact price, side and size. Set OrderBookView::quantity_unit to describe the feed’s quantities; without it the key says “feed units”. A view that needs individual orders on an aggregate feed draws an explicit notice in the pane and an empty ladder, rather than aggregate sizes.

Source

pub fn set_order_book_visible(&mut self, visible: bool)

Show the live book profile at the right edge of the pane, independently of the heatmap. Until explicitly set, the profile follows the heatmap for existing setter callers. Requires a feed and the instrument’s tick size; does nothing without a feed.

Source

pub fn order_book_view(&self) -> OrderBookView

The view set by set_order_book_view, the default of the aggregate book without a feed.

Source

pub fn set_depth_history(&mut self, history: Option<DepthHistory>)

Loads recorded depth from the feed and keeps history of its live book, or stops with None. The history starts empty and is cleared when the symbol or interval changes. It needs the instrument’s tick size, and keeps no columns without one or without a feed. Columns follow the times of the depth updates: an update stamped more than a minute after the feed’s time (Sink::set_server_time) samples nothing, so a wrong time cannot hold the history back. The chart takes the columns sampled since its last frame when it is drawn: while it is not, at most columns of them wait, the oldest making room for new ones.

Source

pub fn set_liquidity_heatmap(&mut self, enabled: bool)

Shows resting liquidity behind the price series. A feed and instrument tick size are required. Enabling starts the default depth history if none is configured; disabling releases textures and retains that history and the appearance settings. Re-enabling an enabled heatmap keeps its textures. Trade bubbles and best bid/ask lines can be enabled independently through the existing chart options.

Source

pub fn set_liquidity_heatmap_config(&mut self, config: LiquidityHeatmapConfig)

Sets the heatmap’s cell brightness and resting-size range from the next frame. A changed appearance redraws the held columns once; an unchanged effective setting uploads nothing. Retained while disabled and in exported images. Does nothing without a feed; enable the heatmap separately with set_liquidity_heatmap.

Source

pub fn liquidity_heatmap_config(&self) -> LiquidityHeatmapConfig

The heatmap appearance supplied by the host, or its default without a feed.

Source

pub fn depth_history(&self, series: SeriesId) -> Option<&DepthHistory>

The order book history of series, if set_depth_history turned it on. Candle-only replay hides the live history.

Source

pub fn bar_clock(&self) -> BarClock

Calendar boundaries selected by the chart, including the resolved exchange or local zone.

Source§

impl Chart

Source

pub fn set_mark_source(&mut self, source: Option<Arc<dyn Marks>>)

Connects a source of bar marks and time-axis events. Replacing or removing the source clears its marks and pending replies; manually supplied annotations are retained.

Source

pub fn reload_marks(&mut self)

Requests fresh marks on the next frame, for example after a host-side event update.

Source

pub fn take_mark_error(&mut self) -> Option<FeedError>

Takes the last mark request error. Retry with reload_marks; errors never clear manual markers. Answers for a previous symbol, interval or viewport are ignored.

Source

pub fn set_time_scale_events(&mut self, events: Vec<TimeScaleEvent>)

Supplies typed corporate, economic and news events independently of a mark source. Replaces the previous list; set_events continues to accept generic badges.

Source

pub fn event_visibility(&self) -> &EventVisibility

Visibility of typed time-axis events, shared with the chart settings dialog.

Source

pub fn set_event_visibility(&mut self, visibility: EventVisibility)

Changes event visibility without discarding the supplied events or fetching them again.

Source§

impl Chart

Source

pub fn set_signal_source(&mut self, source: Option<Arc<dyn Signals>>)

Connects host analytics. Replacing or removing the service clears its signals and stream.

Source

pub fn set_signal_sources(&mut self, sources: Vec<Arc<dyn Signals>>)

Connects several analytics services, each with its own stream and signals, so that one source’s Clear or lagged stream leaves the others’ signals in place. Replacing the sources clears their signals and streams.

Source

pub fn set_signal_category_visible(&mut self, category: &str, visible: bool)

Hides or restores a category without discarding signals or requesting them again.

Source§

impl Chart

Source

pub fn set_price_targets_visible(&mut self, visible: bool)

Show or hide the host’s analyst estimates. Hidden by default; hiding retains the answer. Leave future whitespace in the visible logical range to see the supplied horizon date.

Source

pub fn price_targets_visible(&self) -> bool

Whether analyst estimates are enabled in chart settings.

Source

pub fn price_targets(&self) -> Option<&PriceTargets>

The accepted targets for the current symbol, once answered by the feed.

Source

pub fn reload_price_targets(&mut self)

Ask again on the next frame, for example after estimates change at the host.

Source

pub fn take_price_targets_error(&mut self) -> Option<FeedError>

Take a request or validation error. Unsupported feeds silently leave the chart unchanged.

Source§

impl Chart

Source

pub fn export_csv(&self) -> Result<String, Box<dyn Error + Send + Sync>>

Exports all loaded source bars and visible study plots as UTF-8 CSV. Recalculates copies of the studies so streaming updates and pending refreshes are included without altering the live chart. Price-based charts export source-bar calculations, aligned by source index and plot displacement, rather than mixing element values with source bars. Times include the chart’s UTC offset, including DST changes and subsecond timestamps; on a horizontal scale other than time, keys read as the crosshair label does. Prices inherit instrument precision (two decimals without metadata); study overrides and non-price units retain their precision. Missing/non-finite values are empty cells.

Source

pub fn data_table(&self) -> DataTable

The cells of Self::export_csv (with csv) as a table, with the same bars, study plots, times and precision. During replay it holds the bars the replay cutoff has completed, and on price-based chart types still the source bars. Loads nothing: only loaded bars are listed.

Source

pub fn export_image( &self, ctx: &Context, options: &ImageExportOptions, ) -> Result<ChartImage, ExportError>

Renders an isolated image frame using the same chart, studies, primitives, drawings and scales as the widget. Does not poll feeds, change live viewport state, call the lifecycle hooks of primitives or capture host panels/dialogs. ctx supplies the host’s fonts and style after its first frame. Images use one pixel per point and dimensions between 100 and 7680 on each axis, with at most 33,177,600 pixels. Pass the returned frame to an egui renderer; see ChartImage for delivery responsibilities.

§Errors

Returns ExportError::InvalidSize for dimensions outside the limits, ExportError::NoFrame before the first frame, or ExportError::Unsupported for invalid host textures.

Source

pub fn export_layout_image( &self, ctx: &Context, options: &ImageExportOptions, layout: impl FnMut(&mut Ui, &mut Chart), ) -> Result<ChartImage, ExportError>

Like Self::export_image for a layout of library widgets: layout draws everything inside the image, the toolbars, panels and trading overlays around the chart, and shows the chart it is given, a frozen copy of this one, with Chart::show or Chart::show_footprint. It runs once for each of several layout passes, on a context of its own with no pointer, so its widgets show as at rest. The title and timestamp, if requested, sit above it.

let options = egui_charts::widget::ImageExportOptions::default();
let image = chart.export_layout_image(ctx, &options, |ui, snapshot| {
    ui.horizontal(|ui| {
        ui.label(snapshot.symbol());
        ui.label("1m");
    });
    snapshot.show(ui);
})?;
Source

pub fn export_png( &self, ctx: &Context, options: &ImageExportOptions, ) -> Result<Vec<u8>, ExportError>

Renders the image of Self::export_image on the CPU and encodes it as PNG, so the host needs no renderer or GPU readback. Fails with the reason for content it cannot draw, host paint callbacks and images of textures the host binds itself, such as a legend badge from a user texture, unless ImageExportOptions::textures holds their pixels, instead of leaving it out.

§Errors

Returns the errors of Self::export_image, ExportError::Unsupported for content that cannot be drawn, or ExportError::Encode if the PNG encoder fails.

Source

pub fn export_layout_png( &self, ctx: &Context, options: &ImageExportOptions, layout: impl FnMut(&mut Ui, &mut Chart), ) -> Result<Vec<u8>, ExportError>

Like Self::export_png for a layout of library widgets, drawn by layout as Self::export_layout_image describes.

Source

pub fn export_svg( &self, ctx: &Context, options: &ImageExportOptions, ) -> Result<String, ExportError>

Renders the frame of Self::export_image as an SVG document of the options’ size, with the same title, timestamp, watermark and background. Text stays text, in the font family class of the on-screen font, and the frame’s textures, such as legend icons, are embedded as PNG with png-export enabled, with the host’s ImageExportOptions::textures. Fails with the reason for content SVG cannot take over unchanged, such as host paint callbacks and textures the host binds itself without supplying their pixels, instead of leaving it out.

§Errors

Returns the errors of Self::export_image or ExportError::Unsupported for content the format cannot take over unchanged, including image textures when png-export is off.

Source

pub fn export_layout_svg( &self, ctx: &Context, options: &ImageExportOptions, layout: impl FnMut(&mut Ui, &mut Chart), ) -> Result<String, ExportError>

Like Self::export_svg for a layout of library widgets, drawn by layout as Self::export_layout_image describes.

Source

pub fn export_snapshot( &self, ctx: &Context, options: &ImageExportOptions, ) -> Self

A frozen chart for a multi-chart image layout, with the same background, title, watermark and crosshair choices as Self::export_image. Show it inside the callback of Self::export_layout_image, Self::export_layout_png (with png-export) or Self::export_layout_svg. No storage or live subscriptions are attached; the original chart stays unchanged.

Source§

impl Chart

Source

pub fn format_time(&self, time: DateTime<Utc>) -> String

Formats a timestamp with the chart’s zone, clock visibility and interval, or the median spacing of the source bars in or nearest the view for inferred and trade-based intervals. On a horizontal scale, formats its key as the crosshair does. Hosts can use this for data windows and other readouts beside the chart.

Source

pub fn set_locale(&mut self, locale: Option<String>)

Names months and weekdays in time axis, crosshair, tooltip and forecast date labels in locale’s language, such as "de-DE" (see LocaleTimeFormatter). None restores English names.

The names need the locales cargo feature, on by default; without it they stay English.

Source

pub fn set_date_format(&mut self, date_format: Option<String>)

Writes crosshair, tooltip and forecast dates with a strftime pattern, such as "%d.%m.%Y", followed by the clock for intraday bars. None restores the built-in dates, which an invalid pattern also falls back to.

Source

pub fn set_time_formatter(&mut self, formatter: Option<Arc<dyn TimeFormatter>>)

Formats time axis marks with TimeFormatter::format_tick, whose default calls TimeFormatter::format, and crosshair, tooltip, forecast date and format_time labels with TimeFormatter::format_crosshair.

format_tick receives the chart’s locale in a TickMarkContext and can return None to use the built-in locale-aware text for that tick. Otherwise the formatter replaces the built-in one, the locale and the date format. It receives wall-clock times in the chart’s time zone, and the time scale’s time_visible option still applies. None restores the built-in formatter.

Source

pub fn set_price_formatter( &mut self, formatter: Option<Arc<dyn PriceFormatter>>, )

Formats price scale labels in the normal and logarithmic modes: the crosshair label and price tags with PriceFormatter::format, and the axis ticks with PriceFormatter::format_tick. The formatter receives prices and replaces the instrument’s decimals. It applies to every price scale and to the prices drawings print; studies keep their own formats. None restores the built-in labels.

Source

pub fn set_percentage_formatter( &mut self, formatter: Option<Arc<dyn PriceFormatter>>, )

Formats price scale labels in the percentage and indexed-to-100 modes, as set_price_formatter does in the others. The formatter receives the percentage or index value the axis shows. None restores signed percentages and index values.

Source

pub fn set_volume_formatter( &mut self, formatter: Option<Arc<dyn PriceFormatter>>, )

Formats volume readouts, including volume-formatted studies. None restores the built-in suffixes and instrument volume precision. Values stay in volume units.

Source

pub fn set_series_formatter( &mut self, id: SeriesId, formatter: Option<Arc<dyn PriceFormatter>>, ) -> bool

Overrides raw-price formatting for one bar series, including MAIN. This affects readouts, price tags, ticks and the prices drawings in its pane print; percentage and indexed scales retain the chart’s percentage formatter. None restores chart-wide formatting, then the saved SeriesStyle::display_format. Returns false for an unknown series. A shared axis uses the first visible series’ formatter. Custom text does not replace the declaration’s tick spacing.

Source

pub fn set_session_provider( &mut self, provider: Option<Arc<dyn SessionProvider>>, )

Overrides automatic session breaks with host logic. None restores metadata-based breaks.

Source§

impl Chart

Source

pub fn prepare_conflation( &mut self, bar_spacing: f32, pixels_per_point: f32, ) -> usize

Prepares the main-series conflation groups for bar_spacing in logical points and pixels_per_point (the egui context’s display scale), returning the bars per group. Call after supplying data and configuring conflation_threshold, before showing a dense view at that spacing. Rendering also prepares lazily, using the same cache.

Pan and hover reuse the groups. A changed grouping factor, price source or historical revision rebuilds them; appends and tail updates rebuild only the last existing group and any new groups. Only one factor is retained at a time. This reads the currently applied bars, including a replay cutoff; it does not poll a connected feed. Disabled conflation and price-based chart types return 1 and clear the groups.

Source

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

Renders the chart with its studies and drawings, and handles pan, zoom, crosshair, keyboard shortcuts, the drawing tools and all visual elements configured in ChartConfig.

Overlay studies (moving averages, Bollinger Bands) are drawn on the main pane, any other visible study (RSI, MACD) in a pane below it with its x-axis aligned to the main pane; Chart::get_rendered_indicator_panes returns their layout. A chart built with a feed first asks it for what it needs and applies what it sent. Studies are then brought up to date: an incremental study at once, and at most one study per frame in full, the one that has waited longest.

On price-based types the time scale and reported indices count elements, one OHLC bar per brick, line, column or range bar. Each carries the last contributing bar’s time. Studies use element OHLC on price-based types; time annotations follow element slots. Source-bar study results remain available through Self::indicators.

Reports the series summary and hovered bar values to accessibility clients. Native applications using eframe enable its accesskit feature to connect to screen readers.

Returns an [egui::Response] for additional interaction handling.

Source

pub fn show_footprint( &mut self, ui: &mut Ui, flow: &Footprint, config: &FootprintConfig, ) -> Response

Draws a footprint in place of the price series, below studies, cursor and legend. Supply executions aggregated with the same clock as the chart’s source bars. Bars without complete executions are drawn as candles. While cells would be too narrow to read, every bar is, merged per pixel column when zoomed out. Price-based chart types keep their normal series because their x-axis is not time. config.studies enables execution annotations with the studies feature; config.statistics reserves a per-bar table below the price pane.

Source§

impl Chart

Source

pub fn user_action<R>(&mut self, edit: impl FnOnce(&mut Self) -> R) -> R

Apply one user action from a host toolbar, menu, dialog or intent as one undo step. Nested actions belong to the outer action. Unchanged chart/study settings add no history.

Chart-owned drawing interactions and shortcuts record themselves. Ordinary host calls (including data/feed updates, setters and drawings_mut) do not enter chart history; wrap only edits originating from a user action in this method. Drawing commands and bulk snapshots are transferred from the drawing manager, retaining its sync events. History restores the edited study or settings snapshot, not market data or host state. Hosts without a chart-owned feed should use Self::take_history_changed to reload bars and synchronize their interval/style/settings controls after undo or redo.

Source

pub fn begin_user_action(&mut self)

Begin a user action spanning a host handler that also borrows non-chart state. Pair with Self::end_user_action; prefer Self::user_action when possible.

Source

pub fn end_user_action(&mut self)

Finish the matching Self::begin_user_action, recording only changed components.

Source

pub fn can_undo(&self) -> bool

Whether a chart user action can be undone (also drives toolbar availability).

Source

pub fn can_redo(&self) -> bool

Whether a chart user action can be redone (also drives toolbar availability).

Source

pub fn undo(&mut self) -> bool

Undo the most recent chart user action, across drawings, studies and settings. Returns false while a user action is in progress; finish that action first.

Source

pub fn redo(&mut self) -> bool

Redo the most recently undone chart user action. Returns false while a user action is in progress; finish that action first.

Source

pub fn take_history_changed(&mut self) -> bool

Drain a notification that undo/redo changed chart state. Hosts that own the data must reload it if Self::timeframe or Self::bar_clock changed, and synchronize their UI. Added series that the step removed or brought back are reported by drain_events as ChartEvent::SeriesRemoved and ChartEvent::SeriesAdded.

Source

pub fn edit_count(&self) -> u64

A count that changes with every user edit of the chart, undo and redo included, and with every change of symbol. Compare it with the count at the last save to tell whether the chart changed since, for example to save a layout automatically.

Source§

impl Chart

Source

pub fn shortcuts(&self) -> &ShortcutMap

Bindings used by this chart. Hosts pass this same map to help and menus.

Source

pub fn shortcuts_mut(&mut self) -> &mut ShortcutMap

Edit this chart’s keyboard bindings.

Source

pub fn take_shortcut_requests(&mut self) -> Vec<ShortcutRequest>

Drain commands that need host UI or a host-owned service.

Source

pub fn suppress_shortcuts(&mut self, ctx: &Context)

Give host dialogs keyboard priority over every chart and drawing toolbar this pass.

Source

pub fn dispatch_shortcuts(&mut self, ctx: &Context)

Dispatch keys before other application controls, after dialogs have had their turn.

show also calls this for standalone charts. Each pass dispatches at most once. Text fields, other focused widgets and open popups keep their input.

Source§

impl Chart

Source

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

Zoom programmatically to a screen rectangle from start to end, filling the viewport with the selected time and price ranges. Self::zoom_back undoes it.

Returns false if either dimension of the selection is 20 points or less, or if a corner or the width is non-finite.

Source§

impl Chart

Source

pub fn add_pane(&mut self) -> PaneId

Adds an empty pane at the bottom and returns its id. Fill it with move_series_to_pane. Once its last series or study leaves it the pane is removed, unless set_preserve_empty_pane keeps it.

Source

pub fn remove_pane(&mut self, pane: PaneId) -> bool

Removes a pane with the series and studies it draws. Returns false for the price pane or an unknown id.

Source

pub fn panes(&self) -> Vec<PaneId>

The panes from top to bottom, the price pane included. A study that is not an overlay starts in a new pane at the bottom.

Source

pub fn pane_series(&self, pane: PaneId) -> Vec<SeriesId>

The bar series and studies drawn in pane, in legend order. For the price pane these are the main series, the host series not moved to another pane and the overlay studies. Empty for an unknown pane.

Source

pub fn linked_pane(&self, pane: PaneId, other: &Chart) -> Option<PaneId>

The pane of other that corresponds to the study pane pane of this chart, for linking the drawings of charts in a ChartLayout.

Panes correspond when they hold the same studies, with equal names and input values in the same order. Of several such panes the n-th here corresponds to the n-th there. The price pane and panes without studies have no counterpart.

Source

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

The pane drawing the bar series or study series, or None for an unknown id.

Source

pub fn move_series_to_pane(&mut self, series: SeriesId, pane: PaneId) -> bool

Moves a host series or study into pane, after the series and studies already there. A study moved to the price pane becomes an overlay. Below the price pane a host series shares the pane’s price scale instead of its SeriesScale. Returns false for the main series, an unknown id or pane, or a custom study presentation that rejects placement edits.

Source

pub fn move_indicator_to_pane( &mut self, study: SeriesId, target: SeriesId, ) -> bool

Moves a study to the main pane, another study’s pane, or its own new pane. Use SeriesId::MAIN, the destination study id, or the moved study’s own id respectively. Returns false for an unknown id or a custom presentation that rejects placement edits. move_series_to_pane addresses panes by PaneId.

Source

pub fn move_pane(&mut self, pane: PaneId, index: usize) -> bool

Moves pane to position index from the top, the price pane counting as a pane; an index past the bottom moves it to the bottom. Returns false for an unknown pane.

Source

pub fn swap_panes(&mut self, first: PaneId, second: PaneId) -> bool

Swaps the positions of two panes, either of which may be the price pane. Returns false for an unknown pane.

Source

pub fn pane_height(&self, pane: PaneId) -> Option<f32>

The height of pane in logical pixels as drawn in the last frame, or None when it was not drawn, such as a hidden pane or one left out while another is maximized.

Source

pub fn set_pane_height(&mut self, pane: PaneId, height: f32) -> bool

Gives pane this height in logical pixels from the next frame by setting its stretch factor, so that later resizes keep the proportions. The other expanded panes share the rest by their own factors, and every pane keeps at least 40 pixels. Returns false for an unknown pane or a height that is not finite and positive.

Source

pub fn pane_stretch_factor(&self, pane: PaneId) -> Option<f32>

The stretch factor of pane, or None for an unknown pane. Expanded panes share the chart height in proportion to their factors: 3 for the price pane and 1 for the others by default. A study’s preferred pane height, a dragged separator and set_pane_height set it on the frame that lays the pane out.

Source

pub fn set_pane_stretch_factor(&mut self, pane: PaneId, factor: f32) -> bool

Sets the stretch factor of pane, replacing a height not yet applied. Returns false for an unknown pane or a factor that is not finite and positive.

Source

pub fn set_preserve_empty_pane(&mut self, pane: PaneId, preserve: bool) -> bool

Keeps pane when its last series or study leaves it, instead of removing it. Returns false for the price pane or an unknown id.

Source

pub fn preserves_empty_pane(&self, pane: PaneId) -> bool

Whether pane is kept when it becomes empty; the price pane always is.

Source

pub fn with_pane_options(self, options: PaneOptions) -> Self

Sets the behaviour and colours of the pane separators (builder pattern).

Source

pub fn pane_options(&self) -> &PaneOptions

The behaviour and colours of the pane separators.

Source

pub fn pane_options_mut(&mut self) -> &mut PaneOptions

The behaviour and colours of the pane separators, to change them from the next frame.

Source§

impl Chart

Source

pub fn reorder_indicator(&mut self, id: SeriesId, order: VisualOrder) -> bool

Moves study id in the draw order of its pane, among the pane’s studies and, in the main pane, the price series. Returns false for an id that is not a study of the chart.

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§

impl Chart

Source

pub fn set_post_source(&mut self, source: Option<Arc<dyn Posts>>)

Connects the host service that resolves the links of post and idea drawings. The chart asks once for each link whose content it lacks, gives the answer to every drawing with that link and saves it with them; it never fetches a link itself. Without a source, or after a failed answer, the card says the link could not be loaded; setting a source asks for those links again. Replacing or removing the source drops pending answers.

Source§

impl Chart

Source

pub fn attach_primitive( &mut self, series: SeriesId, primitive: impl Primitive + 'static, ) -> Option<PrimitiveId>

Attaches primitive to series, the main series, an added bar series or a study, to draw in the pane of the series on its price scale from the next show; see Primitive. Several primitives draw in the order they were attached.

Returns None, dropping primitive, when series is not present.

Source

pub fn detach_primitive(&mut self, id: PrimitiveId) -> bool

Detaches a primitive, calling its detached hook if it was attached in a frame. Returns false for an unknown or already detached id.

Source

pub fn add_custom_series( &mut self, study: Box<dyn Indicator>, renderer: impl Primitive + 'static, ) -> SeriesId

Adds a series type the host defines, and returns its id. study supplies its values, which the legend, the crosshair, the last-value tag and the autoscale of its pane read as for any study, in its own pane unless it is an overlay. renderer draws its points in place of the study’s plots and hit tests them: a hit selects the series and is reported as ChartElementId::Indicator. The series is shown, hidden and removed like a study.

Source§

impl Chart

Source

pub fn take_indicator_source_request(&mut self) -> Option<StudySource>

Takes the source preselection requested by a study menu’s Add indicator action. Open the host indicator chooser with this source, then call set_indicator_source on the added study. The chart owns no chooser or account service.

Source

pub fn indicator_value_at( &self, id: SeriesId, index: usize, ) -> Option<(usize, f64)>

The first visible output with a value at a displayed bar index. Price-based charts read element study values, as the legend does. The output number is stable within the study and can be used by host alert services.

Source

pub fn indicator_value_text(&self, id: SeriesId, value: f64) -> Option<String>

Formats a displayed study value with the presentation used by the chart.

Source

pub fn study_values_at(&self, index: usize) -> Vec<StudyValue>

Values of visible study plots at a rendered bar index, with legend names and precision. Gaps remain None; price-based charts use studies calculated from element OHLC. Call after Self::show to use refreshed studies.

Source§

impl Chart

Source

pub fn replay_time(&self) -> Option<DateTime<Utc>>

The exclusive replay cutoff, or None when showing live data.

Source

pub fn replay_driver(&self) -> Option<&Arc<ReplayDriver>>

The shared event driver attached with Self::set_market_replay, if any.

Source

pub fn set_market_replay(&mut self, driver: Option<Arc<ReplayDriver>>)

Replaces the live feed with a shared recording-backed driver, or restores it with None. Retains the live bars, quotes, pause state and feed configuration for exit. Recorded trades build partial bars through the normal feed path, alongside quotes, orders and depth. Attach the same driver to every participating chart, then advance it once per frame before drawing. Its time is inclusive; Self::replay_time reports the exclusive cutoff one nanosecond later. An interval change resubscribes at the same shared position.

Source

pub fn set_replay_time(&mut self, time: Option<DateTime<Utc>>)

Enters or seeks replay, retaining the full history inside the chart. Only bars completed by time reach rendering, studies, auto-scaling and readouts, including the histories that studies request for other symbols and intervals. A bar’s close is its BarClock::next_open; without a timeframe, timestamps are observation instants and bars strictly before time are available. Supply finer bars with set_replay_source to build the unfinished chart bar. No future OHLC is inferred from a completed coarse bar.

The main feed is suspended and current quotes and book views are hidden. Use Self::set_market_replay to replay recorded trades, quotes and depth together. set_data and update retain host corrections behind the window. None exits, restores all retained bars and quotes, and restores the feed’s previous pause state. Hosts own source data and session storage. With a market driver attached this dispatches a seek; call outside egui context locks, as with ReplayDriver::seek.

Source

pub fn set_replay_source(&mut self, bars: Vec<Bar>, clock: BarClock) -> bool

Supplies authoritative finer history for the main series during replay. Its completed bars build the partial chart bar using first open, maximum high, minimum low, last close and summed volume. Earlier chart history stays available. The host must supply all finer bars in the covered chart slots; missing bars are treated as periods without trades.

Recorded trades replay one at a time as bars of one trade each under a clock of Timeframe::Ticks one, as data::aggregate_trades builds them. A trade is an instant: it falls in the chart bar that holds it and is complete once the cutoff passes it, so a ReplayController over the same bars advances the unfinished bar trade by trade. aggregate_trades stamps trades that share a timestamp one nanosecond apart, keeping each a step of its own; bars at one time would replace each other. Bars of more than one trade are refused, since each is stamped at its first trade.

Returns false without changes outside replay, without a chart timeframe, for invalid bars, or when the source intervals do not nest in the chart interval. Input is cleaned and sorted as by set_data. An empty source clears it. Other bar series use completed chart bars. Change playback’s cursor interval to the supplied source interval in the host.

Source§

impl Chart

Source

pub fn selected_element(&self) -> Option<ChartElementId>

Returns the chart element the user has currently selected, if any.

Selection is driven by clicking a series, an overlay indicator line, or a separate-pane indicator line. Host apps read this to open a settings dialog for, or delete, the selected object. Returns None when nothing is selected (for example after a click on empty chart area).

Source

pub fn selected_bar(&self) -> Option<usize>

Returns the index at which the current selection was made, if any. On price-based types it counts elements, otherwise source bars.

This is the data-space index of the segment that was clicked, useful for anchoring tooltips or context menus near the click.

Source

pub fn clear_selection(&mut self)

Clears any current selection.

Equivalent to clicking empty chart area. Call this after the host app has finished acting on a selection (e.g. closing a settings dialog).

Source

pub fn take_right_click(&mut self) -> Option<RightClickTarget>

Drains the right-click target captured during the last frame, if any.

Returns Some exactly once per right-click: the chart hit-tests the cursor against drawings, indicators, and series (same priority as left-click selection) and records where the click landed. The hit object is also selected, so selection handles and any context menu stay consistent.

Hosts that build their own context menus read this each frame and open the appropriate menu at RightClickTarget::pos. With the ui feature, ui::context_menu::ChartMenus consumes it for you.

Carries no ui-feature types, so it is available without the ui feature.

Source§

impl Chart

Source

pub fn add_series(&mut self, options: SeriesOptions) -> SeriesId

Adds a bar series of any time-based chart type, with independent historical and streaming bars, drawn above the main series in the price pane. Supply data through set_data and update; the host owns feeds. Times are projected onto the main series’ time axis, including its whitespace. Move the series to another pane with move_series_to_pane.

Source

pub fn set_series_options( &mut self, id: SeriesId, options: SeriesOptions, ) -> bool

Replaces the display settings of an added bar series, including its chart type, style and scale assignment, as add_series accepts them. Returns false for an unknown id. The main series is styled through set_chart_type, set_chart_type_params, the colours of config_mut and series_style_mut, and assigned with set_series_scale.

Source

pub fn is_fed(&self, id: SeriesId) -> bool

Whether the chart’s feed supplies the bars of a series, as for add_feed_series.

Source

pub fn series_order(&self, id: SeriesId) -> Option<usize>

The position of an added bar series in the draw order, which series follows. Each pane draws its added series in this order: they are drawn above the main series, and a later one covers an earlier one.

Source

pub fn set_series_order(&mut self, id: SeriesId, order: usize) -> bool

Moves an added bar series to position order of the draw order, or to the end for a larger value. Returns false for an unknown id.

Source

pub fn add_feed_series(&mut self, options: SeriesOptions) -> SeriesId

Adds a bar series like add_series whose bars the chart’s feed supplies: the history and live updates of the symbol in options.name, at the chart’s interval, or of a spread such as AAPL-MSFT (see SymbolExpression), computed from the history of each of its symbols. The series pages back as far as the main series, and a new name is a new symbol. A chart without a feed adds a plain series, which the host supplies through set_data; a symbol that contains an operator sign cannot be named.

Source

pub fn add_comparison( &mut self, name: impl Into<String>, color: Color32, ) -> SeriesId

Adds a comparison line on the main series’ scale and switches that scale to percent. Each series uses its own first visible close as zero; scrolling recomputes references.

Source

pub fn series(&self) -> impl Iterator<Item = (SeriesId, &SeriesOptions)>

Added bar series and their display settings, in draw order.

Source

pub fn is_series_visible(&self, id: SeriesId) -> bool

Whether a bar series or study is present and visible.

Source

pub fn set_series_visible(&mut self, id: SeriesId, visible: bool) -> bool

Shows or hides a bar series or study without unloading its data. Returns false when the id is absent. Hidden series do not contribute to auto-scaling.

Source

pub fn set_series_scale(&mut self, id: SeriesId, scale: SeriesScale) -> bool

Assigns a bar series to the right, left, a hidden overlay or an additional labelled scale. Shared assignments share options and manual ranges. Other series retain their assignments.

Source

pub fn series_scale(&self, id: SeriesId) -> Option<SeriesScale>

The scale assignment of a present bar series.

Source

pub fn series_style(&self, id: SeriesId) -> Option<&SeriesStyle>

The numeric display format, last value label, price line, base line, autoscale and click tolerance of a present bar series.

Source

pub fn series_style_mut(&mut self, id: SeriesId) -> Option<&mut SeriesStyle>

Changes the numeric display format, last value label, price line, base line, autoscale or click tolerance of a present bar series. Changes take effect on the next rendered frame.

Source

pub fn series_price_scale(&self, id: SeriesId) -> Option<&PriceScale>

The scale shared by this present bar series, including its options and fitted range.

Source

pub fn series_price_scale_mut( &mut self, id: SeriesId, ) -> Option<&mut PriceScale>

Changes options or a manual range on the scale of this bar series, as returned by series_price_scale. Range bounds use scale units, such as percent in percentage mode.

Source

pub fn series_price_map(&self, id: SeriesId) -> Option<PriceMap>

The price mapping of a present bar series, the main one included, as last drawn in its pane: PriceMap::price_to_y and PriceMap::y_to_price convert between its prices and the y coordinates of the chart’s Ui. None for an absent series, or before its pane is first drawn.

Source

pub fn format_series_price(&self, id: SeriesId, price: f64) -> Option<String>

Formats price as the scale of a present bar series labels it: a price, a signed percentage or an indexed value. None where series_price_map is.

Source§

impl Chart

Source

pub fn take_indicator_settings_request(&mut self) -> Option<SeriesId>

Take the settings request from a legend button or a double-click in a pane: a study, a bar series shown in a pane other than the main one, or SeriesId::MAIN from the main series’ legend button.

Source

pub fn set_data(&mut self, series: SeriesId, bars: Vec<Bar>)

Replaces the bars of series, for history or a replay window. Invalid bars (a non-finite value, a high or low on the wrong side of the open and close, negative volume) are dropped and counted in feed_state, except whitespace bars, which keep their slots empty. The rest are sorted by time, and of several bars with one open time, or in one slot of the timeframe for a chart built with a feed, the last is kept. Drawings retain their timestamps across replacements and interval changes. The studies are updated from the first bar that changed on the next show, and near the live edge the view follows a new last bar, as with update.

Bar series accept data; unknown ids and study ids are ignored with a warning. See set_data_operation_notifications to observe every accepted call, including empty and unchanged replacements.

Source

pub fn update(&mut self, series: SeriesId, bar: Bar)

Merges bar into the bars of series as Sink::push_bar does, matched by open time, or by the slot of the timeframe for a chart built with a feed: a bar that matches a stored bar replaces it, a newer one is appended and an older one is inserted in order. An invalid bar is dropped and counted in feed_state. Drawings move with their bars, studies follow them on the next show, and near the live edge the view follows a new last bar. A merged bar is reported by ChartEvent::DataUpdated.

Bar series accept data; unknown ids and study ids are ignored with a warning. See set_data_operation_notifications to observe every accepted call, including unchanged updates.

Source

pub fn pop_bars(&mut self, series: SeriesId, count: usize) -> Vec<Bar>

Removes the last count bars of series, or all of them for a larger count, and returns them oldest first, leaving the other bars in place. Drawings, studies and the view follow as for update, and ChartEvent::DataUpdated reports the removal. During a replay the bars are removed from the retained history.

Bar series accept this; unknown ids and study ids are ignored with a warning.

Source

pub fn set_bar_limit(&mut self, series: SeriesId, limit: Option<NonZeroUsize>)

Keeps at most limit bars of series. When it holds more, now or after history loads and updates, the oldest are evicted down to limit - limit / 8, so a series that has reached its limit holds between seven eighths of it and all of it. None (the default) keeps all bars. The limit survives symbol and timeframe changes and also bounds retained replay history. Removed data must be supplied again by the host to recover it. Feed scroll-back stops once the main series holds limit - limit / 8 bars, the number an eviction keeps; raising or clearing the limit allows paging again.

Each eviction restarts the studies on the retained window, including their warm-up, so a stream of new bars restarts them once per limit / 8 + 1 bars. Drawing timestamps are kept, even for evicted bars; markers and raw trades have independent lifetimes. Unknown ids and study ids are ignored with a warning.

Source

pub fn bar_limit(&self, series: SeriesId) -> Option<NonZeroUsize>

The retained-bar limit of series, or None when unlimited or absent.

Source

pub fn remove_oldest_bars(&mut self, series: SeriesId, count: usize) -> Vec<Bar>

Removes up to count oldest bars of series, returning them oldest first. Studies restart on the retained window; drawings keep their timestamps and the view keeps its time position where possible. During replay this removes from the full retained history and its matching finer-source slots. Emits ChartEvent::DataUpdated when bars are removed. Unknown ids and study ids are ignored with a warning.

Source

pub fn bars(&self, series: SeriesId) -> &[Bar]

The bars of series, oldest first, with their colours and payloads: bars(id).get(index) is the bar at an index and bars(id).last() the last bar, which can be a whitespace bar. Removed series, volume and studies hold no bars.

Source

pub fn bar_index_at( &self, series: SeriesId, time: DateTime<Utc>, direction: MismatchDirection, ) -> Option<usize>

The index in bars of the bar of series opened at time, or else of its nearest neighbour in direction. None when there is no such bar.

Source

pub fn bars_in_logical_range( &self, series: SeriesId, range: LogicalRange, ) -> Option<BarsInRange>

The bars of series inside range, a range of logical indices of the time scale such as visible_logical_range returns, with the distances to the ends of the series, for example to request older history before the user scrolls to its start. A bar’s logical index is the position of its open time on the time scale, so a series that skips positions counts them. The range’s edges are rounded to whole indices to select the bars. An empty intersection returns an empty slice at the insertion point, with bars_before = range.left - first_index and bars_after = last_index - range.right. Distances at either end of the series also retain the unrounded requested edge. None for a series without bars or a chart without a time scale.

Source

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

Replaces the markers drawn on the bars of series (trade signals, events).

Bar series accept data; unknown ids and study ids are ignored with a warning.

Source

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

The markers of series from set_markers, without those of a mark source. Empty for ids that hold no bars.

Source

pub fn marker_options(&self, series: SeriesId) -> Option<MarkerOptions>

Marker fitting and layering of a bar series, or None for an absent series.

Source

pub fn set_marker_options(&mut self, series: SeriesId, options: MarkerOptions)

Sets whether the markers of series widen its autoscaled price range and where they are painted. The main series’ options also apply to the bar marks of a mark source.

Bar series accept options; unknown ids and study ids are ignored with a warning.

Source

pub fn set_price_lines(&mut self, series: SeriesId, lines: Vec<PriceLine>)

Replaces the price lines drawn on the scale of series. Handles of its previous lines, from add_price_line, no longer refer to a line.

Every bar series accepts price lines. The price scale does not fit to them: a line whose price is off the scale or not finite is not drawn.

Source

pub fn add_price_line( &mut self, series: SeriesId, line: PriceLine, ) -> Option<PriceLineId>

Adds line to the price lines drawn on the scale of series and returns its handle, with which update_price_line moves or restyles it and remove_price_line removes it. None when series holds no bars, as with set_price_lines.

Source

pub fn price_lines( &self, series: SeriesId, ) -> impl Iterator<Item = (PriceLineId, &PriceLine)>

Price lines of a bar series in drawing order, with their handles for editing. Unknown ids and study ids yield no lines.

Source

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

The price line of id, or None once it is removed, replaced by set_price_lines or its series is removed.

Source

pub fn update_price_line(&mut self, id: PriceLineId, line: PriceLine) -> bool

Replaces the price line of id, keeping its place in the drawing order. Returns false when id no longer refers to a line.

Source

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

Removes the price line of id. Returns false when id no longer refers to a line.

Source

pub fn feed_state(&self, series: SeriesId) -> Option<&FeedState>

What the chart knows about the feed of series, such as the bars dropped as invalid. Some for every present bar series.

Source

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

Removes a bar series or study and clears its selection. Removing the main series pauses its feed and retains the time axis for the remaining series and drawings. Undo of the user_action that removed a bar series restores it with its markers, price lines, formatter and bar limit, and for the main series the feed follows set_feed_paused again. Returns false for an unknown or already removed id.

Source

pub fn set_main_series_visible(&mut self, visible: bool)

Show or hide the main price series, its volume and its legend without unloading its bars. Studies and drawings remain visible and continue to receive data.

Source

pub fn is_main_series_visible(&self) -> bool

Whether the main price series is visible.

Source§

impl Chart

Source

pub fn snapshot(&self) -> Result<ChartSnapshot, SaveError>

Captures the chart’s state. Fails while stored drawings are loading, for an unregistered study, when a drawing cannot be saved (see save_drawings) or when restore would refuse the result.

Source

pub fn snapshot_with( &self, factory: &IndicatorFactory, ) -> Result<ChartSnapshot, SaveError>

Captures the chart’s state like snapshot, checking through factory that each study can be built again, so that custom studies it registers are accepted.

Source

pub fn restore( &mut self, snapshot: &ChartSnapshot, ) -> Result<Vec<SkippedDrawing>, RestoreError>

Shows what snapshot captured: its symbol, interval, chart type, settings, studies, added series, panes and view, and its drawings. Studies are built through StudyTemplate::create. Clears undo history and returns the drawings that could not be read. Fails without changing the chart for an unknown study, a study source that names no study, no plot of it or itself, a series or study id used twice, invalid settings or options, a number that is not finite or an unreadable drawings document.

The added series of the chart are replaced by those of the snapshot, which come back without bars and under new ids: look each up with restored_series_id and supply its bars with set_data. Feed-backed series reconnect automatically.

Errors distinguish a saved RestoreError::Study, invalid RestoreError::Settings, RestoreError::Layout geometry and unreadable RestoreError::Drawings.

Source

pub fn restore_with( &mut self, snapshot: &ChartSnapshot, factory: &IndicatorFactory, ) -> Result<Vec<SkippedDrawing>, RestoreError>

Shows what snapshot captured like restore, building the studies through factory, so that studies it registers are restored with their inputs, styles and source links.

Source§

impl Chart

Source

pub fn restored_series_id(&self, saved: usize) -> Option<SeriesId>

The id a series or study of a restored snapshot has now, given its SavedSeries::id or SavedStudy::id, or None for an id the last restore did not add.

Source§

impl Chart

Source

pub fn set_storage(&mut self, storage: Arc<dyn Storage>)

Keeps each symbol’s drawings in storage, in the StoreKind::Drawings document named by the symbol. The drawings of a symbol are read when it is first shown and, when a document holds some, replace the chart’s drawings and undo history; they are written after every drawing edit made through chart history (every user edit, undo and redo) and when the symbol changes. Failed writes retain the latest document and retry after one second of input time; Self::flush_stored_drawings retries immediately. Drawings that could not all be read are never written over.

Charts that show one symbol keep its drawings in one document. A chart reads them again after another chart of the same ChartLayout wrote them to the same storage, and after another client changed them if storage keeps revisions and reports changes through Storage::watch. It does so once nothing of its own is unsaved and no drawing is being drawn, dragged, measured or edited: the stored drawings replace its saveable drawings, selection and undo history, each keeping its local id, and a document deleted elsewhere leaves none. A write waits for such a read, and one that fails is tried again a second of input time later. Drawing sync of a ChartLayout shows drawings of charts outside storage on this chart without saving them here. A drawing whose study the chart does not show appears in the price pane and is written back in its study’s pane. If storage keeps revisions, a write over drawings changed elsewhere since they were read is refused and waits, with the chart’s drawings unchanged, until Self::resolve_storage_conflict settles it; without revisions, the later write replaces the earlier one, including edits on two charts within the time one write takes.

Per-drawing storage notifications are disabled and cleared. To consume them alongside automatic storage, call chart.drawings_mut().set_sync_enabled(true) after attaching it.

Source

pub fn flush_stored_drawings(&mut self) -> bool

Captures current drawing edits and retries failed writes for every symbol immediately. Available replies are processed, but asynchronous storage is not awaited. Returns true once all captured edits are acknowledged. Keep rendering or call again to finish delayed reads and writes; inspect Self::take_storage_error for failures. A write refused because the drawings changed elsewhere stays unacknowledged until Self::resolve_storage_conflict settles it.

Source

pub fn take_storage_error(&mut self) -> Option<StorageError>

The error of a failed read, write or kept-copy operation since the last call, to show to the user. A failed write keeps the drawings on the chart and is reported once. A failed read of drawings changed elsewhere is reported once and tried again a second of input time later until it succeeds. StorageError::Read tells a document from a newer release, which is never written over, from damaged data.

Source

pub fn storage_conflict(&self) -> Option<&str>

The symbol whose drawings storage refused to write because another client changed them after they were read: the shown symbol first, then the others by name. The chart keeps its drawings and writes nothing of that symbol until Self::resolve_storage_conflict settles it; ask the user, for example with ui::dialogs::StorageConflictDialog. None while no refused write waits, including while a kept copy is being written.

Source

pub fn resolve_storage_conflict(&mut self, symbol: &str, choice: ConflictChoice)

Settles the refused write of symbol’s drawings that Self::storage_conflict reports with the user’s choice: read the stored drawings, keep the unsaved ones as the document <symbol> (local copy) (or the next free numbered copy) and read the stored ones, or write the unsaved ones over the stored ones. The drawings change on the next frame or Self::flush_stored_drawings. Does nothing when no write of symbol waits for a choice. Self::local_copies lists the copies kept, to load or discard.

Source

pub fn list_local_copies(&mut self)

Asks storage for the copies of the shown symbol’s drawings that ConflictChoice::KeepLocalCopy kept: the StoreKind::Drawings documents <symbol> (local copy), <symbol> (local copy 2) and so on. Self::local_copies has them once storage answers, on a later frame or Self::flush_stored_drawings. Requests about copies are sent one at a time, each after any copy of its symbol being written. Does nothing without storage or a symbol.

Source

pub fn local_copies(&self) -> Option<&[String]>

The kept copies of the shown symbol’s drawings that the last Self::list_local_copies found, by copy number; None until storage answered it for the shown symbol. A failed listing, reported through Self::take_storage_error, finds none, and a discarded copy leaves the list once storage confirms.

Source

pub fn load_local_copy(&mut self, name: &str)

Replaces the shown symbol’s drawings with those of its kept copy name, one that Self::local_copies lists, as one user action: undo restores the drawings it replaced, and the result is written like any other edit. Drawings that are never saved stay, and the copy stays stored. The copy is read first and loaded once the symbol’s own drawings are read and nothing is being drawn, dragged, measured or edited. A copy that no longer exists or whose drawings cannot all be read changes nothing, and neither does one that arrives after another symbol is shown; Self::take_storage_error reports each. Does nothing for a name that local_copies does not list.

Source

pub fn discard_local_copy(&mut self, name: &str)

Deletes the kept copy name of the shown symbol’s drawings, one that Self::local_copies lists, which then leaves that list once storage confirms. The copy is read first and kept if it does not hold drawings of the shown symbol. Failures are reported through Self::take_storage_error. Does nothing for a name that local_copies does not list.

Source§

impl Chart

Source

pub fn set_study_limit(&mut self, limit: Option<usize>)

Caps the studies at limit, or lifts the cap with None. The cap applies to try_add_indicator and to pasting a copied study, which the terminal’s dialogs and shortcuts use, and to applying a study template set; studies already on the chart stay.

Source

pub fn study_limit(&self) -> Option<usize>

The cap set with set_study_limit; None when uncapped.

Source

pub fn try_add_indicator( &mut self, indicator: Box<dyn Indicator>, ) -> Result<SeriesId, StudyError>

Adds a study like add_indicator, unless the chart already holds as many as study_limit allows. A refused study leaves the chart unchanged and comes back in StudyError::StudyLimitReached.

Source

pub fn add_indicator(&mut self, indicator: Box<dyn Indicator>) -> SeriesId

Adds a study, computed at once from the bars, which show draws: on the main pane if Indicator::is_overlay, otherwise in a new pane at the bottom. Returns the study’s id, which stays valid when other studies are removed. Host code adds past the cap; the interface goes through try_add_indicator.

Source

pub fn set_indicator_inputs( &mut self, id: SeriesId, inputs: impl Into<String>, ) -> bool

Set the input caption displayed beside a study in the legend.

Source

pub fn indicator_inputs(&self, id: SeriesId) -> Option<&str>

The host-supplied input caption of a study, if its id is still present.

Source

pub fn set_indicator_visible(&mut self, id: SeriesId, visible: bool) -> bool

Shows or hides the study id; a hidden study keeps its values. Returns false for an id that is not a study of the chart.

Source

pub fn set_indicator_autoscale(&mut self, id: SeriesId, autoscale: bool) -> bool

Includes or excludes study id from the main price auto-scale, without hiding it. Defaults to true; only visible overlay studies contribute. Returns false for an id that is not a study of the chart.

Source

pub fn set_indicator_scale(&mut self, id: SeriesId, scale: StudyScale) -> bool

Pins study id to the pane’s price scale, a scale of its own or no scale. Returns false for an id that is not a study of the chart, or a custom presentation that keeps its scale.

Source

pub fn indicators(&self) -> impl Iterator<Item = (SeriesId, &dyn Indicator)>

The chart’s studies with their ids, in the order they were added. Their values reflect the bars as of the last show, or of the call to add_indicator. A study that is not updated incrementally can lag the bars by its wait between full recomputes, at least 0.25 s; after the bars changed from the first one on, as when set_data loads other bars or older bars are loaded in front, it has no values until it is recomputed. On price-based types these remain the source-bar results; Self::study_values_at returns the displayed element results.

Source

pub fn indicator_mut( &mut self, id: SeriesId, ) -> Option<&mut (dyn Indicator + 'static)>

The study id, to change its settings. Its values reflect the bars as of the last show; the next one recomputes it in full.

Source

pub fn set_indicator_source( &mut self, id: SeriesId, source: StudySource, ) -> Result<(), StudyError>

Select a price source or another study’s undisplaced output. Rejects missing plots and dependency cycles without changing either study. Hidden sources continue calculating.

Source§

impl Chart

Source

pub fn study_template_set(&self) -> StudyTemplateSet

The chart’s studies as a StudyTemplateSet, in the order they were added. A link to another study’s plot is saved as that study’s position in the set, or past the end of the set when the chart no longer has that study, and the panes record which studies share a pane. Apply the set to this or another chart with apply_study_template_set.

Source

pub fn apply_study_template_set( &mut self, set: &StudyTemplateSet, ) -> Result<Vec<SeriesId>, String>

Replaces the chart’s studies with those of set, built from the built-in studies, as apply_study_template_set_with does with its factory.

Source

pub fn apply_study_template_set_with( &mut self, set: &StudyTemplateSet, factory: &IndicatorFactory, ) -> Result<Vec<SeriesId>, String>

Replaces the chart’s studies with those of set, built through factory, which resolves the names of built-in and host-registered studies, and returns their ids in the set’s order. Each link to a study of the set reads the new study, and a link past the end of the set reads nothing. The studies listed in price_pane are drawn on the price pane, each list in panes becomes a new pane at the bottom, in order, and the other studies are placed as add_indicator places them. The studies are computed at once from the bars. The chart’s volume setting follows the set: a volume study in it becomes the chart’s volume, and without one the setting is off, as when the volume study is removed.

Fails without changing the chart when the set holds more studies than the study cap allows, when its panes name a position twice or past its studies, or when a study cannot be built, with the error of StudyTemplate::create_with. Wrap the call in user_action when it applies a user’s choice, so that one undo restores the previous studies.

Source§

impl Chart

Source

pub fn trade_profile_settings(&self) -> &TradeProfileSettings

Source

pub fn set_trade_profile_settings(&mut self, settings: TradeProfileSettings)

Changes the session profile display without changing its executions or ranges.

Source

pub fn trade_profile_ranges(&self) -> Option<TradeProfileRanges>

Current execution-profile ranges, in time order, over the loaded main bars. Merge and split edits retain UTC boundaries across history eviction and prepending.

Source

pub fn merge_trade_profile(&mut self, index: usize) -> bool

Merges the indexed execution profile with its next neighbour. Returns false if absent.

Source

pub fn split_trade_profile(&mut self, index: usize, time: DateTime<Utc>) -> bool

Splits the indexed execution profile at a loaded bar’s timestamp or clock-slot open. Endpoints and times between bars leave the ranges unchanged.

Source

pub fn reset_trade_profile_ranges(&mut self)

Restores the natural session boundaries for execution profiles.

Source§

impl Chart

Source

pub fn create_drawing( &mut self, drawing: Drawing, points: &[(DateTime<Utc>, f64)], ) -> Result<usize, DrawingError>

Creates a completed drawing from UTC times and prices, with the supplied drawing’s properties, pane, group and layer. Its id and storage identity are replaced. Returns an error without changing history or drawings for invalid anchors or settings. Times can precede loaded history; their projection is updated when bars arrive. Wrap this call in Self::user_action to include it in chart undo history.

use egui_charts::{Chart, drawings::{Drawing, DrawingToolType}};
let mut chart = Chart::new(egui_charts::model::BarData::default());
let time = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();
let mut line = Drawing::new(0, DrawingToolType::HorizontalLine);
line.locked = true;
let id = chart.create_drawing(line, &[(time, 100.0)]).unwrap();
assert_eq!(chart.drawing_points(id).unwrap(), vec![(time, 100.0)]);
Source

pub fn drawing_points(&self, id: usize) -> Option<Vec<(DateTime<Utc>, f64)>>

Returns a drawing’s UTC anchors and prices, or None for an unknown id or an index without a time mapping. Retains exact supplied times between bars and in whitespace.

Source

pub fn set_drawing_points( &mut self, id: usize, points: &[(DateTime<Utc>, f64)], ) -> Result<(), DrawingError>

Replaces a drawing’s anchors as one undoable edit. Invalid points and locked drawings leave the original untouched. Screen positions are rebuilt on the next frame.

Source

pub fn set_drawing_image( &mut self, id: usize, uri: impl Into<String>, size: Vec2, ) -> Result<(), &'static str>

Sets an image drawing’s picture as one undoable edit. uri is the address the host’s image loaders resolve, and size is its pixel size, which gives the frame its proportions, scaled down to fit 240 x 180 points. Closes this drawing’s text editor. Unknown, locked and non-image drawings, an empty address and a size that is not positive and finite change nothing. Each frame side is at least one point.

Source

pub fn drawing_pane(&self, id: usize) -> Option<PaneId>

The pane that draws drawing id, or None for an unknown drawing.

Source

pub fn move_drawing_to_pane(&mut self, id: usize, pane: PaneId) -> bool

Moves drawing id into pane as one undoable edit, keeping its anchors and style; the anchors’ prices are read on the new pane’s scale. Returns false for an unknown drawing or pane and for a locked drawing.

Source§

impl Chart

Source

pub fn study_data_requests(&self) -> Vec<StudyDataRequest>

Histories required by feed-backed series, study inputs and profile drawings, with chart defaults resolved. Hosts without a connected feed supply these through Self::set_study_data. A connected feed receives resolve, history and subscription calls automatically on the next frame.

Source

pub fn set_study_data( &mut self, request: StudyDataRequest, bars: Vec<Bar>, instrument: Option<Instrument>, )

Replace a study history with host-owned historical or streaming bars. Bars are sorted, deduplicated and validated like chart data. This takes ownership of this request from the connected feed; the host supplies further replacements. Metadata sets its calendar.

Source

pub fn study_data_error(&self, request: &StudyDataRequest) -> Option<&FeedError>

The last error for a requested study history. Recoverable resolve and page failures retry with exponential backoff, respecting rate limits; success clears the error. An unavailable source leaves gaps.

Source§

impl Chart

Source

pub fn hover_time(&self) -> Option<DateTime<Utc>>

The time of the nearest hovered bar or price-based element, or None outside the data.

Source

pub fn set_synced_crosshair_time(&mut self, time: Option<DateTime<Utc>>)

Shows a crosshair at the local bar whose period holds time, from its open until the next bar of its interval opens. Between bars it marks the nearest one; ties choose the earlier bar. Times before the first bar or after the last bar’s period, and None, clear it. Repeated element times choose the first element. Each receiver resolves the timestamp against its own series, including after bars are evicted or older history is loaded.

Source

pub fn set_crosshair_position(&mut self, position: Option<(DateTime<Utc>, f64)>)

Shows a crosshair at the local bar for time, as Self::set_synced_crosshair_time does, with its horizontal line and price label at price on the main price scale. None, a time outside the data or a non-finite price clears it. The pointer’s own crosshair takes its place while the pointer is over the plots.

Source

pub fn visible_time_range(&self) -> Option<VisibleTimeRange>

The visible UTC range, including whitespace mapped by Self::index_to_time. Empty charts return None. Between bars, time is interpolated, so session gaps retain fractional edge positions.

Source

pub fn apply_synced_time_range(&mut self, range: VisibleTimeRange) -> bool

Fits the receiver’s bars to a UTC range using its own plot width. Returns false without changing the view for empty data, reversed or zero ranges, a range that ends before the first bar’s slot or starts after the last bar’s period, or endpoints mapping to the same element. Spacing stops at the configured maximum, or 50 pixels when unlimited, centring short spans. The minimum spacing and local edge constraints still apply, and the fit keeps a bar in view: a range longer than the plot at the minimum spacing shows the newest bars.

Source

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

Sets a crosshair in local index coordinates, counting elements on price-based types. None clears it. Use Self::set_synced_crosshair_time between independent charts.

Source

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

Returns the nearest hovered local index from the last frame, counting elements on price-based types. Use Self::hover_time to exchange positions between charts.

Source

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

Restores local bar spacing and right offset, for example after inspecting another view. These coordinates depend on the data and plot width. Use Self::apply_synced_time_range between independent charts.

Source

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

Local time-scale state as (bar_spacing, right_offset), for view restoration. Use Self::visible_time_range to exchange viewports between independent charts.

Source§

impl Chart

Source

pub fn fit_content(&mut self)

Fits every bar into the plot width, then restores the configured right offset.

The right offset, in bars or pixels, is kept free of bars. The bar spacing limits still apply.

Source

pub fn reset_time_scale(&mut self)

Restores the configured bar spacing and right offset, leaving the price scale unchanged.

Source

pub fn reset_chart_view(&mut self)

Restores the configured bar spacing and right margin, scrolls to the latest bar and returns every price scale in every pane to auto-scaling. Scale modes and inversion stay. Pending scrolls, animations and requested visible-bar counts are cancelled.

Source

pub fn scroll_to_real_time(&mut self, animated: bool)

Scrolls to the latest bar with the configured right offset, keeping the zoom.

Unlike Chart::enable_tracking_mode, the view does not keep returning to the latest bar afterwards. animated scrolls over 400 ms instead of jumping.

Source

pub fn scroll_to_position(&mut self, position: f32, animated: bool)

Scrolls the latest bar position bars from the right edge, keeping the zoom.

Positive positions leave empty space on the right and negative ones scroll into history; the edge limits of the time scale options still apply. animated scrolls over one second instead of jumping. Ignores non-finite positions.

Source

pub fn visible_logical_range(&self) -> Option<LogicalRange>

The visible range of logical indices, None without data.

Index 0 is the oldest bar, or the oldest element on price-based chart types. Both bounds are fractional and may lie outside the data, in whitespace before the first bar or after the last. right is the index at the right edge less half a bar, so a range spans right - left + 1 bar widths of plot.

Source

pub fn set_visible_logical_range(&mut self, range: LogicalRange) -> bool

Shows the logical range across the plot width of the last frame, setting both the bar spacing and the scroll position, so Chart::visible_logical_range returns it.

Returns false without changing the view for empty data, non-finite bounds or a right below left. The bar spacing and edge limits still apply.

Source

pub fn index_to_time(&self, index: f64) -> Option<DateTime<Utc>>

The UTC time at a logical index, None without data or for a non-finite index.

Between bars the time is interpolated, and in whitespace it is extrapolated, as in Chart::visible_time_range, by the known timeframe duration or the most common positive spacing among the outermost 16 bars (shorter spacing breaks ties, one second if none). A step that divides an hour keeps the slots on the grid of the regular bars nearest the edge, so a partial edge bar does not shift them. Known month and year timeframes step by calendar months in the display time zone when the edge bars fall at its midnight, and in UTC otherwise.

Source

pub fn time_to_index(&self, time: DateTime<Utc>) -> Option<f64>

The fractional logical index of a UTC time, None without data.

The inverse of Chart::index_to_time: a time between two bars lies between their indices, and a time outside the data is extrapolated into whitespace.

Source

pub fn set_horizontal_scale(&mut self, scale: Option<Arc<dyn HorizontalScale>>)

Gives the horizontal axis a meaning other than time, such as option strikes or bond maturities. The time of each bar, marker and drawing then holds a key of scale, which labels the axis and the crosshair; everything placed by time is placed by key. None restores the time scale.

Session breaks and extended-hours shading are periods of time, drawn on the time scale only.

Source

pub fn index_to_x(&self, index: f64) -> Option<f32>

The screen x of a logical index in the last frame, at the centre of its bar.

None before the chart is shown or for a non-finite index.

Source

pub fn x_to_index(&self, x: f32) -> Option<f64>

The fractional logical index at a screen x in the last frame, the inverse of Chart::index_to_x. Round it for the nearest bar.

None before the chart is shown or for a non-finite x.

Source

pub fn time_scale_size(&self) -> Vec2

The size of the time axis below the plots in the last frame, in points.

The width is the plot width; the height is zero while time labels are hidden.

Source§

impl Chart

Source

pub fn set_instrument(&mut self, instrument: Option<Instrument>)

Supplies instrument metadata for a chart without a feed, including price precision and the default tick-mark grid. An explicit tick_marks.min_price_step takes precedence. Pass None to clear the metadata. Feed metadata takes precedence when available.

Source

pub fn set_currency_choices(&mut self, currencies: Vec<String>)

Supplies currencies the host can convert the chart into. Choosing one emits an intent; the host replaces bars and instrument metadata together after conversion.

Source

pub fn take_currency_choice(&mut self) -> Option<String>

Takes the selected currency. No prices change until the host supplies converted data.

Source

pub fn set_legend_badge(&mut self, badge: Option<ImageSource<'static>>)

Supplies an image for the legend’s symbol mark in place of Instrument::logo. None shows the instrument’s logo, or the symbol’s initial without one; ChartConfig::show_legend_badge hides the mark.

Source

pub fn set_watermark(&mut self, watermark: Option<Watermark>)

Paints watermark behind the series of the price pane, in addition to the symbol watermark of ChartConfig::show_watermark. None removes it.

Source

pub fn set_legend_statuses(&mut self, statuses: &[LegendStatus<'_>])

Supplies status marks and their host-defined meaning and colours.

Source

pub fn set_quote(&mut self, quote: Option<Level1Quote>)

Supplies the current bid and ask, independently of the hovered historical bar. Pass None when quotes are unavailable or the symbol changes.

Source

pub fn set_server_time(&mut self, now: Option<DateTime<Utc>>)

Supplies the current server time for a chart without a feed. The clock advances between calls; update it when a replay jumps. None restores the feed clock or latest quote time.

Source

pub fn set_bar_close_time(&mut self, close: Option<DateTime<Utc>>)

Supplies an exact closing instant for the newest bar, for irregular sessions or replays. None derives the close from the timeframe and the instrument’s session.

Source

pub fn set_right_margin(&mut self, bars: f32)

Sets the right margin in bars and moves to that margin when it changes.

Source

pub fn set_session_quote(&mut self, quote: Option<SessionQuote>)

Supplies an independent extended-session price and qualifier. None hides the tag.

Source

pub fn set_events(&mut self, events: Vec<Marker>)

Supplies event badges at the time-axis boundary, separately from bar annotations.

Source

pub fn take_event_click(&mut self) -> Option<String>

Takes the ID of the last clicked event badge.

Source

pub fn take_scale_settings_request(&mut self) -> bool

Takes a request to open the host’s price-scale settings.

Source

pub fn take_quote_action(&mut self) -> Option<QuoteSide>

Takes the last legend quote click. No order is submitted by the chart.

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_back(&mut self) -> bool

Restore the view preceding the last box zoom. Drawing and chart edit history is unchanged.

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_crosshair_style(&mut self, style: CrosshairStyle)

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

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 set_tooltip_enabled(&mut self, enabled: bool)

Enables the configured values readout without changing pan or zoom.

Source

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

Apply series settings to chart colors, price source and price scale.

Copies candlestick colors (bullish/bearish fill, border, wick) and the price source field from the given SeriesSettings into the chart’s ChartConfig, and its scale mode and inversion into the main price scale. A new scale mode returns the scale to auto-scaling and clears the zoom history, whose ranges are in the old mode’s units. Call this when the user changes series appearance in a settings dialog.

Source

pub fn series_settings(&self) -> SeriesSettings

Read the current appearance and chart type parameters for the series settings dialog. Pass the result to SeriesSettingsDialog::open, then apply its accepted settings with Self::apply_series_settings. The active chart type is dialog context only.

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. On price-based chart types its indices count elements instead of source bars.

Source

pub fn config_mut(&mut self) -> &mut ChartConfig

Returns a mutable reference to the chart’s visual configuration.

Use this to edit visual options in place, e.g. chart.config_mut().show_grid = false, without rebuilding the whole ChartConfig. Changes take effect on the next rendered frame. Wrap a host UI submission in Self::user_action to include it in chart history.

Source

pub fn set_theme(&mut self, ctx: &Context, theme: &Theme)

Apply a theme to this chart and to the UI in ctx, without changing data or pan and zoom.

Other charts sharing the context follow the active theme on their next frame, keeping colours the host has edited and any per-chart theme override.

Source

pub fn set_theme_override(&mut self, theme: Option<Theme>)

Overrides this chart’s palette and text sizes without changing sibling charts or egui.

Some(theme) also applies its series colours to the chart configuration. Explicit configuration edits made afterwards are kept. None follows the host’s palette again, retaining host-edited colours. set_theme clears this override and themes egui.

Source

pub fn config(&self) -> &ChartConfig

The chart’s visual configuration.

Source

pub fn chart_options(&self) -> &ChartOptions

The chart’s behaviour options, set with Chart::with_chart_options or Chart::set_chart_options.

Source

pub fn set_chart_options(&mut self, options: ChartOptions)

Replaces the chart’s behaviour options at runtime, taking effect on the next frame.

To change some options and keep the rest, edit a copy of the current ones:

let mut options = chart.chart_options().clone();
options.crosshair.mode = egui_charts::config::CrosshairMode::Magnet;
options.time_scale.min_bar_spacing = 0.1;
chart.set_chart_options(options);

The view is kept: the bar spacing changes only when time_scale.bar_spacing changes or the new spacing bounds exclude it, and the chart scrolls only when time_scale.right_offset or right_offset_pixels changes. A non-finite bar_spacing, right_offset or right_offset_pixels keeps its previous value, and a kinetic_scroll.damping_coeff outside 0.0..1.0 is replaced by the default.

Source

pub fn set_size(&mut self, size: Option<Vec2>)

Gives the chart an explicit size in points instead of filling the space show is given; None, the default, fills it again. The size includes the axes and study panes.

Source

pub fn size(&self) -> Option<Vec2>

The explicit size set with Chart::set_size.

Source

pub fn state(&self) -> &ChartState

The chart’s bars, time scale, price scale and zoom history, to read them.

Source

pub fn price_scale_mut(&mut self) -> &mut PriceScale

The main price scale, to zoom it or change its mode and options.

Source

pub fn drawings(&self) -> &DrawingManager

The chart’s drawings and drawing tools.

Source

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

The chart’s drawings and drawing tools, to set the active tool or to save and load the drawings. Direct host edits do not enter chart history; wrap UI-originated edits in Self::user_action. The manager’s own history is for standalone drawing use.

Auto Trait Implementations§

§

impl !Freeze for Chart

§

impl !RefUnwindSafe for Chart

§

impl !Sync for Chart

§

impl !UnwindSafe 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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

§

fn simd_from(_simd: S, value: T) -> T

§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

§

fn simd_into(self, simd: S) -> T

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.