xendi
xendi

Reputation: 2522

How to dynamically add stockEvents to amCharts

I have a function I'm using to add new data points to my stock chart. I need to create a condition under which one of the data points comes with an icon. I see that stockEvents can do this but it's not showing in my chart:

function addDataPoint(ask) {
        var dataProvider = chart.dataSets[0].dataProvider;
        var newDate = new Date(dataProvider[dataProvider.length - 1].date.getTime());
        newDate.setHours(newDate.getHours(), newDate.getMinutes() + 1, newDate.getSeconds());
        var a = Math.round(Math.random() * (40 + 1000)) + 100 + 1000;
        var b = Math.round(Math.random() * 100000000);
        dataProvider.push({
            date: newDate,
            value: ask,
            volume: ask
        });
        chart.dataSets[0].stockEvents = [{
            date: newDate,
            type: "flag",
            text: "F",
            description: "Some longer\ntext can also\n be added"
        }];
        dataProvider.shift();
    }

Upvotes: 0

Views: 360

Answers (1)

xorspark
xorspark

Reputation: 16012

You need to set the stock event's graph property in order for it to be visible. This can be a reference to the stock graph object, or the graph's id. You also need to call validateData in order to update the chart if you aren't already doing so outside of your addDataPoint function.

AmCharts.makeChart("chartdiv", {
  // ...
  "panels": [{
    // ...
    "stockGraphs": [{
       // ...
       "id": "g1", //added id
       // ...
    },
    // ...
    ]
  },
  // ...
  ],
  // ...
});
// ...
function addDataPoint(ask) {
  // ...
  chart.dataSets[0].stockEvents = [{
    date: newDate,
    type: "flag",
    text: "F",
    graph: "g1", //added
    description: "Some longer\ntext can also\n be added"
  }];
  dataProvider.shift();
  chart.validateData(); //added
}

Also note that you're overwriting the stockEvents array each time in your addDataPoint function. If you want to preserve your previous event, then you need to use push since it's an array.

Demo

Upvotes: 1

Related Questions