# I Built a Charting Engine in Rust for Flutter: How nalgo-chart Works, with the Maths

- URL: https://www.dhruvvakharwala.dev/blogs/rust-charting-engine-flutter-nalgo-chart
- Author: Dhruv Vakharwala (https://www.dhruvvakharwala.dev/about)
- Published: November 24, 2026
- Category: Engineering
- Keywords: rust charting engine, flutter chart, rust ffi flutter, dart ffi, webassembly chart, candlestick chart engine, klinecharts alternative, lightweight charts alternative, chart performance, drawvertices

> A Rust charting engine drawn from Flutter over a C ABI and WebAssembly: scales, layers, triangles, indicators, the maths, and 7.5 us per tick with no GPU.

**TL;DR:** I am building an algo trading platform where any user can connect any broker. One piece of it is a charting engine. I started with the open-source **KLineChart** in the web app, but I wanted to own the whole chart so I could keep optimizing it from my side, so I wrote my own chart engine in **Rust** (`nalgo-chart`), exposed it over a **C ABI** (`chart-ffi`), and draw it from **Flutter**: `dart:ffi` on iOS and Android, **WebAssembly** on the web. The engine does all the maths (scales, bars, indicators, layout) and hands Flutter a flat buffer of ready-made triangles. In my recording, on a cloud box with 4 vCPUs, **no GPU** and a screen recorder running, one chart at 5,000 ticks/s cost **7.5 us per tick**, a grid of 9 charts at 200 ticks/s each rendered in **94 us per chart**, and the same Rust code natively on one core drew a full 50,000-bar frame in **12 us**. This post is the whole design: how other open-source engines work, what is different here, the maths with worked numbers, what the measurements do and do not say, and what the new GPU crate is for. I never ran a head-to-head against KLineChart, so there is no "X times faster" claim anywhere below.


![nalgo-chart cover: three measured numbers from the recording, 7.5 us per tick at 5,000 ticks/s, 94 us per chart in a grid of 9, and 12 us for a native 50,000-bar frame](https://www.dhruvvakharwala.dev/images/blog/rust-charting-engine-flutter-nalgo-chart/cover.png)

[The 136 second speed showcase: indicators, drawings, trade lines, compare, replay, tick stress up to 5,000 ticks/s, then grids of 4 and 9 charts. The last frame is the measured summary.](https://www.dhruvvakharwala.dev/videos/blog/rust-charting-engine-flutter-nalgo-chart/speed-showcase.mp4)

## Why build a chart engine at all?

The platform is a broker-neutral algo trading stack for Indian markets (I wrote about the backend in [nalgo: Building a Pure-Rust Algo Trading Platform](https://www.dhruvvakharwala.dev/blogs/nalgo-pure-rust-algo-trading-nautilustrader)). You connect your broker, the platform pulls live and historical data, and the screen you spend your day on is a chart. This post is only about that chart.

The first chart was **KLineChart 10.0.3** inside a React package in the web app. It is a good library and it got me far: candles, a pane for each indicator, drawing tools, price lines. In the git history that package starts on 2026-10-01 and by 2026-10-02 it already had indicators, drawings and full screen. By 2026-10-09 custom indicators from my own script language ran on it.

Then I wanted more speed than I could get from the outside. I want to be careful about what that sentence means. I never benchmarked KLineChart against anything, and nothing here says it is slow. The point was ownership: the speed work I could do sat around the library, not inside it. One concrete example from the web app: KLineChart asks for an indicator calculation on every tick and never drops a stale request, so I put my own worker in front of it that coalesces the calls (while one is in flight, only the newest waiting one runs). I wanted to own the whole chart, from the tick to the pixels, so I could keep optimizing it from my side, toward the feel I was after: a chart that stays smooth while hundreds of ticks a second arrive, with several charts on screen at once, on a phone. The Indian broker [Sahi](https://sahi.com/) was my reference point. Its site talks about "in-house Sahi charts" and has a heading "Trade from Charts, at Sahi Speed", and its charts feel fast to me. I do not know how they build theirs and I am not guessing here. I just wanted to get to that feeling.

There was a second reason, and it is a design reason rather than a speed one. I wrote the first Rust chart crate on 2026-11-15 and 16, for a cross-platform app stack that I dropped a few days later. On 2026-11-21 the plan became one **Flutter** code base for web, iOS and Android, and the question was whether to keep the Rust chart or write a new one in Dart. A JavaScript charting library does not run inside a Flutter canvas, and a Dart chart would mean two chart implementations to keep in agreement with each other and with the strategy engine. The indicator maths already lived in Rust. So the decision was: one Rust chart core, host it from Flutter.

That is the whole motivation. The rest is how it works.

---

## What do the open-source chart engines do, and where does this one differ?

I read the READMEs and docs of the engines people actually reach for. Everything in this table is from the project's own page; where a page did not say, I wrote that it did not.

| Project | Language | Renderer | License | Size, as stated | Real-time data |
|---|---|---|---|---|---|
| [KLineChart](https://github.com/klinecharts/KLineChart) | TypeScript | Canvas ("built with html5 canvas") | Apache-2.0 | "only 50k under gzip compression" | README does not cover it |
| [TradingView Lightweight Charts](https://github.com/tradingview/lightweight-charts) | JavaScript, TypeScript | HTML5 canvas | Apache-2.0 (attribution required) | "close to static images", no kB figure in the README | docs: call `update` to change the last item or add one, not `setData` |
| [uPlot](https://github.com/leeoniya/uPlot) | JavaScript | Canvas 2D | MIT | "~50 KB min" | "Data streaming (live update)" is a listed feature |
| [Apache ECharts](https://github.com/apache/echarts) | JavaScript | Canvas by default (zrender), SVG optional | Apache-2.0 | not in the README | handbook recommends canvas for more than 1k elements |
| [fl_chart](https://pub.dev/packages/fl_chart) (Flutter) | Dart | not stated on the page | MIT | not applicable | lists a `CandlestickChart` |

Three more context points. TradingView also sells a separate product, [Advanced Charts](https://www.tradingview.com/charting-library-docs/), with its own documentation. Syncfusion's Flutter charts need a Syncfusion commercial license or its free Community license, as its pub.dev page says, and I did not pick it. And when I surveyed Flutter packages on pub.dev in November 2026 (`candlesticks`, `kline_chart`, `fincharts`, `interactive_chart`, `k_chart`, `syncfusion_flutter_charts`), none of them had scriptable indicators, session bands, draggable order lines with exits, or saved drawings. Each would have been a fork.

uPlot's README is the most concrete about speed, and it is worth quoting what it measured, with its own caveats: a cold start of an interactive chart with 166,650 points in 25 ms, on a Ryzen 7 PRO 5850U with Chrome 113 in March 2023. That is a great number, for a different job (dense time series, not a live candle chart with indicators, drawings and trade lines).

### Where the design differs

These libraries have a shared shape, and it is the right shape for the browser. You hand the library data. It owns the layout, runs the maths in JavaScript on the main thread, and draws with the browser's Canvas 2D API. The renderer is built in.

`nalgo-chart` splits that apart:

- **The engine owns the maths and nothing else.** Bars, view, scales, indicators, drawings, trade lines, hit testing. It has no I/O and does not know what a screen is.
- **It draws through a small `Painter` trait.** Rectangles, paths, circles, text, clips (plus a text measure with a default). Something else decides what a rectangle becomes.
- **The "something else" is a host.** For Flutter, the host is a C ABI that turns every paint call into a flat buffer, plus a Dart `CustomPainter` that replays it with `drawVertices`.

```rust
pub trait Painter {
    fn fill_rect(&mut self, rect: Rect, color: Rgba);
    fn stroke_path(&mut self, points: &[Point], stroke: Stroke);
    fn fill_path(&mut self, points: &[Point], color: Rgba);
    fn fill_circle(&mut self, center: Point, radius: f64, color: Rgba);
    fn text(&mut self, text: &str, at: Point, style: TextStyle);
    fn clip(&mut self, rect: Rect);
    fn unclip(&mut self);
}
```

That trade is not free. The browser libraries come with a renderer that already works; mine needed a buffer format, a Dart painter, a WebAssembly build and golden tests. In exchange the same compiled core runs on a phone and on the web, and a test can record paint calls and assert on them. It is a different target, not a better library: those projects aim at the browser, and they are mature, documented and widely used. If you are building a web page, use them.

---

## What does the engine look like from the outside?

The chart is a pure Rust crate. A host feeds it values and reads back a frame.

```mermaid
flowchart LR
    subgraph RUST["Rust (compiled once)"]
      BARS["Bars + tick()"] --> VIEW["View + Scale"]
      IND["Indicators<br/>push_closed / eval_forming"] --> RENDER
      VIEW --> RENDER["render_with(Painter, Layer)"]
      DRAW["Drawings, trade lines"] --> RENDER
      RENDER --> FB["FrameBuffer<br/>words, vertices, colors, indices"]
    end
    FB -->|"C ABI: one bulk copy"| DART["Dart ChartController"]
    DART --> PAINT["CustomPainter<br/>drawVertices per batch"]
    PAINT --> GPU["Impeller (phones)<br/>skwasm (web)"]
```

The crate is about 17,000 lines of Rust across three crates (`chart`, `chart-ffi`, `chart-gpu`), tests included. The pieces:

| Piece | Job |
|---|---|
| `bars` | Loaded history plus the forming bar; a tick updates it or opens the next one |
| `view` | Which bars are on screen and how wide each is; pan and zoom |
| `scale` | Price to pixel, linear, log and percent; the tick labels |
| `indicators` | Scripts compiled from our own indicator language, run over the bars, then incrementally |
| `paint` | The `Painter` trait |
| `chart/*` | Layout, series, drawings, trade lines, alerts, replay, compare, volume profile |
| `chart-ffi` | The C ABI, the frame encoder, the triangle mesher, the host that keeps frame layers |

Everything the recording showed, from the EMA ribbon to bar replay, is in those modules. The recording starts with one chart taking 4 ticks a second, then adds indicators, pan and zoom, bar and area charts, a log scale, magnet snapping, a long-position tool, undo and redo, alert lines, bracket lines whose stop and target follow the entry, compare against BANKNIFTY, FINNIFTY and SENSEX, a volume profile, bar replay, and then the stress phases. The feed in the recording is synthetic.

![One frame end to end: Rust computes bars, scales, indicators and layers, chart-ffi encodes words, vertices, colors and indices, Dart copies once and replays with drawVertices, Flutter rasterises](https://www.dhruvvakharwala.dev/images/blog/rust-charting-engine-flutter-nalgo-chart/pipeline.png)

---

## How does a price become a pixel?

Everything starts with the vertical scale. A `Scale` is four numbers and a mode: the value at the top edge, the value at the bottom edge, where the pane starts, and its height in pixels.

```rust
/// Pixel row of a value.
pub fn y_of(&self, value: f64) -> f64 {
    self.y + (self.top - self.unit(value)) / (self.top - self.bottom) * self.height
}
```

That is the linear map

```text
y(v) = y0 + (top - u(v)) / (top - bottom) * h
```

where `u(v)` is the value in scale units: the price itself on linear and percent scales, the natural log of the price on a log scale. The inverse (`value_at`, for the crosshair) is the same line solved for `v`, then `exp` on a log scale.

### Fitting the scale to what is on screen

`Scale::fit` takes the lowest and highest value on screen and leaves a 10 percent margin above and below:

```rust
let mid = (hi + lo) / 2.0;
let half = span / 2.0 / (1.0 - 2.0 * FIT_MARGIN);
Self { top: mid + half, bottom: mid - half, .. }
```

So the fitted range is `span / 0.8`, which is 1.25 times the data range. A worked example with a price pane 500 px tall and visible bars between 24,480 and 24,520:

| Step | Value |
|---|---|
| span | 24,520 - 24,480 = 40 |
| mid | 24,500 |
| half | 40 / 2 / 0.8 = 25 |
| top, bottom | 24,525 and 24,475 |
| `y_of(24,512)` | (24,525 - 24,512) / 50 * 500 = **130 px** |

A flat range (one price) widens to 1 percent of the price, or 1 if that is larger, so a single value still sits in the middle of the pane.

### Linear, log and percent

The modes differ only in `u(v)` and in the labels. Take a pane 500 px tall showing 100 to 400 exactly:

| Mode | `y_of(200)` | Why |
|---|---|---|
| Linear | (400 - 200) / (400 - 100) * 500 = **333 px** | equal price steps, equal distances |
| Log | (ln 400 - ln 200) / (ln 400 - ln 100) * 500 = (0.693 / 1.386) * 500 = **250 px** | equal ratios, equal distances: 200 is the geometric middle of 100 and 400 |

A log scale falls back to linear when any value in range is zero or negative, because the log is undefined there. A percent scale is linear underneath, but labels each tick as the change from the first visible close:

```rust
(ScaleMode::Percent, Some(pct)) => { let p = pct(value); ... out.push('+'); ... out.push('%'); }
// percent_of: (v / base - 1.0) * 100.0
```

With a base of 24,500, a price of 24,512 labels as (24,512 / 24,500 - 1) * 100 = 0.049, which prints as `+0.05%` at two decimals.

### Nice tick steps

Axis labels should be round numbers at least 36 px apart (`LABEL_GAP_PX`). The engine asks for `floor(height / 36)` labels, takes the raw step that would give that many, and rounds it up to 1, 2 or 5 times a power of ten:

```rust
pub fn nice_step(raw: f64) -> f64 {
    let power = 10f64.powf(raw.log10().floor());
    let unit = raw / power;
    let nice = if unit <= 1.0 { 1.0 } else if unit <= 2.0 { 2.0 }
               else if unit <= 5.0 { 5.0 } else { 10.0 };
    nice * power
}
```

For the 500 px pane and the 24,475 to 24,525 range from before:

| Step | Value |
|---|---|
| wanted labels | floor(500 / 36) = 13 |
| raw step | 50 / 13 = 3.846 |
| power, unit | 10^floor(log10 3.846) = 1, unit 3.846 |
| nice step | unit is above 2 and at most 5, so **5** |
| first tick | ceil(24,475 / 5) * 5 = 24,475 |
| ticks | 24,475, 24,480, ... 24,525 (11 labels, 0 decimals) |

`decimals_of(step)` finds how many decimals show the step exactly, so a step of 0.5 prints one decimal and a step of 5 prints none.

### The rule that keeps the scale still while a bar forms

This is the part that makes the layered frames possible, so it is worth slowing down. If every new high of the forming bar refitted the scale, the scale would move on nearly every tick, and every closed bar would have to be redrawn on every tick. So `Scale::fit_live` fits only the **closed** bars. The forming bar's range is ignored while it stays inside the fitted pane (inside the 10 percent margin). Only when it breaks out does it move the scale, and then in steps:

```rust
let step = (c.1 - c.0).max(c.1.abs() * 0.001).max(f64::MIN_POSITIVE) * LIVE_STEP;
let hi = step_past(c.1, l.1, step);
let lo = -step_past(-c.0, -l.0, step);
Self::fit(lo, hi, y, height)
```

`LIVE_STEP` is 0.1 of the closed range. `step_past` returns the edge, or past it by `step` times the smallest power of two that holds the value:

```rust
let mut level = step;
for _ in 0..1100 {
    if edge + level >= value { return edge + level; }
    level *= 2.0;
}
```

Worked example. The closed bars span 24,480 to 24,520, so the fitted pane is 24,475 to 24,525. The step is max(40, 24,520 * 0.001) * 0.1 = 4.

| Forming bar high | Inside pane? | Levels tried (edge 24,520) | New top |
|---|---|---|---|
| 24,524 | yes | none | 24,525 (unchanged) |
| 24,530 | no | +4, +8, +16 (24,536 holds it) | `fit` of 24,480..24,536 gives **24,543** |
| 24,560 | no | +4, +8, +16, +32 (24,552 is short), +64 | `fit` of 24,480..24,584 |

The `fit` with the new range (24,480..24,536): span 56, mid 24,508, half 56 / 2 / 0.8 = 35, so top 24,543 and bottom 24,473. The levels double, so a bar that keeps growing moves the scale a number of times proportional to the log of how far it overshoots, not to the overshoot itself. That doubling was a later fix: with linear steps, a 1-minute volume bar at the open (several times the visible maximum) caused 11 base redraws a second per chart on a test feed.

### Bar space, home position and zoom about a point

Horizontally, a `View` is two numbers: `bar_space` (pixels per bar, between 1 and 50) and `gap` (empty bars between the newest bar and the right edge). The x of a bar index is

```text
x(i) = W - (gap + (newest - i) + 0.5) * bar_space
```

```rust
pub fn x_of(&self, index: f64, count: usize, width: f64) -> f64 {
    let newest = count as f64 - 1.0;
    width - (self.gap + (newest - index) + 0.5) * self.bar_space
}
```

The reset view sizes bars to fit: `bar_space = clamp((W - 80) / count, 6, 14)` and `gap = 80 / bar_space`, so the newest bar rests 80 px from the right edge. For a plot 1,536 px wide (a 1600 px chart minus the 64 px price axis) and 2,000 bars: (1536 - 80) / 2000 = 0.728, clamped up to **6**. The gap is 80 / 6 = 13.33 bars, and the newest bar's center is at 1536 - (13.33 + 0.5) * 6 = 1,453 px. The visible range is the bar indices under x = 0 and x = W: here 244 bars (`newest - 243` to `newest`).

Zoom about a point keeps the bar under the cursor in place. It reads the fractional index under the anchor, rescales `bar_space`, and solves for the `gap` that puts the same index back under the anchor:

```rust
let index = self.index_at(anchor_x, count, width);
self.bar_space = (self.bar_space * factor).clamp(MIN_BAR_SPACE, MAX_BAR_SPACE);
self.gap = (width - anchor_x) / self.bar_space - (newest - index) - 0.5;
```

Worked example: 2,000 bars, `bar_space` 6, anchor x = 768 (the middle of 1,536), zoom factor 2:

| Step | Value |
|---|---|
| index under anchor | 1,999 - ((1536 - 768) / 6 - 13.333 - 0.5) = 1,999 - 114.167 = **1,884.833** |
| new `bar_space` | 12 |
| new gap | (1536 - 768) / 12 - (1,999 - 1,884.833) - 0.5 = 64 - 114.167 - 0.5 = **-50.667** |
| check: index under anchor again | 1,999 - (64 + 50.667 - 0.5) = 1,884.833 |

The gap goes negative: the view is now panned back into history, which is exactly right. A unit test asserts this property to 1e-9. Panning is `gap -= dx / bar_space`, and `bound` keeps at least two bars on screen at either end.

The candle body is about 70 percent of the bar space, forced odd so the wick sits in its middle: `floor(0.7 * 6) = 4`, even, so 3 px.

---

## How does a tick reach the screen?

A tick is a trade price from the stream. In `Bars::tick` it either updates the forming bar (high, low, close, volume) or opens the next one. The effect is one of three values, and the effect decides how much has to be redrawn:

```mermaid
stateDiagram-v2
    [*] --> Forming: load history, last bar forming
    Forming --> Forming: Updated (price stays in the bar's period)
    Forming --> Forming: Opened (period ended, new bar starts)
    Forming --> Forming: Ignored (older tick, or not a price)
    note right of Forming
      Updated bumps revision only
      Opened bumps revision and base revision,
      moves the view if it is not at home,
      pushes the closed bar to every indicator
    end note
```

The bucket of a new bar is computed from the session open, so intraday bars line up with the exchange open and gaps keep the bar grid:

```rust
origin + (at_ms - origin).div_euclid(self.period_ms) * self.period_ms
```

### Indicators: update, do not recompute

Indicators are scripts in our own indicator language. They compile once through the strategy compiler and run in a `ChartRunner`. The first run goes over every loaded bar. After that the chart never reruns history. It catches up:

```rust
pub fn sync(&mut self, bars: &Bars) {
    while self.pushed < bars.closed() {
        self.rows.truncate(self.pushed * self.width);
        ...
        self.runner.push_closed(&bar, &mut self.rows);
        self.pushed += 1;
    }
    self.rows.truncate(self.pushed * self.width);
    if bars.len() > self.pushed && let Some(bar) = bars.last().and_then(chart_bar) {
        self.runner.eval_forming(&bar, &mut self.rows);
    }
}
```

A bar that closes is pushed once (`push_closed`), which commits it into the runner's state. The forming bar is evaluated on a copy of that state (`eval_forming`), so the next tick starts from the same committed state instead of stacking on the previous guess. The textbook case is an exponential moving average, where one step from the committed value is a multiply-add:

```text
ema_t = ema_(t-1) + k * (price - ema_(t-1)),   k = 2 / (n + 1)
```

For a 20-bar EMA, k = 2/21 = 0.0952. If the last closed EMA is 24,500.00 and the forming bar's price is 24,512, the forming value is 24,500 + 0.0952 * 12 = 24,501.14. The old bars are not touched. The chart core's test after 200 live ticks found the rows equal to a full rerun bit for bit for the EMA ribbon, RSI and VWAP, and a tick through both indicators measured 1.6 us natively on a 2,000-bar chart (release build, 2026-11-16).

### The tick path in order

```mermaid
sequenceDiagram
    participant S as Market stream
    participant C as ChartController (Dart)
    participant E as chart-ffi (Rust)
    participant V as Flutter vsync
    participant P as CustomPainter
    S->>C: tick(time, price, volume)
    C->>E: nalgo_chart_tick (leaf FFI call)
    E-->>C: flags (redraw?)
    C->>C: invalidate(): first call in a frame schedules one callback, the rest return
    S->>C: tick, tick, tick ... (same frame)
    V->>C: frame callback
    C->>E: render_layers (base only if its key changed)
    E-->>C: buffers, one bulk copy
    C->>P: notifyListeners (repaint, no widget rebuild)
    P->>P: drawVertices per batch
```

Two details in the Dart controller carry most of the speed story, and both are short:

```dart
/// Asks for a render before the next frame; many calls in one frame render once.
void invalidate() {
  if (_scheduled || _disposed) {
    return;
  }
  _scheduled = true;
  SchedulerBinding.instance
    ..scheduleFrameCallback((_) => _render())
    ..ensureVisualUpdate();
}
```

The first tick in a frame asks Flutter for a frame; the next hundred in the same frame see `_scheduled` and return. And the painter is attached to the controller as a `Listenable`:

```dart
CustomPaint(painter: _painter ??= _makePainter(), size: box.biggest)
// painter built with repaint: c
```

`CustomPainter(repaint: controller)` repaints when the controller notifies, without rebuilding any widget. That is the last line of the recording's summary: "no widget rebuilds on a tick".

---

## How does a candle become triangles?

The engine's `Painter` output goes into a `FrameBuffer`. In mesh mode, rectangles and thin solid lines (up to 1.5 px wide) become **indexed quads**: four vertices and six 16-bit indices.

```rust
fn quad(&mut self, q: [f64; 8], color: u32) {
    if self.colors.len() - self.run + 4 > RUN_VERTICES { self.flush_run(); }
    let first = u16::try_from(self.colors.len() - self.run).unwrap_or(u16::MAX - 3);
    self.vertices.extend(q.map(|v| v as f32));
    self.colors.extend_from_slice(&[color; 4]);
    self.indices.extend_from_slice(&[first, first + 1, first + 2, first, first + 2, first + 3]);
}
```

A thin line is a quad too: for each segment it computes the unit normal and offsets by half the width.

```text
len = sqrt(dx*dx + dy*dy)
n   = (-dy * (w/2) / len,  dx * (w/2) / len)
```

The four corners are `a + n`, `b + n`, `b - n` and `a - n`. A run closes at 65,536 vertices so every index fits in 16 bits. Everything that is not a thin solid shape (dashed lines, wide strokes, fills, circles, text, clips) stays as an op in the same buffer, in paint order.

A candle is a wick (a 1 px stroke, so one quad) and a body (a rectangle, one quad). That is 2 quads, 8 vertices, 12 indices and 4 triangles. The volume bar under it is one more quad.

![A candle as two quads with vertices numbered, and the counts for a 1600 by 900 chart: 244 visible bars, 732 quads, 2,928 vertices, 4,392 indices](https://www.dhruvvakharwala.dev/images/blog/rust-charting-engine-flutter-nalgo-chart/geometry.png)

The memory per quad: four vertices of `x` (f32), `y` (f32) and a `u32` color are 4 * 12 = 48 B, six `u16` indices are 12 B, so **60 B and 2 triangles** per quad. A worked frame, 1600 x 900, 2,000 bars, no indicators, volume on:

| Quantity | Value |
|---|---|
| bar space | 6 px, so 244 bars visible |
| quads | 244 * (2 candle + 1 volume) = 732 |
| vertices | 732 * 4 = **2,928** |
| indices | 732 * 6 = **4,392** (1,464 triangles) |
| engine benchmark, whole frame | about 3,100 vertices and 4,600 indices (the rest is grid and axis lines) |

Why quads with indices rather than six vertices each? An earlier version used six vertices per quad, and the copy out of WebAssembly memory grew with the vertex bytes: 330 to 590 us per full frame on the web. Four vertices plus six indices are 60 B against 72 B, about a sixth fewer bytes.

At a bar space under 3 px the engine skips bodies and draws only wicks (`thin`), because a body narrower than the wick adds nothing.

### The paint op encoding

Everything else is encoded as 32-bit words: an opcode, then fields, floats as `f32` bits, colors as one `u32`.

| Op | Fields | Words | Bytes |
|---|---|---|---|
| 0 Rect | x y w h color | 6 | 24 |
| 1 Stroke | color width dash n, then n points of x y | 5 + 2n | 20 + 8n |
| 2 Fill | color n, then n points | 3 + 2n | 12 + 8n |
| 3 Circle | x y radius color | 5 | 20 |
| 4 Text | x y color size align baseline offset length | 9 | 36 |
| 5 Clip | x y w h | 5 | 20 |
| 6 Unclip | none | 1 | 4 |
| 7 Vertices | first count index_first index_count | 5 | 20 |

(Counts include the opcode word.) Text bytes go to a side buffer that the Text op points into. Dart mirrors these opcode numbers, and a test pins every layout.

### Bytes per frame at 5,000 ticks/s

The live metrics panel in the recording, at the 5,000 ticks/s phase, reads `frame: ops / triangles 6.4 KB / 2816` for one chart with an EMA ribbon, MACD and RSI.

![A frame of the recording at 5,000 ticks/s with the live metrics panel: 29.2 frames drawn per second, render + copy 412 us, 6.4 KB of ops and 2816 triangles, 5030 ticks/s fed, cost per tick 6.1 us, Dart paint 0.84 ms, raster 33.40 ms](https://www.dhruvvakharwala.dev/images/blog/rust-charting-engine-flutter-nalgo-chart/live-metrics-frame.jpg)

Taking the panel's triangle count as indices divided by 3, with every triangle coming from a quad, the mesh is 2,816 / 2 = 1,408 quads:

| Part | Calculation | Bytes |
|---|---|---|
| ops (as shown) | | 6.4 KB |
| vertices and colors | 1,408 * 4 * 12 | 67,584 |
| indices | 1,408 * 6 * 2 | 16,896 |
| mesh total | | 84,480 (82.5 KiB) |

If those 1,408 quads had stayed rectangle ops they would be 1,408 * 24 = 33,792 B, so the mesh is bigger in bytes. What it buys is call count: the Dart side issues a handful of `drawVertices` calls over views of the buffers instead of replaying about 1,400 rectangle calls through `Canvas`. Earlier measurements of the same engine (with the EMA ribbon and RSI) put a frame at 606 draw calls for an 800 x 500 chart and 1,302 for 1600 x 900, and painting those calls, not the Rust, was the real per-frame cost.

---

## How do layers make a tick cheap?

After the ops are cheap, the next win is not drawing most of the chart. A chart has a part that moves only when the view or a closed bar changes (the grid, closed candles, closed indicator values, axis labels) and a part that moves on every tick (the forming candle, the last price line). The engine splits a frame into **five layers**:

| Layer | Draws | Redrawn when |
|---|---|---|
| Base | background, grid, bands, closed bars, indicator values up to the last closed bar, levels, axis labels | the base key changes |
| Live | the forming bar and its volume, the newest indicator segments | every frame |
| Overlay | drawings | with the base |
| Top | last price line, alert lines, trade lines, axis tags | every frame |
| Pointer | crosshair and legend | every frame |

The stack order is the same as a full frame (base, live, overlay, top, pointer), so the forming candle sits under your drawings and the price lines sit over them.

The host decides whether the base needs rebuilding with a hash, `base_key`:

```rust
pub fn base_key(&self, frame: &Frame) -> u64 {
    let mut h = std::hash::DefaultHasher::new();
    self.base_revision.hash(&mut h);
    for s in std::iter::once(&frame.price).chain(&frame.panes) {
        for v in [s.top, s.bottom, s.y, s.height, s.base] { v.to_bits().hash(&mut h); }
        s.mode.hash(&mut h);
    }
    frame.visible.hash(&mut h);
    ...
    self.theme.hash(&mut h);
    self.settings.hash(&mut h);
    h.finish()
}
```

It hashes a revision counter (bumped by everything except hovers and ticks that only move the forming bar), the fitted scales, the visible range, the volume scale, the theme and the settings. A test ticks 600 times and checks that an equal key always means an identical base.

```mermaid
flowchart TD
    T["tick()"] --> E{"TickEffect"}
    E -->|Updated| R1["revision + 1<br/>base revision unchanged"]
    E -->|Opened| R2["revision + 1<br/>base revision + 1<br/>view.on_bar_added()"]
    R1 --> RL["render_layers()"]
    R2 --> RL
    RL --> K{"base_key equals kept key?"}
    K -->|yes| L["clear live buffer<br/>draw Live, Top, Pointer"]
    K -->|no| B["clear base buffer<br/>draw Base + Overlay<br/>store the new key"]
    B --> L
    L --> D["Dart: base kept as a GPU image,<br/>live layers replayed"]
```

```rust
pub fn render_layers(&mut self) -> bool {
    let frame = self.chart.frame();
    let key = self.chart.base_key(&frame);
    let fresh = self.base_key != Some(key);
    if fresh {
        self.base.clear();
        self.chart.render_with(&mut self.base, &frame, Layer::Base);
        self.base_split = self.base.mark().words();
        self.chart.render_with(&mut self.base, &frame, Layer::Overlay);
        self.base.finish();
        self.base_key = Some(key);
    }
    self.live.clear();
    self.chart.render_with(&mut self.live, &frame, Layer::Live);
    ...
}
```

The result in the benchmark harness, measured when the engine had three layers (base, live, pointer; overlay and top were split out on 2026-11-24) (2,000 bars, median of 3,000 frames after 300 warm-up frames, 4 vCPU cloud box, the "full frame" being one tick in the forming bar, one pointer move and a whole render, as the Flutter host does at each vsync):

| Case | Before | After |
|---|---|---|
| Full frame, 800 x 500, plain | 10.0 us | 5.4 us |
| Full frame, 800 x 500, ribbon + RSI | 46.2 us | 20.7 us |
| Full frame, 1600 x 900, ribbon + RSI | 67.5 us | 39.5 us |
| Crosshair move only, 1600 x 900, ribbon + RSI | 7.54 us | 0.07 us |
| Hover frame through the host (body kept), ribbon + RSI | 67.5 us | 1.2 us |
| Tick frame, layered, 800 x 500, plain | 10.0 us | 1.3 us |
| Tick frame, layered, 1600 x 900, ribbon + RSI | 67.5 us | 11.3 us |
| Base redrawn while ticking 4 per second | every frame | 14 of 3,300 frames |
| Instructions per full frame (callgrind), 1600 x 900, ribbon + RSI | 973 k | 581 k |

Most of the "before" to "after" on full frames came from profiling, not from clever architecture. In callgrind, 26 percent of a frame was parsing a fixed plot color string at every bar, 16 percent was decoding colors the scale fit never used, and 8 percent was `format!` for axis labels. The fixes were boring: parse colors once at compile, read value cells straight from the rows, write price digits as integers. The layering is what turns a 67.5 us hover into 1.2 us.

From Dart, the same split measured on web skwasm: Dart paint 5.0 ms down to 1.1 ms per frame and 20 up to 46 to 51 frames per second, in an experiment done before the final numbers in this post.

---

## What do the video's numbers say, honestly?

The final frame of the recording is a summary card. Here it is, transcribed:

| phase | fps | Rust render | Dart paint | ticks/s | cost/tick |
|---|---|---|---|---|---|
| 1 chart, plain, 4 ticks/s | 48 | 207 us | 1.48 ms | 4 | 36.4 us |
| 1 chart + 3 indicators, 4 ticks/s | 32 | 281 us | 1.29 ms | 4 | 118.9 us |
| 1 chart + indicators, 30 ticks/s | 31 | 342 us | 1.20 ms | 11 | 97.0 us |
| 1 chart + indicators, 100 ticks/s | 30 | 355 us | 1.16 ms | 94 | 108.5 us |
| 1 chart + indicators, 1,000 ticks/s | 31 | 358 us | 1.14 ms | 970 | 17.3 us |
| 1 chart + indicators, 5,000 ticks/s | 29 | 381 us | 1.22 ms | 4779 | 7.5 us |
| 4 charts, 20 ticks/s each | 23 | 171 us | 1.14 ms | 158 | 93.3 us |
| 9 charts, 20 ticks/s each | 21 | 109 us | 0.84 ms | 180 | 50.6 us |
| 9 charts, 200 ticks/s each | 19 | 94 us | 0.69 ms | 1741 | 10.9 us |

The card's own header reads "Measured in this recording (no GPU, software raster, recorder running)", and the footer of every frame says: Flutter 3.50 web, dart2wasm and skwasm, Rust nalgo-chart compiled to wasm at opt-level 3, cloud box with 4 vCPUs, no GPU (software GL), screen recording running.

```mermaid
xychart-beta
    title "Measured cost per tick (us), one chart with indicators"
    x-axis ["100 ticks/s (94 measured)", "1,000 (970)", "5,000 (4779)"]
    y-axis "us per tick" 0 --> 120
    bar [108.5, 17.3, 7.5]
```

![Horizontal bars of cost per tick for all nine phases of the recording, from 7.5 us to 118.9 us](https://www.dhruvvakharwala.dev/images/blog/rust-charting-engine-flutter-nalgo-chart/cost-per-tick.png)

### Reading it without fooling myself

**The fps is not a Rust number.** On this box nothing runs on a GPU, so Skia rasterises in software, and a screen recorder is competing for the same 4 vCPUs. The panel at the 5,000 ticks/s phase makes this visible: `build / raster per frame 7.59 / 33.40 ms`. A raster time of 33.4 ms is a ceiling of 1 / 0.0334 = 29.9 frames a second, and the panel read 29.2 frames drawn per second. Rust is 381 us of that, Dart paint 1.22 ms: together about 1.6 ms, next to 7.59 ms of Flutter build and 33.4 ms of raster per frame. So "29 fps" says the software rasteriser is slow, not that the engine is. On a phone with Impeller on a real GPU this raster time is a different number, which I have not measured yet.

**What "Rust render" is.** The panel calls it "render + copy to Dart": the Rust frame plus the bulk copy of the buffers out of WebAssembly memory. It is per chart, per render. It falls from 381 us for one chart to 94 us per chart in a grid of 9, plausibly because each chart in the grid is smaller (I did not isolate the cause).

**What cost per tick is.** The panel times 2,000 tick runs and averages them:

```text
cost per tick (us) = total time for 2,000 runs (ms) / 2,000 * 1,000
```

Worked through: the 7.5 us row means the 2,000 runs took 7.5 * 2,000 / 1,000 = 15 ms in total, and the 108.5 us row means they took 217 ms. The label says what a run includes: "cost per tick (incl. frame request)", so it is the tick plus asking Flutter for a frame, not the engine's tick alone. Natively that engine tick is 0.06 us, under 1 percent of 7.5 us, so nearly all of the measured cost is what sits around it in the browser: the call from Dart into WebAssembly and the frame request.

**Why cost per tick falls.** This is the most interesting column. Three facts from the source and the card:

1. A render happens at most once per screen frame, however many ticks arrive (the `invalidate` coalescing above). The card says it in words: "at most one render per screen frame however many ticks arrive".
2. Rust render time is flat in the tick rate: 342 to 381 us from 30 to 5,000 ticks/s.
3. The panel's label for the last column is "cost per tick (incl. frame request)".

Because the frame request coalesces, only the first tick after a frame actually schedules one; `invalidate()` returns at once for the ticks behind it while a frame is already scheduled. At 100 ticks/s only about 3 ticks share a frame (94 ticks/s over 30 drawn frames/s), so a large share of the 2,000 runs pay for a real frame request. At 5,000 ticks/s about 165 ticks share each frame (4,779 ticks/s over 29 drawn frames/s is 164.8 ticks per frame), so almost every run is the cheap kind and the average falls. In time per second, 7.5 us * 4,779 ticks/s = 35.8 ms, or 3.6 percent of one core, to ingest nearly five thousand ticks a second. From 100 to 5,000 ticks/s the cost per tick drops 108.5 / 7.5 = 14.5 times while the Rust render stays near 355 to 381 us.

The low-rate rows do not fall in a straight line (118.9 us at 4 ticks/s is higher than 97.0 us at 11 and 108.5 us at 94), so I treat the shape, a sharp fall once many ticks share a frame, as the claim, not a model that predicts every digit.

**The tweet.** The tweet quotes three of these numbers (7.5 us per tick at 5,000 ticks/s, 94 us per chart in the 9-chart grid, 12 us per native frame). They are the same ones as above, and "94 us render per chart" is the `Rust render` column of the last row, not an end-to-end frame time.

### The native numbers

The last line of the card reads: "Same Rust engine, native, one CPU core (cargo bench, 50,000 bars, 1600x900): tick 0.06 us, full frame 12 us plain, 45 us with EMA ribbon + RSI; a tick-only frame (live layer) 2 to 13 us."

These come from the benchmark harness in `chart-ffi` (`frame_bench`), which has a 50,000-bar 1600 x 900 case that measures a tick in the forming bar, a crosshair move, a render into the frame buffer, and the full frame (tick, pointer move, render), with and without the EMA ribbon and RSI. The card's numbers are from a `frame_bench` run I made for the recording. They agree with the earlier 2,000-bar runs: 20.7 to 39.5 us for the ribbon-and-RSI full frame at 800 x 500 and 1600 x 900, 11.3 us for a layered tick frame at 1600 x 900, and 1.3 us at 800 x 500 plain.

That a 50,000-bar chart costs about the same as a 2,000-bar chart (45 us against 39.5 us) is not a coincidence. A frame draws only the **visible** bars, 244 in the worked example, and `View::visible` clamps to the pane. The history behind them costs memory, not time. Likewise a tick costs 0.06 us regardless of history because indicators update incrementally. For scale: at 60 Hz a frame has 16,667 us, so a 12 us frame is 0.07 percent of it and a 45 us frame is 0.27 percent.

---

## How do the C ABI and WebAssembly work?

The only crate with `unsafe` is `chart-ffi`, and every exported function goes through one wrapper that checks the handle for null and catches panics, so a bad call answers zero instead of tearing down the app:

```rust
pub(crate) fn with<T>(handle: *mut ChartHost, fallback: T,
                      f: impl FnOnce(&mut ChartHost) -> T) -> T {
    if handle.is_null() { return fallback; }
    // SAFETY: a non-null handle comes from `nalgo_chart_new` and lives until `nalgo_chart_free`
    let host = unsafe { &mut *handle };
    catch_unwind(AssertUnwindSafe(|| f(host))).unwrap_or(fallback)
}
```

The hot path is one buffer per frame, so the ABI is narrow and hand-written: `abi.rs` has 54 exported functions, with more for the surface and scene frames. I chose a hand-written ABI over `flutter_rust_bridge` because a general bridge adds a code generator and I only need to move a few buffers per frame.

On native (iOS, Android), Dart binds the symbols with `@Native(..., isLeaf: true)` and reads the buffers through pointers. A leaf call is one that cannot call back into Dart, which makes it cheap, and the chart hot path uses them:

```dart
@Native<Uint32 Function(Pointer<_Host>)>(symbol: 'nalgo_chart_render', isLeaf: true)
```

On the web, the same exports are compiled to WebAssembly (the chart module is a separate build profile with `opt-level = 3`, about 1.8 times faster than the size-optimised one on frames in Node, at a cost of about 20 KB of gzip), loaded with `WebAssembly.instantiateStreaming`, and called through `dart:js_interop`. One finding mattered for speed: copy the buffer into Dart memory once per frame instead of reading through a view over the Rust memory, because per-element reads across the JS boundary cost about 20 percent more. WebAssembly memory can grow on any call, which detaches old buffers, so the Dart side reads the memory buffer fresh each time.

How much does the bridge itself cost? In the early measurements, through `dart:ffi` the bridge added about 8 to 15 us per frame natively. At 120 Hz a frame has 8.3 ms, and the whole chart computation measured 1 to 2 percent of it natively and 2 to 4 percent on the web, on a slow server core.

---

## What about drawing from Flutter?

On the Dart side the work is replaying buffers. The painter walks the ops, and for each Vertices op (7) it builds a `ui.Vertices` over views of the shared buffers and draws it in one call:

```dart
final vertices = ui.Vertices.raw(
  ui.VertexMode.triangles,
  Float32List.sublistView(f.vertices, first * 2, end * 2),
  colors: Int32List.sublistView(f.colors, first, end),
  indices: Uint16List.sublistView(f.indices, indexFirst, indexEnd),
);
canvas.drawVertices(vertices, BlendMode.dst, Paint());
```

The other ops (dashed lines, fills, text, clips) replay one by one, with text laid out once and cached as paragraphs, because text layout is the expensive part and chart labels repeat. The frame copies go into grow-only Dart buffers so nothing allocates on a tick.

A layered painter then keeps the base as a recorded picture, and as a **GPU image** once it holds still for a frame; a pan or zoom changes the base key every frame, so during a pan it draws from the picture and does not pay for an offscreen pass. The image is device-pixel-ratio times the logical size, drawn without filtering, so it is as sharp as a direct draw. What gets replayed on a tick is small: the live layer is about 100 to 200 words.

---

## What was built when?

I try not to say more than git says. These are commit times in UTC.

```mermaid
timeline
    title From KLineChart to a Rust engine in Flutter
    2026-10-01 to 10-09 : Web chart package on KLineChart 10.0.3 : indicators, drawings, then custom indicators from our script language
    2026-11-15 : First Rust chart crate commits : bars, view, scale, trading, indicators, drawings, rendering
    2026-11-21 : C ABI export and the Flutter host, five minutes apart (10:22 and 10:27 UTC)
    2026-11-22 : Layered frames, live scale steps, the triangle frame : then log and percent scales, chart types, magnet, panes, position tools, compare, volume profile, replay, undo, alert lines
    2026-11-23 : Whole engine surface bound in Dart : indicators, lines, events
    2026-11-24 : GPU layers and scenes, then the tweet at 11:26 UTC
```

The tweet calls it a "Weekend project". The dates above are what the repository shows: the first Rust chart commits are on 2026-11-15, the C ABI and Flutter host are on 2026-11-21, and the speed work and almost every feature in the recording are on 2026-11-22. Most of the crate's logic was ported from the web package I already had, such as the fitted bar space and the session band placement, whose test cases I carried over.

I posted the recording:

[Post on X](https://x.com/i/status/2125189268876452327)

Sahi's official account liked it, and a lot of other people did too.

---

## What about the GPU?

Everything above ran with no GPU at all, and Flutter still draws the triangles on the GPU on real devices (Impeller on Metal and Vulkan, skwasm on WebGL2 on the web). The next question was how much of the remaining Dart work could move into Rust too. That is the `chart-gpu` crate, written on 2026-11-24 and merged the same day, and it is the next step, not part of the numbers in this post.

What it does, from its plan:

- A second painter turns every paint call into a `Scene`: vertices with position, atlas texel and color, `u32` indices, and batches per clip rectangle.
- Strokes and dashes are tessellated (one quad per segment, round joins past 1.5 px), fills go through `lyon_tessellation`.
- Text becomes glyph quads over one **glyph atlas** rasterised in Rust at device resolution from an embedded Geist Mono, so there is no text layout in Dart at all.
- Flutter draws each batch with one `drawVertices` over an `ImageShader` of the atlas. A wgpu backend (Metal, Vulkan, GLES) exists behind a feature, mainly for tests and for a possible native surface.

What the plan measured, on a test bed with headless Chromium, skwasm, software GL, indicators, drawings and trade lines at 40 ticks/s: scenes ran at 60 fps with a 1.1 ms build and 13.4 ms raster, layers at 58 fps (3.6 ms, 14.9 ms), and a single frame at 29 fps (9.0 ms, 34.2 ms). In Rust, a full 1200 x 700 scene at 2x builds in 0.3 ms and a tick's scenes in 0.01 ms.

What it does **not** have is a device measurement. Frame times on an iPhone and an Android phone are not measured yet, so I am not claiming a GPU result. The native wgpu surface for iOS and Android is a plan with no code, and it will be built only if device numbers say the scene painter misses the frame budget. The glyph atlas covers printable ASCII only, and the chart module grows from 421 KB to 498 KB gzip with the tessellator and font.

---

## What is not done, and what I would check first

- **No head-to-head.** I have no benchmark of this engine against KLineChart on the same data and the same machine. I built this to own the whole chart and keep optimizing it from my side, not because of a measured gap, and I would not turn the result into a ratio.
- **No device numbers yet.** The recording is a software-raster cloud box. The target I set is 99 percent of frames under 8.3 ms on a 120 Hz phone while ticking and panning, and under 16.6 ms on a 60 Hz mid-range Android. I have not run that.
- **The feed is synthetic.** The recording ticks dummy prices; real broker feeds have bursts and gaps.

---

## FAQ

### What is nalgo-chart?

It is my charting engine written in Rust. It owns the bars, scales, indicators, drawings and layout, draws through a small `Painter` trait, and gives a host a flat buffer of ready-made triangles, so Flutter on iOS, Android and the web draws the same chart from one compiled core.

### How does a Rust chart engine run in Flutter?

On iOS and Android Dart calls it through `dart:ffi` over a C ABI with leaf calls, and on the web the same exports are compiled to WebAssembly. Each render, Dart copies the frame buffer once and replays it with `drawVertices`, and a `CustomPainter` that listens to the controller repaints without rebuilding any widget.

### How fast is it, and what did you measure?

In the recording, on a 4 vCPU cloud box with no GPU and a screen recorder running, one chart at 5,000 ticks/s cost 7.5 us per tick, and 9 charts at 200 ticks/s each rendered in 94 us per chart. Natively on one core, a 50,000-bar 1600 x 900 frame took 12 us plain and 45 us with an EMA ribbon and RSI. The frame rate in the recording (19 to 48 fps) is limited by software rasterisation, not by Rust.

### Is it faster than KLineChart, Lightweight Charts or uPlot?

I do not know, because I never ran a head-to-head. Those libraries target the browser with Canvas and are mature; this engine targets a Flutter host and shares one Rust core across native and web, so the two are not the same job.

### Why does the cost per tick fall as the tick rate rises?

Cost per tick is the total time of 2,000 tick runs divided by 2,000, and each run includes the frame request. A frame is requested at most once per screen frame however many ticks arrive, so at 5,000 ticks/s about 165 ticks share each frame and almost every run skips the expensive part. The cost per tick went from 108.5 us at 100 ticks/s to 7.5 us at 5,000 ticks/s while the Rust render stayed near 355 to 381 us.

**Takeaway:** The speed of a chart is mostly decided by what you do not redraw. `nalgo-chart` keeps the maths in compiled Rust, keeps the scale still while a bar forms (so a hash of the scales and view can prove the base is unchanged), batches the whole frame into a few indexed triangle lists, renders at most once per screen frame, and repaints through a `Listenable` so a tick never rebuilds a widget. In my recording that is 7.5 us per tick at 5,000 ticks/s with no GPU, and 12 us for a native 50,000-bar frame. What I have not measured is a real phone, and I never compared it with KLineChart, so those are the two things to check before you believe more than this post says.


## References

- [KLineChart](https://github.com/klinecharts/KLineChart) README: canvas, Apache-2.0, "only 50k under gzip compression"
- [TradingView Lightweight Charts](https://github.com/tradingview/lightweight-charts) README and [docs](https://tradingview.github.io/lightweight-charts/docs): HTML5 canvas, Apache-2.0, `update` for real-time data
- [uPlot](https://github.com/leeoniya/uPlot) README: Canvas 2D, MIT, "~50 KB min", the 166,650 point benchmark
- [Apache ECharts](https://github.com/apache/echarts) README and the [Canvas vs SVG handbook page](https://echarts.apache.org/handbook/en/best-practices/canvas-vs-svg/)
- [fl_chart on pub.dev](https://pub.dev/packages/fl_chart) and TradingView's [Advanced Charts documentation](https://www.tradingview.com/charting-library-docs/)
- [Sahi](https://sahi.com/): the broker whose charts inspired this
- [The tweet](https://x.com/thedev_dv/status/2125189268876452327) with the numbers
- Related: [nalgo: Building a Pure-Rust Algo Trading Platform for Indian Markets on NautilusTrader](https://www.dhruvvakharwala.dev/blogs/nalgo-pure-rust-algo-trading-nautilustrader)