Reuse the stock-chart CSV parser (same format, same sample file): IndicatorWidget::populate_from_csv / Widget::load_csv_data replace the demo bars and the lines recompute from the loaded series at draw time, so no per-kind wiring was needed. Adds csv::bars_from_rows + date_to_epoch_nanos (Bar::time is nanoseconds; this also makes the four pivot widgets compute real lines instead of all-NaN). Demo series stays as fallback (reset_to_demo, loaded_from_csv flag). Tests: 9 new (all-250 load + recompute + headless draw, pivot fix, bad-CSV keeps demo bars); full workspace suite clean except the pre-existing lightgui-gen fixture failure. Screenshots: 250/250 CSV-loaded renders under Xvfb differ from demo goldens (RMSE 0.0060-0.0661). Docs: docs/indicators-csv.md; rustdoc Ind* pages updated.
15 KiB
Stock chart widgets: how plotting data gets in (Rust)
How the 37 Stock* widgets in lightgui_rust ingest data, what sample
data ships with them (none — see below), and how to plot your own CSV.
The reference implementation is crates/xframe-widgets/src/csv.rs
(parser + derived series) and the loaders on XGraph
(crates/xframe-widgets/src/graph.rs).
The short version
use xframe_widgets::{create, Widget};
let mut chart = create("StockCandlestickChart").unwrap();
chart.set_bounds(40, 40, 720, 520);
let csv = std::fs::read_to_string(
"crates/xframe-demo/examples/data/sample-ohlcv.csv",
).unwrap();
let rows = chart.load_csv_data(&csv).expect("sample CSV loads");
assert_eq!(rows, 30); // 30 bars plotted
Or from the shell, with a live window under Xvfb:
cargo run -p xframe-demo -- StockCandlestickChart \
--csv crates/xframe-demo/examples/data/sample-ohlcv.csv \
--geometry 20,20,760,560 --hold 5
Audit: how data gets in today
All 37 Stock* kinds are one archetype, ChartWidget
(crates/xframe-widgets/src/archetypes.rs), wrapping one XGraph
(crates/xframe-widgets/src/graph.rs). There are not 547 structs: the
kind string (e.g. "CandlestickChart") specialises the archetype.
Data model
XGraph holds a list of GraphSeries:
| Series kind | Stored as | Drawn as |
|---|---|---|
Line |
line: Vec<f64> |
polyline |
OhlcBars |
bars: Vec<XGraphBar{open,high,low,close}> |
OHLC ticks |
Candlesticks |
bars: Vec<XGraphBar> |
candle bodies + wicks |
Bars |
line: Vec<f64> |
vertical bars from the zero line (volume) |
plus x_labels: Vec<String> (one label per bar, shown on the time
axis) and a PlotView (first/count window, auto-y with 6% padding,
wheel zoom, drag pan, crosshair). There is no volume field on a bar
and no timestamp field: volume lives in its own series, dates live
only as string labels.
Setters (the API before CSV existed)
| Method | What it does |
|---|---|
add_line_series(name, colour, values) |
append a line series |
add_ohlc_series(name, colour, bars, candlesticks) |
append an OHLC/candle series |
clear_series() |
drop every series (keeps x labels) |
clear_data() |
drop every series and every x label |
set_x_labels(labels) |
replace the x labels |
set_y_range(lo, hi) / set_auto_y(bool) |
fix the y range / back to auto |
reset_view() / zoom_at(factor, frac) |
show all / zoom around a point |
set_series_kind(i, kind) / set_series_color(i, c) / set_series_up_down(i, up, down) |
retarget one series |
There was no set_data / add_point / populate and no CSV loader
anywhere in the repo. The typical refresh is clear-then-add, then
redraw.
Template / sample data: there is none inside the widget
A fresh ChartWidget / XGraph has an empty series list and draws
nothing — a blank background. No literal sample arrays and no seeded
series are baked into the Rust chart code. (The C repo has
make_seeded_series(n, 42) in widgets/components/StockData.h; the
Rust port of that generator lives in
crates/xframe-widgets/src/indicators.rs as demo_bars(n) and feeds
the Ind* indicator widgets only, not the Stock* charts. The
comment in crates/lightgui-gen/src/gen.rs that used to say
"StockCandlestickChart draws its seeded preview series" was wrong and
has been corrected.) The repo's sample data is the file
crates/xframe-demo/examples/data/sample-ohlcv.csv: 30 weekday bars,
2026-01-05..2026-02-13, a random walk starting at 100.00.
The kind string does not change what is drawn
ChartWidget::draw delegates straight to XGraph::draw, which draws
whatever series are present. Two kinds given the same series render
identically — the kind only decides which series populate_from_csv
builds (see the table below). Per-kind transforms that exist in the C
widgets (Heikin-Ashi, Renko, VWAP, OBV, …) are computed here in
csv.rs at load time, not in the draw path. Annotation overlays
(Trendline, FibRetracement, …) are stored (set_anchor(bar, price),
set_color) but the Rust chart draws no overlays yet.
CSV format
One bar per line, comma-separated, in this column order:
date,open,high,low,close,volume
2026-01-05,100.00,101.20,99.10,100.80,850000
- A header row is optional: the first non-blank line is skipped when its second field is not a number, so the header above is recognised and a file without one just works.
volumeis optional and defaults to0.0when the column is absent. Columns aftervolumeare ignored.- Blank lines and lines starting with
#are skipped. Surrounding whitespace and surrounding double quotes on a field are stripped. dateis kept verbatim as the chart's x-axis label. It must look like a date:YYYY-MM-DD,YYYY/MM/DD,YYYYMMDD, epoch seconds (all digits, 9+), or a date followed by a time (YYYY-MM-DD HH:MM:SS). Anything else is an error naming the line.- The four prices must parse as finite numbers. A bad row is an error naming its line number, and the whole load fails — the chart is left untouched, because the rows are parsed before anything is cleared. An empty file (or header only) is an error.
- No network, no live market data, no API keys.
The parser is xframe_widgets::csv::parse_ohlcv_csv (also exported as
xframe_widgets::parse_ohlcv_csv); rows are OhlcvRow { date, open, high, low, close, volume }.
Per-kind table: what populate_from_csv plots
ChartWidget::populate_from_csv(text) (or the generic
Widget::load_csv_data(text), which forwards to it) picks the series
for the kind. It returns the number of CSV rows loaded. Every loader
replaces all plotted data (clear-then-add).
| Widget | Plots from one CSV | Loader used |
|---|---|---|
StockCandlestickChart |
OHLC as candles | load_ohlcv_csv(…, true) |
StockHollowCandles |
OHLC as candles (hollow up-bodies are not rendered distinctly yet — same candles) | load_ohlcv_csv(…, true) |
StockOHLCBarChart |
OHLC as plain bars | load_ohlcv_csv(…, false) |
StockHeikinAshi |
Heikin-Ashi candles, computed from the rows | load_heikin_ashi_csv |
StockRenko |
Fixed-brick Renko candles from the closes; brick defaults to 1% of the first close (min 0.01), or pass one to load_renko_csv |
load_renko_csv(…, None) |
StockLineChart |
Close line | load_close_line_csv |
StockAreaChart |
Close line (no fill yet — same line) | load_close_line_csv |
StockBaselineChart |
Close line (no baseline fill yet — same line) | load_close_line_csv |
StockCorrelationView |
Close line (single series; a second symbol is needed for a real correlation — see below) | load_close_line_csv |
StockMultiSymbolChart |
Close line (single series; add a second with add_ohlc_csv) |
load_close_line_csv |
StockOverlayChart |
Close line (single series; add a second with add_ohlc_csv) |
load_close_line_csv |
StockRatioChart |
Close line (single series; for a real ratio load two series, then add_ratio_line) |
load_close_line_csv |
StockSpreadChart |
Close line (single series; for a real spread load two series, then add_spread_line) |
load_close_line_csv |
StockIndexedComparison |
Closes indexed to 100 at the first bar | load_indexed_close_csv |
StockRelativePerformance |
Closes indexed to 100 at the first bar | load_indexed_close_csv |
StockSectorComparison |
Closes indexed to 100 at the first bar | load_indexed_close_csv |
StockVWAP |
Price candles plus the VWAP line (2 series; the line is named "VWAP") |
load_vwap_csv |
StockOBVChart |
On-Balance Volume line | load_obv_csv |
StockMoneyFlowChart |
Per-bar money-flow line (multiplier * volume, not cumulative) |
load_money_flow_csv |
StockAccumulationDistribution |
Accumulation/Distribution line (cumulative money flow) | load_accum_dist_csv |
StockVolumeBars |
Volume bars from the zero line | load_volume_csv |
StockVolumeCandles |
Volume candles (open = previous bar's volume, close = this bar's volume) | load_volume_candles_csv |
StockVolumeProfile |
10-bin volume profile: per-price-bin volume bars, "lo-hi" price labels |
load_volume_profile_csv(…, 10) |
Derived-series definitions (csv.rs): VWAP is cumulative
typical * volume / cumulative volume with
typical = (high + low + close) / 3 (zero-volume bars fall back to the
typical price); OBV starts at the first bar's volume and adds /
subtracts the bar's volume when the close rose / fell; the money-flow
multiplier is ((close − low) − (high − close)) / (high − low)
(0 when high == low); A/D is its cumulative multiplier * volume;
Heikin-Ashi is ha_close = (o+h+l+c)/4,
ha_open = (prev_ha_open + prev_ha_close)/2 (first bar: the raw open);
Renko steps a fixed brick from the first close (capped at 50,000
bricks); the volume profile buckets typical price into 10 bins over
[min low, max high].
Drawing-only kinds (no data input)
These 14 plot no data series. populate_from_csv / load_csv_data
returns an error naming the kind; xframe-demo --csv on one exits 2
with that message. Position them with set_anchor(bar, price) instead.
StockArrow, StockBrush, StockEllipse, StockFibExtension,
StockFibRetracement, StockHorizontalLine, StockMeasureTool,
StockParallelChannel, StockPitchfork, StockPriceLabel,
StockRectangle, StockTextAnnotation, StockTrendline,
StockVerticalLine.
Worked examples
Clear / populate refresh
use xframe_widgets::{create, Widget};
let mut chart = create("StockLineChart").unwrap();
let csv = std::fs::read_to_string("data.csv").unwrap();
chart.load_csv_data(&csv).unwrap(); // 30 closes plotted
// New file arrives: re-populate replaces, never accumulates.
let csv2 = std::fs::read_to_string("data2.csv").unwrap();
chart.load_csv_data(&csv2).unwrap();
// Or clear explicitly, then add series by hand.
chart.load_csv_data(&csv).unwrap();
// (no clear_data on the trait; drop down to the concrete widget:)
let mut chart = xframe_widgets::archetypes::ChartWidget::new(
"StockLineChart", "LineChart", 0, 0, 720, 520,
);
chart.populate_from_csv(&csv).unwrap();
chart.clear_data(); // series + x labels gone; chart is blank again
assert!(chart.graph.series.is_empty());
Two-symbol ratio / spread
use xframe_widgets::{Widget, XGraph, XGraphBar};
// XGraph-level loaders: load the first symbol, append the second,
// then derive the line from the two close series.
let mut g = XGraph::new("XGraph", 0, 0, 720, 520);
let a = std::fs::read_to_string("symbol-a.csv").unwrap();
let b = std::fs::read_to_string("symbol-b.csv").unwrap();
g.load_ohlcv_csv("A", &a, true).unwrap();
g.add_ohlc_csv("B", &b, true).unwrap();
g.add_ratio_line().unwrap(); // series "Ratio": A closes / B closes
g.add_spread_line().unwrap(); // series "Spread": A closes - B closes
A zero divisor in the ratio plots as a gap (NaN), not a crash.
add_ratio_line / add_spread_line error when fewer than two
series are loaded.
Loading without the widget: parse + derived series
use xframe_widgets::csv::{parse_ohlcv_csv, vwap_line, obv_line};
let rows = parse_ohlcv_csv(&std::fs::read_to_string("data.csv").unwrap()).unwrap();
let vwap = vwap_line(&rows);
let obv = obv_line(&rows);
Verification
cargo test -p xframe-widgets --test csv_tests: 13 tests — parser (header / no header / optional volume / comments / date formats / errors naming the line), derived-series math against hand-computed values, all 23 data kinds loading the 30-row sample file, all 14 drawing kinds rejecting it, clear/populate refresh, two-symbol ratio/spread, and headlessCanvasrenders proving the CSV data is on screen (candle pixels > 100 where the blank chart has 0).cargo run -p xframe-demo --example csv-chart-shotsrenders all 23 kinds headlessly at 760×560 and diffs each against the blank template: every kind differs by 5,888–131,949 pixels (least: the close-line kinds at 5,888; most:StockVolumeBars).- Live under Xvfb:
xframe-demo StockCandlestickChart --csv sample-ohlcv.csvandStockVolumeBars --csv …show the CSV data with axis labels and legend;StockTrendline --csv …exits 2 with the drawing-overlay error. Screenshots are not committed to the repo; regenerate them with thecsv-chart-shotsexample.
Limits, honestly stated
- One file, one symbol, per load.
populate_from_csvplots one CSV. Multi-symbol kinds (MultiSymbolChart,OverlayChart,CorrelationView,RatioChart,SpreadChart) plot that file's close line (or indexed closes) until a second file is appended withadd_ohlc_csv+add_ratio_line/add_spread_line. - The kind does not change the rendering.
AreaCharthas no fill yet andBaselineCharthas no baseline fill;HollowCandlesdraws the same solid candles asCandlestickChart. The per-kind difference today is which series the loader builds. - No separate volume pane. Volume is its own series on the same
axes (bars from the zero line — the y range is forced to contain 0
when a
Barsseries is present, so the bars stay inside the plot). - Dates are labels only. The x axis shows the CSV date strings; there is no time-scale-aware axis (no weekend gaps, no intraday spacing).
- Overlays are stored, not drawn.
set_anchor/set_coloron the drawing kinds record the geometry; the chart draws no overlay shapes yet. - No live data. Nothing here fetches prices. The sample CSV is
synthetic; bring your own file (or generate one — the C repo's
make_seeded_seriesis the deterministic generator theInd*widgets use). - Renko brick default is 1% of the first close. For a $3 stock
that is $0.03 bricks (hundreds of bricks); for a $3,000 stock it is
$30 bricks (very few). Pass an explicit brick to
load_renko_csvwhen the default does not fit the price level.
See also
crates/xframe-widgets/src/csv.rs— parser + derived series (the CSV format spec lives in its module docs).crates/xframe-widgets/src/graph.rs—XGraphloaders,SeriesKind::Bars, the zero-baseline y range.crates/xframe-demo/src/lib.rs—run_widget_with_csvand the--csvflag of thexframe-demobinary.crates/xframe-demo/examples/csv-chart-shots.rs— headless per-kind renders + blank-template diff.crates/xframe-demo/examples/data/sample-ohlcv.csv— the 30-row sample file.- Doc blog: https://rustdoc.lightgui.com/ — each widget page has a "Plotting your own data (CSV)" section.
docs/indicators-csv.md— the same CSV format, loaded into the 250Ind*indicator widgets (IndicatorWidget::populate_from_csv/Widget::load_csv_data): the indicator lines recompute from the loaded bars, with the built-in demo series as fallback.