Enhancing Financial Charts: Add Bollinger Bands to CanvasJS

Vishwas R
3 min readJan 24, 2024

--

CanvasJS is a versatile JavaScript library that empowers developers to create interactive and visually appealing charts & stockcharts. In this article, let’s explore how to add Bollinger Bands, a key technical indicator, in CanvasJS StockChart. This combination delivers a sophisticated and insightful view of stock market data, merging the power of candlestick patterns with the volatility analysis offered by Bollinger Bands.

Prerequisites:

Before we begin, make sure you have the latest version of CanvasJS StockCharts library integrated into your web application. You can obtain the library from the official CanvasJS website or include it using a CDN.

<script src="https://cdn.canvasjs.com/canvasjs.stock.min.js"></script>

Step 1: Setting Up the CanvasJS StockChart

Begin by creating a basic CanvasJS StockChart that displays the financial data you want to analyze. Set the type to "candlestick" and adjust the y values to represent [open, high, low, close].

var dataPoints = [
{ x: new Date('2024-01-01'), y: [150, 170, 140, 160] },
{ x: new Date('2024-01-02'), y: [160, 180, 150, 170] },
// ... add more data points
];

var stockChart = new CanvasJS.StockChart("stockChartContainer", {
title: { text: "Financial Data with Bollinger Bands" },
charts: [{
type: "candlestick",
data: [{
dataPoints: dataPoints
}]
}]
});

stockChart.render();

Step 2: Calculating Bollinger Bands

Bollinger Bands consist of three lines — the middle band (SMA), the upper band (SMA + (2 * standard deviation)), and the lower band (SMA — (2 * standard deviation)). We can calculate these values and add them to the stockchart. The Bollinger Bands are calculated based on the closing prices (y[3]). The upper, lower, and middle bands are added as separate series to the chart.

function calculateBands(dps, count) {
var avg = function(dps){
var sum = 0, count = 0, val;
for (var i = 0; i < dps.length; i++) {
val = dps[i].y[3]; sum += val; count++;
}
return sum / count;
}

var sd = function(dps) {
var total = 0;
for(var i = 0; i < dps.length; i++)
total += dps[i].y[3];
var meanVal = total / dps.length;

var SDprep = 0;
for(var i = 0; i < dps.length; i++)
SDprep += Math.pow((parseFloat(dps[i].y[3]) - meanVal),2);

return Math.sqrt(SDprep/(dps.length-1));
}

var avgData = [], rangeData = [], upperBand, middleBand, lowerBand;
count = count || 5;
for (var i = 0; i < count; i++) {
avgData.push({ x: dps[i].x , y: null });
rangeData.push({ x: dps[i].x, y: null });
}

for (var i = count - 1, len = dps.length; i < len; i++){
upperBand = avg(dps.slice(i - count + 1, i)) + (sd(dps.slice(i - count + 1, i)) * 2);
middleBand = avg(dps.slice(i - count + 1, i));
lowerBand = avg(dps.slice(i - count + 1, i)) - (sd(dps.slice(i - count + 1, i)) * 2);

if (isNaN(middleBand)) {
avgData.push({ x: dps[i].x, y: null });
} else {
avgData.push({ x: dps[i].x, y: Number(middleBand.toFixed(2)) });
}

if(isNaN(upperBand) || isNaN(lowerBand)) {
rangeData.push({ x: dps[i].x, y: null });
}else {
rangeData.push({ x: dps[i].x, y: [Number(lowerBand.toFixed(2)), Number(upperBand.toFixed(2))] });
}
}
return { avg: avgData, range: rangeData };
}

Step 3: Adding Bollinger Bands to the Chart

Now that we have calculated the Bollinger Bands values, we can add them to the chart. Use range-area to show lower & upper bands and line chart to show middle band.

data.push({
type: "rangeArea",
toolTipContent: "Lower Band: {y[0]}<br/>Upper Band: {y[1]}",
fillOpacity: 0.1,
dataPoints: rangeData
});
data.push({
type: "line",
toolTipContent: "Middle Band: {y}",
dataPoints: avgData
});

JSFiddle: https://jsfiddle.net/vishwas_r/wepsh49x/

This combination of candlestick patterns and Bollinger Bands empowers developers and traders with deeper insights into market dynamics. Customize the appearance and styling to suit your application’s design, offering users an informative and visually engaging financial charting experience.

--

--

Vishwas R
Vishwas R

Written by Vishwas R

<< Engineer || Software Developer || Techie || Cricketer || Traveler || Blogger >>

No responses yet