score:1

Accepted answer

your problem comes from 2 things:

  1. your chart config in options with xaxes that should be xaxis instead
  2. missing labels and correct data in chart data

here is the codes that works:

var stocksdata = {
  datasets: [
    {
      label: 'open',
      backgroundcolor: 'rgba(104,0,255,0.1)',
      data: [

      ],
    },
  ],
};
window.onload = function() {
  var ctx = document.getelementbyid('mychart').getcontext('2d');

  var linechart = new chart(ctx, {
    type: 'line',
    data: stocksdata,
    options: {
      scales: {
        xaxis: [
          {
            type: 'linear',
            position: 'bottom',
          },
        ],
      },
    },
  });
  window.linechart = linechart;
};

var sym = 'aapl'; //get from form
var tseries = 'time_series_intraday'; //get from form
var target = `https://www.alphavantage.co/query?function=${tseries}&symbol=${sym}&interval=5min&apikey=va3rz8b9ppywkqkn`;
function update () {
fetch(target)
  .then(response => response.json())
  .then(data => {
    var prices = data['time series (5min)'];
    for (prop in prices) {
      var stockprices = prices[prop]['1. open'];
      //change to 2. high, etc
      console.log(`${prop} : ${stockprices}`);
      //stocksdata.datasets[0].data.push({x: prop, y: +stockprices})
      stocksdata.datasets[0].data.push(stockprices);
      // format date here. for example with moment:
      // var date = moment(prop).format('yyyy-mm-dd')
      stocksdata.labels.push(prop);
      //time x axes are preventing render
      window.linechart.update();
    }
  })
  .catch(error => console.error(error));
}

a complete format for chart data would be like:

var stocksdata = {
  labels: ['date1', 'date2', 'date3', 'date4'],
  datasets: [
    {
      label: 'open',
      backgroundcolor: 'rgba(104,0,255,0.1)',
      data: [
        'data1', 'data2', 'data3', 'data4'
      ],
    },
  ],
};

then each data and date label should be push separately:

stocksdata.datasets[0].data.push(stockprices);
stocksdata.labels.push(prop);

to format with moment you can use:

var datestr = moment(prop).format('yyyy-mm-dd');

score:1

the "odd" time format is (almost) the standard international datetime format. in this case yyyy-mm-dd hh:mm:ss. i strongly suggest you familiarise yourself with it and use it in preference to dd/mm/yyyy or mm/dd/yyyy.

you can fix your code by changing the x-axis type to time and adding the appropriate configuration options:

options: {
  scales: {
    xaxes: [
      {
        type: 'time',
        ...

note that you'll also need to change your call to chart.js to the version with moment.js bundled (or include moment separately):

<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.9.3/chart.bundle.min.js"></script>

Related Query

More Query from same tag