Search code examples
angularchart.jscandlestick-chart

Trouble getting a candlestick graph to plot


The relevant parts of package.json are:

    "@angular/core": "^18.0.3",
    "chart.js": "^4.4.3",
    "chartjs-chart-financial": "^0.2.1",
    "ng2-charts": "^6.0.1",

The application is built using Components.

I have successfully created a number of bar, line, and pie charts in my application, however I cannot get a candlestick graph to render.

I have created an isolated component, with minimal test data to ensure there are no conflicts with other charts.

My test component reads:

import { Component } from '@angular/core';

import { ChartConfiguration, ChartData, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';

import 'chartjs-chart-financial';


@Component({
  selector: 'naas-test',
  template: `<h3>Whisker data</h3>
  <canvas
  style="border: 1px solid red"
  baseChart
  [data]="myWiskerChartData"
  [options]="myWiskerChartOptions"
  [type]="candlestickChartType"
  aria-label="candlestck graph"></canvas>`,
  standalone: true,
  imports: [BaseChartDirective],
})
export class TestComponent {
  constructor() {}

  public candlestickChartType: ChartType = 'candlestick';

  public myWiskerChartOptions: ChartConfiguration['options'] = {
    responsive: true,
    scales: {
      x: {
        type: 'linear',
        position: 'bottom'
      },
    },
  };

  public myWiskerChartData: ChartData<'candlestick'> = {
    datasets: [
     {
      label: 'my Whisker',
      data: [
        {
          "x": 1,
          "o": 59,
          "l": 59,
          "h": 59,
          "c": 59
        },
        {
          "x": 2,
          "o": 3660,
          "l": 3690,
          "h": 3750,
          "c": 3780
        },
        {
          "x": 3,
          "o": 3840,
          "l": 4020,
          "h": 4844,
          "c": 5340
        },
      ]
    }
  ]
  };
}

This test component renders in my app, and I can see the space the canvas element takes up (both from the red box border, and looking at the page elements after rendering)... however I'm not getting anything rendered in the graph: no axis, no labels, no grids, and the three box-and-whisker items are not being shown.

As far as I can tell, by datasets match the requirements for chartjs-chart-financial structures, and the creation of the charts matches what has worked with all my line/bar/pie charts.

What am I missing?


Solution

  • Chart.js is one of those tree-shakable libs, so you must import and register components and their controllers.

    Like this :: import { CandlestickController, CandlestickElement, OhlcController, OhlcElement } from 'chartjs-chart-financial'; Chart.register(OhlcElement,OhlcController,CandlestickElement,CandlestickController) Chart.register(...registerables)

    StackBlitzDEMOLINK