Skip to content

History and live studies

Connect a Datafeed when the chart should request history and accept streaming updates. This scene uses a finite in-memory sample and emits synthetic ticks from the egui frame clock. It needs no network connection or producer thread and runs in the browser. Your application supplies the data service in production.

Select Load older, or drag the chart right to reveal earlier bars. The history page counter increases as the chart requests data. Select Latest to return to the current candle. Its close and high/low change as ticks arrive; the EMA recalculates with it. Every 7.5 seconds of playback, a new candle starts.

Local history and a streaming candleOpen full size

Load older pages, return to Latest and watch the current candle and EMA for at least eight seconds.

The interactive example needs JavaScript and WebAssembly. You can still use the chart setup alongside it.

live_data.rs
use chrono::TimeDelta;
use eframe::egui;
use egui_charts::{
Chart, ChartBuilder,
data::{Datafeed, HistoryPage, HistoryRequest, Reply, Sink, Subscription},
model::{Bar, Tick, Timeframe},
studies::EMA,
widget::SeriesId,
};
use std::{
sync::{
Arc, Mutex,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
struct LocalFeed {
bars: Vec<Bar>,
sink: Mutex<Option<Sink>>,
pages: AtomicUsize,
}
impl Datafeed for LocalFeed {
fn history(&self, request: HistoryRequest, reply: Reply<HistoryPage>) {
let end = self
.bars
.partition_point(|bar| request.before.is_none_or(|before| bar.time < before));
let lower = self
.bars
.partition_point(|bar| request.since.is_some_and(|since| bar.time < since));
let start = end.saturating_sub(request.count.min(200)).max(lower);
self.pages.fetch_add(1, Ordering::Relaxed);
reply.send(Ok(HistoryPage::new(
self.bars[start..end].to_vec(),
start == 0,
)));
}
fn subscribe(&self, subscription: Subscription) {
*self.sink.lock().unwrap() = Some(subscription.sink);
}
}
/// Answer history locally and drive a synthetic stream from the frame clock.
pub struct LiveData {
feed: Arc<LocalFeed>,
started: Option<f64>,
last_step: Option<i64>,
}
impl LiveData {
/// Connect one chart to a finite history and an initially idle stream.
pub fn new() -> (Chart, Self) {
let start = chrono::DateTime::UNIX_EPOCH + TimeDelta::days(20_000);
let bars = (0..1_200)
.map(|i| {
let open = 100.0 + f64::from(i) * 0.01 + (f64::from(i) * 0.1).sin();
let close = open + (f64::from(i) * 0.3).sin() * 0.4;
Bar::new(
start + TimeDelta::minutes(i.into()),
open,
open.max(close) + 0.2,
open.min(close) - 0.2,
close,
100.0,
)
})
.collect();
let feed = Arc::new(LocalFeed {
bars,
sink: Mutex::new(None),
pages: AtomicUsize::new(0),
});
let mut chart = ChartBuilder::new()
.with_symbol("SYNTH")
.with_timeframe(Timeframe::Min1)
.with_feed(feed.clone())
.with_initial_bars(200)
.build();
chart.set_visible_bars(30);
chart.add_indicator(Box::new(EMA::new(20)));
(
chart,
Self {
feed,
started: None,
last_step: None,
},
)
}
/// Emit one tick per quarter second and expose history and latest-bar navigation.
pub fn show(&mut self, ui: &mut egui::Ui, chart: &mut Chart) {
let sink = self.feed.sink.lock().unwrap().clone();
if let Some(sink) = sink.filter(Sink::is_active) {
let now = ui.input(|input| input.time);
let started = *self.started.get_or_insert(now);
let step = ((now - started) * 4.0).floor() as i64;
if self.last_step != Some(step) {
self.last_step = Some(step);
let last = self.feed.bars.last().unwrap();
sink.push_tick(Tick::new(
last.time + TimeDelta::minutes(1) + TimeDelta::seconds(step * 2),
last.close + (step as f64 * 0.3).sin(),
1.0,
None,
));
}
}
ui.horizontal_wrapped(|ui| {
if ui.button("Load older").clicked()
&& let Some(first) = chart.bars(SeriesId::MAIN).first()
{
chart.scroll_to_time(first.time - TimeDelta::minutes(1));
}
if ui.button("Latest").clicked() {
chart.scroll_to_real_time(false);
}
ui.label(format!(
"{} history pages",
self.feed.pages.load(Ordering::Relaxed)
));
});
ui.label("Synthetic ticks: 250 ms apart; a new minute bar every 7.5 s.");
ui.ctx().request_repaint_after(Duration::from_millis(250));
}
}

Create the (chart, live) pair with LiveData::new() once. Call live.show(ui, &mut chart) before chart.show(ui) on each frame. The first show starts the feed; subsequent frames emit at most one tick every 250 ms. Each emitted tick has volume 1. The synthetic clock advances two market seconds per quarter second of elapsed frame time, so a one-minute candle takes 7.5 seconds of continuous playback. Late frames and background tabs may skip ticks; this is an integration sample, not a market clock or a recording.

Datafeed::history receives a HistoryRequest. Answer through its Reply with a HistoryPage. The sample returns at most 200 bars per page from its 1,200-bar history.

  • since includes its boundary; before excludes its boundary.
  • Return the newest count bars within that range, or fewer when a page is smaller.
  • end_of_history is true only when the oldest available bar has been reached. An empty page also ends paging unless it declares continue_before.

The chart merges pages and recalculates studies after prepending bars. In your host, fetch asynchronously and send the reply when ready. Do not block the UI while waiting for a remote response. See the datafeed guide for errors, retries, symbol metadata and lifecycle.

Datafeed::subscribe supplies a Sink. push_tick aggregates trades into the requested interval. The ticks in this scene begin at the minute after the last historical bar. Repeated ticks in one interval update its forming candle; a tick in the next interval starts a new one. Stop emitting when is_active is false. Hosts with complete OHLCV snapshots can use push_bar instead, replacing the same open time as that candle develops.

Keep the chart and its studies alive while feeding them. Returning to the latest bar changes the viewport without clearing the loaded history. Try the custom study or return to the built-in study scene.

These pages reuse the guide’s shared widget bundle. Its studies feature is enabled for EMA and RSI and adds no crates. Measured on 2026-11-03 with Rust 1.99.1, Trunk 0.21.14, the committed lockfile, the wasm-release profile and wasm-opt -Oz:

AssetBefore these scenesWith these scenesgzip level 9, before / after
WebAssembly4,855,666 bytes4,996,997 bytes2,016,078 / 2,071,686 bytes
JavaScript loader73,804 bytes73,804 bytes11,524 / 11,524 bytes

The additional compressed WebAssembly is 55,608 bytes, about 2.8%, so these scenes use the existing cached download rather than a second bundle. Compression was measured per file with Python 3.14.3 and zlib 1.3.1; transfer size depends on the server. The table excludes the HTML page and font licence. Reproduce the optimized build from examples/docs with:

Terminal window
trunk build --release --locked --public-url /egui-charts/docs/examples/widget/

Each embedded scene starts loading only when it approaches the viewport; guide pages without a running example do not request this bundle.