Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Charts.js candlestick (Financial Charts) displays half the bar in the beginning and the end

Having had a look at their documentation there is very little info about this.

I basically want to display a full candle chart at the beginning and the end of the graph instead of the existing half bar (Horizontally displays half of the candle bar). I have the option of tweaking my JSON data and add a fake amount, but prefer if I can manage this with existing options the charts.js might offer.

Below is the code for displaying the chart:

var candleCount = 60;
var data = getRandomData('April 01 2017', candleCount);

// Candlestick
var ctx = document.getElementById("chart1").getContext("2d");
ctx.canvas.width = 1000;
ctx.canvas.height = 250;
var candlestickChart = new Chart(ctx, {
    type: 'candlestick',
    data: {
        datasets: [{
            label: "CHRT - Chart.js Corporation",
            data: data
        }]
    }
});

// OHLC
var ctx2 = document.getElementById("chart2").getContext("2d");
ctx2.canvas.width = 1000;
ctx2.canvas.height = 250;
var ohlcChart = new Chart(ctx2, {
    type: 'ohlc',
    data: {
        datasets: [{
            label: "CHRTO - Chart.js Corporation, OHLC division",
            data: data
        }]
    }
});

var getRandomInt = function(max) {
    return Math.floor(Math.random() * Math.floor(max));
}

document.getElementById('randomizeData').addEventListener('click', function() {
    candlestickChart.data.datasets.forEach(function(dataset) {
        dataset.data = getRandomData('April 01 2017', candleCount + getRandomInt(10));
    });
    candlestickChart.update();

    ohlcChart.data.datasets.forEach(function(dataset) {
        dataset.data = getRandomData('April 01 2017', candleCount + getRandomInt(10));
    });
    ohlcChart.update();
});

Your help is much appreciated. Cheersenter image description here

like image 893
13thOlympian Avatar asked Nov 22 '25 21:11

13thOlympian


1 Answers

you can add an extra label to either side of the x-axis

by default, the labels are pulled from the data,
to override, we can pull the labels out of the data...

var candleCount = 60;
var data = getRandomData('April 01 2017', candleCount);

var xTicks = data.map(function (x) {
  return x.t;
});

then add an extra day before the first and after the last...

var oneDay = (1000 * 60 * 60 * 24);
xTicks.unshift(xTicks[0] - oneDay);
xTicks.push(xTicks[xTicks.length - 1] + oneDay);

then add the new labels to the chart options...

new Chart(ctx, {
  type: 'candlestick',
  data: {
    labels: xTicks,
    datasets: [{
      label: "CHRT - Chart.js Corporation",
      data: data,
    }]
  },
});
like image 101
WhiteHat Avatar answered Nov 25 '25 11:11

WhiteHat