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