Chart trading

Open-source charting engine

Chart trading

Trade from the chart, as a paper simulation. Select a long or short position, set the amount at risk and the quantity follows from the distance to the stop; Place order hands the page an intent with side, entry, target, stop and quantity. The placed position then has price lines, and dragging TP or SL asks the page first: a refused change puts the line back. The engine connects to no exchange and sends nothing.

Apache-2.0

Chart trading: Execution & trade review example

createTradeTicket · createTradingLines · priceLineDrag · drawings.add('long_position')

Code
import { FerroChart } from '@ferrochart/core';
import { createTradeTicket, createTradingLines } from '@ferrochart/core/trading';

const canvas = document.querySelector('canvas');
// Market data: the synthetic FerroChart demo API. Use your own feed.
const chart = await FerroChart.create(canvas, { theme: 'dark' });
const bars = await fetch('/api/bars?symbol=BTCUSD&interval=15m&count=600').then((r) => r.json());
const candles = chart.addCandlestickSeries();
candles.setData(bars);
const n = bars.time.length, entry = bars.close[n - 1];
// Paper trading: the order "fills" in this page and goes nowhere else. A real
// page sends the intent to its own server here.
const ui = (tag, css, parent = canvas.parentElement) => {
  const e = document.createElement(tag);
  e.style.cssText = css;
  parent.append(e);
  return e;
};
const BTN = 'font:600 12px system-ui;color:#fff;border:0;border-radius:5px;padding:7px 14px;cursor:pointer;white-space:nowrap;pointer-events:auto';
const bar = ui('div', 'position:absolute;left:12px;top:10px;right:84px;display:flex;flex-wrap:wrap;gap:8px;align-items:center;z-index:2;pointer-events:none');
const buy = ui('button', BTN + ';background:#26a69a', bar);
const sell = ui('button', BTN + ';background:#ef5350', bar);
buy.textContent = 'Buy / Long';
sell.textContent = 'Sell / Short';
const note = ui('span', 'font:500 12px system-ui;color:#8b93a7;margin-left:4px', bar);
const say = (text) => { note.textContent = `Paper trading · ${text}`; };

// The panel of the filled position, with a Close button.
const panel = ui('div', 'margin-left:auto;display:none;gap:10px;align-items:center;white-space:nowrap;' +
  'padding:4px 5px 4px 12px;border-radius:8px;background:rgba(30,34,45,.96);border:1px solid #363a45;' +
  'font:12px system-ui;color:#d1d4dc;font-variant-numeric:tabular-nums', bar);
const info = ui('span', '', panel);
const close = ui('button', BTN + ';background:#363a45;padding:5px 10px', panel);
close.textContent = 'Close position';

// Wide: controls over the chart, with room below the bars for the ticket.
// Narrow (phones): the chart leaves a strip above it for the buttons and one
// below it, where the ticket docks and the position panel goes.
const host = canvas.parentElement, css = canvas.style.cssText;
let narrow = null;
function layout() {
  const now = host.clientWidth < 480;
  if (now === narrow) return;
  narrow = now;
  canvas.style.cssText = css + (now ? ';margin-top:76px;height:calc(100% - 172px)' : '');
  const first = n - (now ? 30 : 110);
  chart.setVisibleLogicalRange(first, n + (now ? 34 : 40));
  // The bars in view and a 2% target on either side.
  chart.applyPriceScaleOptions({
    margins: now ? { top: 0.14, bottom: 0.14 } : { top: 0.12, bottom: 0.32 },
    range: {
      low: Math.min(entry * 0.98, ...bars.low.slice(first)),
      high: Math.max(entry * 1.02, ...bars.high.slice(first)),
    },
  });
  bar.style.right = now ? '12px' : '84px';
  note.style.flexBasis = now ? '100%' : 'auto';
  (now ? host : bar).append(panel);
  Object.assign(panel.style, now
    ? { position: 'absolute', left: '12px', right: '12px', bottom: '24px', justifyContent: 'space-between' }
    : { position: 'static', justifyContent: 'flex-start' });
}
layout();
const resized = new ResizeObserver(layout);
resized.observe(host);

// The lines of what was placed; drag TP or SL to change it.
let position = null;
const lines = createTradingLines(chart, candles, {
  priceStep: 0.5,
  async onModify({ kind, price }) {
    await new Promise((r) => setTimeout(r, 300)); // the server's answer
    if (!position) return false; // closed meanwhile
    const above = price > position.entry;
    if ((kind === 'takeProfit') !== (above === (position.side === 'buy'))) throw new Error('refused: wrong side of the entry');
    position[kind === 'takeProfit' ? 'target' : 'stop'] = price;
    say(`${kind === 'takeProfit' ? 'Take profit' : 'Stop'} moved to ${price}.`);
  },
  onError: (e) => say(`Change ${e.message}; the line went back.`),
});

// Buy and Sell open a position at the market price, 2% target and 1% stop;
// drag its handles to adjust. Users can also draw one with
// chart.drawings.startTool('long_position' or 'short_position').
const until = bars.time[n - 1] + 25 * 15 * 60_000;
function open(long) {
  for (const id of chart.drawings.ids()) if (chart.drawings.get(id)?.kind.endsWith('_position')) chart.drawings.remove(id);
  const k = long ? 1 : -1;
  chart.drawings.select(chart.drawings.add({ kind: long ? 'long_position' : 'short_position', anchors: [
    { time: bars.time[n - 1], price: entry },
    { time: until, price: entry * (1 + 0.02 * k) },
    { time: until, price: entry * (1 - 0.01 * k) },
  ] }));
  say('Adjust the target and stop, then Place order.');
}
buy.onclick = () => open(true);
sell.onclick = () => open(false);
// One position at a time: Buy and Sell wait until it is closed.
const holding = (on) => {
  for (const b of [buy, sell]) { b.disabled = on; b.style.opacity = on ? '0.4' : '1'; b.style.cursor = on ? 'default' : 'pointer'; }
  panel.style.display = on ? 'flex' : 'none';
};
close.onclick = () => {
  for (const id of lines.ids()) lines.remove(id);
  position = null;
  holding(false);
  say('Position closed. Buy or Sell to open another.');
};
open(true);

// The ticket beside the selected position: quantity from the amount at risk.
const ticket = createTradeTicket(chart, candles, {
  canvas, risk: 500, currency: '$', priceStep: 0.5, quantityStep: 0.001,
  async onPlaceOrder(intent) {
    buy.disabled = sell.disabled = true; // until the answer
    await new Promise((r) => setTimeout(r, 400));
    position = intent;
    const { entry, target, stop, quantity, side } = intent;
    lines.set({ id: 'position', kind: 'position', price: entry, quantity, title: `${side === 'buy' ? 'Long' : 'Short'} ${quantity}` });
    lines.set({ id: 'tp', kind: 'takeProfit', price: target, quantity });
    lines.set({ id: 'sl', kind: 'stopLoss', price: stop, quantity });
    chart.drawings.remove(intent.drawing);
    info.innerHTML = `<b style="color:${side === 'buy' ? '#26a69a' : '#ef5350'}">${side === 'buy' ? 'LONG' : 'SHORT'}</b> ${quantity} @ ${entry}`;
    holding(true);
    say('Filled. Drag TP or SL on the chart.');
  },
});

// The page calls this before it destroys the chart.
const stop = () => { resized.disconnect(); ticket.destroy(); lines.destroy(); bar.remove(); panel.remove(); canvas.style.cssText = css; };

Built for tick-level data.

Apple M4 Max · Chrome + WebGPU

Load 1 million bars and draw the first frame in the browser

WASM · WebGPU

Load 10 million bars natively, level-of-detail pyramid included

native Rust

Heap allocations per frame while panning, zooming and streaming

steady state

WebAssembly package size, gzip

all features

Browser figures: Google Chrome with WebGPU; the 10 million bar load is native Rust. Bars show each figure against its target: 300 ms for a load, no allocations, 1.5 MB for the package.

Examples

320 examples
across 20 use cases.

Each example is a live chart rendered by FerroChart in your browser, with its source code alongside. All data is synthetic.

Bar replay
Real-time stream
Candlesticks + volume
01

Price action

28 examples →

Candles, bars and lines for any market, streaming in real time.

Depth heatmap
Delta footprint
Footprint
04

Order flow

20 examples →

Footprint, depth heatmap and market profile, on a compute-shader path.

Implied volatility · basis
Long/short ratio · CVD
Funding · open interest · liquidations
06

Crypto derivatives

15 examples →

Funding, open interest, liquidations and basis in panes under price.

Risk reversal · butterfly
Expected move to expiry
Implied vs realised vol · IV rank
12

Options & volatility

18 examples →

Implied against realised, skew, expected moves and dealer exposure in time.

Joint drawdowns
Underwater curve · worst drawdown
Equity curve · drawdown
16

Portfolio, risk & quant

24 examples →

Equity curves, drawdowns, rolling statistics, factor research and risk checks.

Grouped columns
Stacked columns
100% stacked area
19

Custom series & plugins

11 examples →

Stacked, grouped, box and brushed series: layer plugins on the same GPU frame.

Browse all 20 use cases

Price action

Bar types & transforms

Technical analysis

Order flow

Execution & trade review

Crypto derivatives

On-chain

DeFi & AMMs

Memecoins & wallets

Equities & fundamentals

China A-shares

Options & volatility

Rates, FX & macro

Futures & commodities

Funds & ETFs

Portfolio, risk & quant

Private markets & personal finance

Prediction markets

Custom series & plugins

Labs & flagships

Features

Designed for market data.

01

Cross-platform rendering

A single Rust core with WebGPU and WebGL2 backends in the browser, wgpu on Metal, Vulkan and DirectX 12 in native applications, and a CPU renderer for servers. Golden-image tests keep the backends consistent.

02

Performance independent of data size

Bar data stays on the GPU and coordinate transforms run in shaders, so panning and zooming update only a few uniforms. A level-of-detail pyramid keeps tens of millions of bars responsive.

03

30 built-in indicators

Moving averages, channels and oscillators from SMA to Ichimoku. Values are updated incrementally on each tick and tested against reference data.

04

29 drawing tools

Trend lines, channels, Fibonacci tools, pitchforks, Gann fans, patterns, Elliott waves, ranges, positions and text, with undo and redo. Drawings and chart state serialize to JSON.

05

Synchronized charts

Sync groups link the crosshair and the visible range across multiple charts.

06

Extensible

Plugin interfaces for custom series, layers and drawing tools. Bindings for JavaScript, Rust and Python, and a C ABI for C#, C++, Qt and Flutter.

Get started

One API in every language.

Every binding follows the same model: create a chart, add series, set data and add indicators. Data is passed as columns, from typed arrays, Rust slices or DataFrames.

  • JavaScript & TypeScript
  • Rust
  • Python & Jupyter
  • C, C#, C++
Read the documentation
main.js
$ npm install @ferrochart/core
import { FerroChart } from '@ferrochart/core';

const chart = await FerroChart.create(canvas, { theme: 'dark' });
const candles = chart.addCandlestickSeries();
chart.addVolumeSeries(candles);
candles.setData(bars); // [{ time, open, high, low, close, volume }, ...]
chart.addIndicator(candles, 'ema', { n: 20 });
chart.addIndicator(candles, 'macd'); // in a new pane

FerroChart

Every market.
Every screen.
One engine.

Open source under Apache-2.0, from the browser to the trading desk.