If you are working or doing research on any charting library, you might have heard about Highcharts. Highstock is nothing but an extension of the highcharts which is specifically built for the financial or time series data. So that you have more options to leverage on any time related actions.
You might have seen any charts streaming live data for example in any stock exchange site, or a live sports site. Likewise, Highstock also provides an option to live stream your data.
In today’s blog post, I will show you how to live stream your data.
First, include Highstock in your page the old-school way:
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>Create a container:
<div id="liveChart" style="height: 400px; min-width: 600px"></div>Create a Basic Highstock Live Chart
Here’s the simplest possible live-updating Highstock chart.
Step 1: Initialize the chart
Highcharts.stockChart('liveChart', {
chart: {
events: {
load: function () {
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(); // current time
var y = Math.random() * 100; // random value (simulate API data)
series.addPoint([x, y], true, true); // shift to keep chart moving
}, 1000);
}
}
},
rangeSelector: {
selected: 1
},
title: {
text: 'Live Data Streaming with Highstock'
},
series: [{
name: 'Random Data',
data: (function () {
// generate initial data for last 1 minute
var data = [], time = (new Date()).getTime(), i;
for (i = -60; i <= 0; i++) {
data.push([time + i * 1000, Math.random() * 100]);
}
return data;
}())
}]
});How It Works
1. Load Event
Once the chart loads, we fetch the first series:
var series = this.series[0];2. Load data at every specific interval & Add new point to the searies
var x = new Date().getTime();
var y = Math.random() * 100;
series.addPoint([x, y], true, true);Here in addPoint
- 1st
true-> redraw chart instantly - 2nd
true-> remove the first point (keeps the chart sliding like real stock charts)
This gives you the smooth “live feed” effect.
Now you can load the data from the API instead of just using Math.Random.