Skip to content

Real-Time Data

ChartGPU is designed for live streaming. Here's how to connect it to a WebSocket feed.

appendCandle

The primary API for live data:

ts
chart.appendCandle({
  open:      103.5,
  high:      105.2,
  low:       102.8,
  close:     104.1,
  timestamp: Date.now(),
  volume:    85000,
});

If the viewport is at the trailing edge (user hasn't scrolled back), the chart automatically advances to keep the latest candle in view.

WebSocket Example (Binance)

ts
const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@kline_1m');

ws.onmessage = (event) => {
  const { k } = JSON.parse(event.data);

  chart.appendCandle({
    open:      parseFloat(k.o),
    high:      parseFloat(k.h),
    low:       parseFloat(k.l),
    close:     parseFloat(k.c),
    timestamp: k.t,
    volume:    parseFloat(k.v),
  });
};

Updating the Last Candle

For tick-level updates where the current candle is still forming, replace the last candle:

ts
const candles = chart.getCandles();
candles[candles.length - 1] = updatedCandle;
chart.setCandles(candles);

setCandles replaces the full dataset and resets the viewport to show all candles. For high-frequency updates, prefer appendCandle with a complete candle per interval.

Timeframe Switching

When the user changes the timeframe, fetch new candle data and reset:

ts
chart.setTimeframe('5m');
chart.setCandles(await fetchCandles('5m'));

setTimeframe fires the timeframeChange event which you can subscribe to:

ts
chart.on('timeframeChange', (tf) => {
  console.log('New timeframe:', tf);
});

Events

ts
chart.on('viewportChange', (viewport) => {
  // viewport.start, viewport.end changed (pan/zoom)
});

chart.on('timeframeChange', (tf) => {
  // User switched timeframe
});

Released under the MIT License.