Search code examples
javascriptgraphecharts

How to get red/green solid candlestick in eCharts graph


I'm trying to get red/green candlesticks in a eCharts graph starting by the example on eCharts site.

The starting example it's called "Large Scale Candlestick" that generates random data from a custom function called generateOHLC.

ORIGINAL EXAMPLE LINK

In an other example there's a link that gets data from a JSON file also from eCharts site you can see at this link: https://echarts.apache.org/...

The values ​of each array (in the big array) ​are respectively [date ,open, close, low, high, volume]

Now, I have taken some of this value and I have adapted it to get an other value in the inners array with this small easy JavaScript code:

data.forEach(function (point, point_index){
  point.push (   getSign(data, point_index, point[1], point[2], 2)   )
  //console.log(point)
})

by using the same function getSign used from the previous example.

So the last value added (pushed in the array as 1 or -1) should make the candle turn red or green.

You can see the result of the adapted example here:

ADAPTED ECHART EXAMPLE

So, why the candles are always red and the ones in the first example are red and green?

Where's my error and what I'm doing wrong?


Solution

  • Your error is in the assumption that the sign value in the data array is responsible for the coloring. This is not the case. In fact, the sign value is not even used for the candlestick series in this example you linked (only for the visualMap to color the bars). If you remove the sign completely from the data, the chart doesnt change, see here.

    Take a look at the candlestick data property. The red / green coloring depends on wether open is smaller or larger than close. As a first step it should be easier to go from this offical example as it has less complexity. From there you can transfer your data into a dataset and use encode to specify the dimensions in the same way as they are expected by the candlestick data property.

    To summarize: Your candles are always red because the dataset dimension that encodes for the open part of the candle body is always smaller than the dimension that encodes for the close part of the candle body.


    Code of the minimal candlestick example in case the link dies some day:

    option = {
      xAxis: {
        data: ['2017-10-24', '2017-10-25', '2017-10-26', '2017-10-27']
      },
      yAxis: {},
      series: [
        {
          type: 'candlestick',
          data: [
            [20, 34, 10, 38],    // red because 'open' (first dimension) is smaller than 'close' (second dimension)
            [40, 35, 30, 50],    // green because 'close' (second dimension) is smaller than 'open' (first dimension)
            [31, 38, 33, 44],
            [38, 15, 5, 42]
          ]
        }
      ]
    };