Time zones and sessions
Store historical bars, streaming updates and shared time ranges as UTC instants. The display zone changes calendar and clock labels; changing it does not rewrite the supplied timestamps or move bars to a new instant. Bars of a day or longer given without a feed keep the date of a 00:00 UTC stamp, or of a stamp at the display zone’s midnight, as the sessions section below describes.
Choose a display zone
Section titled “Choose a display zone”use egui_charts::{ChartBuilder, model::TimezoneId, scales::TimezoneMode};
let mut chart = ChartBuilder::new().build();let mut options = chart.chart_options().clone();options.time_scale.timezone = TimezoneMode::Timezone( TimezoneId::fixed_offset(5 * 3600 + 45 * 60).unwrap(),);options.time_scale.time_visible = true;options.time_scale.seconds_visible = false;chart.set_chart_options(options);TimeScaleOptions::timezone
accepts a TimezoneMode:
| Mode | Display clock |
|---|---|
Utc | UTC, the default. |
Local | The user’s system local zone. |
Timezone(zone) | The selected validated zone. |
Exchange(fallback) | The instrument’s time_zone, or fallback when absent. |
TimezoneId
parses UTC and signed offsets such as +05:45 in every build. IANA names such
as America/New_York require timezones, enabled by default; unavailable names
return an error rather than being approximated. Handle that error when a user
enters a zone. Fixed offsets never observe daylight saving. Named zones use the
offset valid at each UTC instant, including historical daylight-saving changes.
For example, 14:30 UTC displays as 09:30 at offset -05:00 and 10:30 at -04:00.
time_visible
controls whether intraday labels include the clock;
seconds_visible
controls seconds. These presentation settings do not change the bar interval.
Date patterns, calendar language and custom label formatters are covered in
Theming and localization.
Try the same instant in two clocks
Section titled “Try the same instant in two clocks”Toggle UTC +05:45 and compare Stored UTC with Display. Adding five hours and 45 minutes changes the displayed clock, including the date if it crosses midnight; Stored UTC stays identical. Hover a candle to inspect the crosshair time. The scene setup uses the same deterministic history and works without the optional zone database.
Toggle UTC +05:45 and compare the stored timestamp with its display.
The interactive example needs JavaScript and WebAssembly. You can still use the chart setup alongside it.
use std::sync::Arc;
use eframe::egui;use egui_charts::{ Chart, localization, model::TimezoneId, scales::{CustomPriceFormatter, TimezoneMode}, theme::{self, Theme, ThemeExt}, widget::SeriesId,};
/// Change presentation while keeping the same synthetic UTC history.#[derive(Default)]pub struct Presentation { high_contrast: bool, monospace: bool, german: bool, price_units: bool, offset: bool, host_dark: Option<bool>,}
impl Presentation { /// Draw host controls before the chart; only apply settings when they change. pub fn show(&mut self, ui: &mut egui::Ui, chart: &mut Chart) { let dark = ui.visuals().dark_mode; let theme_changed = self.host_dark.replace(dark) != Some(dark); ui.horizontal_wrapped(|ui| { if ui .checkbox(&mut self.high_contrast, "High contrast") .changed() || theme_changed { chart.set_theme_override(self.high_contrast.then(Theme::high_contrast)); } if ui.checkbox(&mut self.monospace, "Monospace font").changed() || theme_changed { if self.monospace { let mut fonts = egui::FontDefinitions::default(); fonts.families.insert( egui::FontFamily::Proportional, fonts.families[&egui::FontFamily::Monospace].clone(), ); ui.ctx().set_fonts(fonts); } else { theme::apply_to_egui(ui.ctx(), &ui.active_theme()); } } }); ui.horizontal_wrapped(|ui| { if ui.checkbox(&mut self.german, "German UI lookup").changed() { if self.german { localization::set_translator(ui.ctx(), |english| match english { "Reset view" => Some("Ansicht zurücksetzen".into()), _ => None, }); } else { localization::clear_translator(ui.ctx()); } chart.set_locale(self.german.then(|| "de-DE".into())); } if ui.checkbox(&mut self.price_units, "Price units").changed() { chart.set_price_formatter(self.price_units.then(|| { Arc::new(CustomPriceFormatter::new(|price| format!("{price:.2} u"))) as Arc<dyn egui_charts::scales::PriceFormatter> })); } }); ui.horizontal_wrapped(|ui| { if ui.checkbox(&mut self.offset, "UTC +05:45").changed() { let mut options = chart.chart_options().clone(); options.time_scale.timezone = if self.offset { TimezoneMode::Timezone(TimezoneId::fixed_offset(5 * 3600 + 45 * 60).unwrap()) } else { TimezoneMode::Utc }; chart.set_chart_options(options); } if ui .button(localization::text(ui.ctx(), "Reset view")) .clicked() { chart.reset_chart_view(); } }); let time = chart.bars(SeriesId::MAIN)[0].time; ui.label(format!("Stored UTC: {}", time.format("%F %T"))); ui.label(format!("Display: {}", chart.format_time(time))); }}Set exchange sessions separately
Section titled “Set exchange sessions separately”A display zone is not a trading calendar. Supply the instrument’s exchange zone
and hours through
Instrument::with_time_zone
and with_session.
For a venue that stays at UTC year round:
use chrono::{NaiveTime, Weekday};use egui_charts::{ChartBuilder, model::{Instrument, Session, SessionWindow, TimezoneId}};
let session = Session::new([SessionWindow::new( vec![Weekday::Mon, Weekday::Tue, Weekday::Wed, Weekday::Thu, Weekday::Fri], NaiveTime::from_hms_opt(9, 0, 0).unwrap(), NaiveTime::from_hms_opt(17, 0, 0).unwrap(),)]);let instrument = Instrument::new("SYNTH") .with_time_zone(TimezoneId::utc()) .with_session(session);let mut chart = ChartBuilder::new().build();chart.set_instrument(Some(instrument));chart.config_mut().show_session_breaks = true;SessionWindow
uses exchange-local opening and closing times with an inclusive open and
exclusive close. A window spanning midnight is named by its closing weekday.
Session
also carries extended windows, overnight windows, holidays and date-specific overrides for early
closes or exceptional openings. An override replaces that date’s weekly hours
and holiday; an empty override closes the date. The host supplies an accurate
calendar and its updates. The library does not fetch exchange hours or data.
Overnight trading, such as 20:00 to 04:00 between the post-market close and the next
pre-market open, belongs in
overnight_windows.
Its market status and shading distinguish it from pre-market and post-market activity.
Chart::set_overnight_hours
selects all hours, including extended hours. History and live requests carry both
extended_hours and overnight_hours; hosts supply data for that choice.
The time scale toolbar reads the chart’s choice with
SessionType::from_chart.
After showing the toolbar, call
TimeframeToolbar::show_session_menu
each frame, setting session_menu_open on OpenSessionMenu, to offer regular and
extended hours, plus overnight hours where supported or already selected. A choice
applies as one undo step and reloads history. Instruments without session hours
show 24/7 and offer no hours choice. The Session selector on the Symbol tab
of chart settings offers the same choices when the host passes the instrument to
SettingsDialog::set_feed_capabilities.
Accepting it also reloads as one undo step.
Enable show_session_breaks
for a line at each new session on intraday intervals and
show_extended_hours
for shading of supplied bars outside regular hours, with a separate overnight tint.
New charts shade the pre-market orange, the post-market blue and overnight bars
purple (#D500F9), each at 8% opacity. The Session backgrounds section of the
Symbol tab switches highlighting and chooses the pre-market, post-market and
overnight colours and opacity. Each phase can stay unshaded. Ok applies these edits; Cancel
keeps the chart’s colours. Templates and Apply to all carry the highlights as well
as the hours choice. Older saved settings without backgrounds keep the chart’s
values. Saved phase colours of None still use extended_hours_color, including
its theme fallback. Shading does not fetch or filter bars. set_session_provider
accepts host-defined break detection; None restores metadata-based breaks.
This replaces boundary detection, not the instrument’s trading calendar.
For feed-built bars, keep the feed’s
BarClock
and session metadata consistent with the venue. Changing display labels cannot
reaggregate prebuilt historical OHLC bars. Daily and longer bars identify trading
dates; follow the data contract rather than applying an offset
to every bar. The bars of the chart’s own feed read their dates on the bar clock
of the display zone. Bars given with
Chart::new,
ChartBuilder or Chart::set_data
read in UTC when the display zone is behind UTC, unless they
sit at its midnight, and in the display zone otherwise, which gives a 00:00 UTC
stamp the same date. A bar stamped at 00:00 UTC on its trading date therefore
keeps that date in the crosshair, the tooltip,
Chart::format_time,
the time axis marks, the chart data table and
Chart::export_csv
in every display zone.
Chart::bar_clock
runs on the same dates, so
bar replay completes such a bar when its date ends and forms the bar of the
cursor’s date there, and studies group the bars into weeks and months by those
dates; pass it to
ReplayController::cutoff.
When the instrument has a session,
bar replay completes such a bar when its last trading window closes, extended
hours included when
Chart::set_extended_hours
selects them, and the finer bars
given with
Chart::set_replay_source
form the bar of their trading date
instead, as data::resample_with_session dates them. The trades and heartbeats
of the chart’s feed join the bar of their trading date too. Intraday bars always
read in the display zone.
Synchronize charts using the
UTC time range, even when their
display clocks differ.