AmChart stock chart not showing different graphs - javascript

I am trying to show two graphs in an AmChart stock chart but it is showing the same data in both charts. My Javascript code looks like this:
var chart = AmCharts.makeChart("chartdiv", {
type: "stock", // Possible types are: serial, pie, xy, radar, funnel, gauge, map, stock
pathToImages: "http://www.amcharts.com/images/",
dataDateFormat: "YYYY-MM-DD",
dataSets: [{
color: "#b0de09", // bar chart color
// userRegistrations variable is source of user data
dataProvider: userRegistrations,
fieldMappings: [{
fromField: "val",
toField: "value"
}],
categoryField: "date"
},
{
color: "#efefef", // bar chart color
// likes variable is source of data for likes
dataProvider: likes,
fieldMappings: [{
fromField: "val",
toField: "value"
}],
categoryField: "date",
}],
panels: [{
legend: {},
stockGraphs: [{
id: "graph1",
valueField: "value",
type: "column",
title: "User Graph",
fillAlphas: 1,
comparable: true,
compareField: "value",
balloonText: "Users registered: <b>[[val]]</b>",
}]
},
{
legend: {},
stockGraphs: [{
id: "graph2",
valueField: "value",
type: "column",
title: "Watch List Graph",
fillAlphas: 1,
comparable: true,
compareField: "value",
balloonText: "Added to Watch List: <b>[[val]]</b>",
}]
}],
panelsSettings: {
startDuration: 1
},
categoryAxesSettings: {
dashLength: 5
},
valueAxesSettings: {
dashLength: 5
},
chartScrollbarSettings: {
graph: "graph1",
graphType: "line",
position: "top"
},
chartCursorSettings: {
valueBalloonsEnabled: true,
fullWidth:true,
cursorAlpha:0.1
},
// range selector
periodSelector: {
position: "top",
periods: [{
period: "DD",
count: 1,
label: "1 day"
}, {
period: "DD",
selected: true,
count: 7,
label: "7 days"
}, {
period: "MM",
count: 1,
label: "1 month"
}, {
period: "YYYY",
count: 1,
label: "1 year"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
}]
},
// ballon on mouse hover
"balloon": {
"adjustBorderColor": true,
"color": "#000000",
// "cornerRadius": 5,
"fillColor": "#FFFFFF"
}
});
// date picker
chart.addListener('rendered', function (event) {
var dataProvider = chart.dataSets[0].dataProvider;
$(".amChartsPeriodSelector .amChartsInputField").datepicker({
dateFormat: "dd-mm-yy",
minDate: dataProvider[0].date,
maxDate: dataProvider[dataProvider.length-1].date,
onClose: function() {
$(".amChartsPeriodSelector .amChartsInputField").trigger('blur');
}
});
});
I have two datasets and two panels. Both panels are showing the same dataset (the one with the userRegistrations dataProvider). I want to show to separate data sets.
I have looked through the AmCharts documentation but cannot work out how to do this.

If I understand it correctly, you want the first panel to display graph generated from first data set, and the second panel to show graph from second data set.
To achieve that you will need to do a couple of things:
1) Make the second data set compared by setting it's compared parameter to true as well as map the value field to a different name than the first data set:
{
color: "#efefef", // bar chart color
// likes variable is source of data for likes
dataProvider: likes,
fieldMappings: [{
fromField: "val",
toField: "value2"
}],
categoryField: "date",
compared: true
}
2) Make the graph on the second panel use "value2" field insteadl of "value".
Here's full code:
var chart = AmCharts.makeChart("chartdiv", {
type: "stock", // Possible types are: serial, pie, xy, radar, funnel, gauge, map, stock
pathToImages: "http://www.amcharts.com/images/",
dataDateFormat: "YYYY-MM-DD",
dataSets: [{
color: "#b0de09", // bar chart color
// userRegistrations variable is source of user data
dataProvider: userRegistrations,
fieldMappings: [{
fromField: "val",
toField: "value"
}],
categoryField: "date"
},
{
color: "#efefef", // bar chart color
// likes variable is source of data for likes
dataProvider: likes,
fieldMappings: [{
fromField: "val",
toField: "value2"
}],
categoryField: "date",
compared: true
}],
panels: [{
legend: {},
stockGraphs: [{
id: "graph1",
valueField: "value",
type: "column",
title: "User Graph",
fillAlphas: 1,
comparable: true,
compareField: "value",
balloonText: "Users registered: <b>[[val]]</b>",
}]
},
{
legend: {},
stockGraphs: [{
id: "graph2",
valueField: "value2",
type: "column",
title: "Watch List Graph",
fillAlphas: 1,
comparable: true,
compareField: "value2",
balloonText: "Added to Watch List: <b>[[val]]</b>",
}]
}],
panelsSettings: {
startDuration: 1
},
categoryAxesSettings: {
dashLength: 5
},
valueAxesSettings: {
dashLength: 5
},
chartScrollbarSettings: {
graph: "graph1",
graphType: "line",
position: "top"
},
chartCursorSettings: {
valueBalloonsEnabled: true,
fullWidth:true,
cursorAlpha:0.1
},
// range selector
periodSelector: {
position: "top",
periods: [{
period: "DD",
count: 1,
label: "1 day"
}, {
period: "DD",
selected: true,
count: 7,
label: "7 days"
}, {
period: "MM",
count: 1,
label: "1 month"
}, {
period: "YYYY",
count: 1,
label: "1 year"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
}]
},
// ballon on mouse hover
"balloon": {
"adjustBorderColor": true,
"color": "#000000",
// "cornerRadius": 5,
"fillColor": "#FFFFFF"
}
});

Related

CanvasJS stock chart axisY doesn't update automatically with my data

I have tried the stock chart with sample data present on the CanvasJS site and it updates the Y axis everytime I scroll through it, but when I pass my data to that function it scrolls but without updating the Y-axis.
First I was trying to fetch data from array of arrays but the sample chart was using array of JSON so I converted my data to be of the exact similar manner but to no avail. I would be very thankful if you can help me on this.
My data
window.onload = function () {
CanvasJS.addColorSet("greenShades",
[//colorSet Array
"red",
"#008080",
"#2E8B57",
"#3CB371",
"#90EE90"
]);
var dataPoints = [];
var stockChart = new CanvasJS.StockChart("stockChartContainer",{
zoomEnabled: true,
theme: "light2",
colorSet: "greenShades",
exportEnabled: true, //false
title:{
text:""
},
subtitles: [{
text: ""
}],
rangeSelector: {
buttons: [
{
range: 10, //Change it to 6
rangeType: "day",
label: "10D"
},
{
range: 1, //Change it to 6
rangeType: "month",
label: "1M"
},
{
range: 6, //Change it to 6
rangeType: "month",
label: "6M"
},
{
range: 1, //Change it to 6
rangeType: "year",
label: "1Y"
},
{
rangeType: "all",
label: "All" //Change it to "All"
}
]
},
charts: [{
axisX: {
},
axisY: {
prefix: "",
suffix: "",
title: "",
viewportMinimum: 20,
viewportMaximum: 200,
titleFontSize: 14
},
data: [{
type: "area",
xValueFormatString: "MMM YYYY",
yValueFormatString: "#,###.##M",
dataPoints : dataPoints
}]
}],
navigator: {
// slider: {
// minimum: new Date(2010, 00, 01),
// maximum: new Date(2014, 00, 01)
// }
}
});
$.getJSON("https://financialmodelingprep.com/api/v3/historical-price-full/AAPL?apikey=API_KEY", function(data) {
for(var i = 0; i < data.historical.length; i++){
dataPoints.push({x: new Date(data.historical[i].date), y: Number(data.historical[i].close)});
}
console.log(dataPoints)
stockChart.render();
});
}

How to make the zoom bar stay always on top when scrolling through the graphs in Amchart

Is there a way to make the zoom bar to stay fixed when scrolling through the graphs in amchart. Here is the demo.
Here is the code:
var chartData1 = [];
var chartData2 = [];
var chartData3 = [];
generateChartData();
function generateChartData() {
var firstDate = new Date();
firstDate.setDate(firstDate.getDate() - 500);
firstDate.setHours(0, 0, 0, 0);
for (var i = 0; i < 500; i++) {
var newDate = new Date(firstDate);
newDate.setDate(newDate.getDate() + i);
var a1 = Math.round(Math.random() * (40 + i)) + 100 + i;
var a2 = -1 * Math.round(Math.random() * (100 + i)) + 200 + i;
var a3 = -1 * Math.round(Math.random() * (1000 + i)) + 2000 + i;
chartData1.push({
date: newDate,
value: a1
});
chartData2.push({
date: newDate,
value: a2
});
chartData3.push({
date: newDate,
value: a3
});
}
}
AmCharts.makeChart("chartdiv", {
type: "stock",
dataSets: [{
title: "first data set",
fieldMappings: [{
fromField: "value",
toField: "value"
}],
dataProvider: chartData1,
categoryField: "date"
},
{
title: "second data set",
fieldMappings: [{
fromField: "value",
toField: "value2"
}],
dataProvider: chartData2,
categoryField: "date",
compared: true
},
{
title: "third data set",
fieldMappings: [{
fromField: "value",
toField: "value3"
}],
dataProvider: chartData3,
categoryField: "date",
compared: true
}
],
panels: [{
showCategoryAxis: false,
title: "Data set #1",
recalculateToPercents: "never",
stockGraphs: [{
id: "g1",
valueField: "value",
comparable: true,
bullet: "round"
}],
stockLegend: {
}
},{
showCategoryAxis: false,
title: "Data set #2",
recalculateToPercents: "never",
stockGraphs: [{
id: "g2",
valueField: "value2",
comparable: true,
bullet: "round"
}],
stockLegend: {
}
}, {
showCategoryAxis: true,
title: "Data set #3",
recalculateToPercents: "never",
stockGraphs: [{
id: "g3",
valueField: "value3",
compareField: "value3",
comparable: true,
bullet: "round",
visibleInLegend: false
}],
stockLegend: {
}
}
],
chartScrollbarSettings: {
graph: "g1"
},
chartCursorSettings: {
valueBalloonsEnabled: true,
fullWidth:true,
cursorAlpha:0.1
},
periodSelector: {
periods: [{
period: "MM",
selected: true,
count: 1,
label: "1 month"
}, {
period: "YYYY",
count: 1,
label: "1 year"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
}]
}
});

Unable to Add More than 2 charts to amchart stock chart

I'm trying to add 3 charts to the stock chart displaying data from different data set in separate panels.
Here is the JS code:
var chartData1 = [];
var chartData2 = [];
var chartData3 = [];
generateChartData();
function generateChartData() {
var firstDate = new Date();
firstDate.setDate(firstDate.getDate() - 500);
firstDate.setHours(0, 0, 0, 0);
for (var i = 0; i < 500; i++) {
var newDate = new Date(firstDate);
newDate.setDate(newDate.getDate() + i);
var a1 = Math.round(Math.random() * (40 + i)) + 100 + i;
var a2 = -1 * Math.round(Math.random() * (100 + i)) + 200 + i;
var a3 = -1 * Math.round(Math.random() * (1000 + i)) + 2000 + i;
chartData1.push({
date: newDate,
value: a1
});
chartData2.push({
date: newDate,
value: a2
});
chartData3.push({
date: newDate,
value: a3
});
}
}
AmCharts.makeChart("chartdiv", {
type: "stock",
dataSets: [{
title: "first data set",
fieldMappings: [{
fromField: "value",
toField: "value"
}],
dataProvider: chartData1,
categoryField: "date"
},
{
title: "second data set",
fieldMappings: [{
fromField: "value",
toField: "value2"
}],
dataProvider: chartData2,
categoryField: "date"
},
{
title: "third data set",
fieldMappings: [{
fromField: "value",
toField: "value3"
}],
dataProvider: chartData3,
categoryField: "date",
compared: true
}
],
panels: [{
showCategoryAxis: false,
title: "Data set #1",
recalculateToPercents: "never",
stockGraphs: [{
id: "g1",
valueField: "value",
comparable: true,
bullet: "round"
}],
stockLegend: {
}
},{
showCategoryAxis: false,
title: "Data set #2",
recalculateToPercents: "never",
stockGraphs: [{
id: "g2",
valueField: "value2",
comparable: true,
bullet: "round"
}],
stockLegend: {
}
}, {
showCategoryAxis: true,
title: "Data set #3",
recalculateToPercents: "never",
stockGraphs: [{
id: "g3",
valueField: "value3",
compareField: "value3",
comparable: true,
bullet: "round",
visibleInLegend: false
}],
stockLegend: {
}
}
],
chartScrollbarSettings: {
graph: "g1"
},
chartCursorSettings: {
valueBalloonsEnabled: true,
fullWidth:true,
cursorAlpha:0.1
},
periodSelector: {
periods: [{
period: "MM",
selected: true,
count: 1,
label: "1 month"
}, {
period: "YYYY",
count: 1,
label: "1 year"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
}]
}
});
Here is a link to the demo. It displays only two charts , the third is not rendering.
You need to set compared to true in all dataSets after the first one if you want them to be visible by default. You only have it set in the third one but not the second.
{
title: "second data set",
fieldMappings: [
{
fromField: "value",
toField: "value2"
}
],
dataProvider: chartData2,
categoryField: "date",
compared: true //needs to be enabled
},
{
title: "third data set",
fieldMappings: [
{
fromField: "value",
toField: "value3"
}
],
dataProvider: chartData3,
categoryField: "date",
compared: true //needs to be enabled
Updated codepen

Dynamic div id for directive html

I have a problem using dynamic div id in directive template to rendering graph. The error that I get is
Cannot set property 'innerHTML' of null
My template.html
<div id="{{title}}" style="height: 40vh;"></div>
The directive is simply rendering graph on given div id
link: function (scope, element, attrs) {
let chart = AmCharts.makeChart(scope.title, {
type: "stock",
theme: "light",
dataSets: [scope.data.dataset],
panels: [{
showCategoryAxis: false,
recalculateToPercents: "never",
title: scope.data.title,
valueAxes: [{
title: scope.data.type,
titleFontSize: 10,
titleBold: false
}],
stockGraphs: [{
id: "g1",
valueField: "value",
comparable: true,
bullet: "round",
bulletBorderColor: "#FFFFFF",
bulletBorderAlpha: 1,
balloonText: "[[title]]: <b>[[value]]</b>",
compareGraphBalloonText: "[[title]]: <b>[[value]]</b>",
compareGraphBullet: "round",
compareGraphBulletBorderColor: "#FFFFFF",
compareGraphBulletBorderAlpha: 1
}],
stockLegend: {
periodValueTextRegular: "[[value.close]]"
},
}],
panelsSettings: {
mouseWheelZoomEnabled: true,
marginLeft: 60
},
valueAxesSettings: {
axisAlpha: 1,
gridThickness: 0,
axisThickness: 1,
inside: false
},
categoryAxesSettings: {
minPeriod: "ss"
},
chartScrollbarSettings: {
graph: "g1",
usePeriod: "10mm",
updateOnReleaseOnly: false
},
chartCursorSettings: {
cursorPosition: "mouse"
},
periodSelector: {
dateFormat: "YYYY-MM-DD JJ:NN:SS",
periods: [{
period: "hh",
count: 1,
label: "1 hour"
}, {
period: "hh",
count: 2,
label: "2 hours"
}, {
period: "hh",
count: 5,
label: "5 hour"
}, {
period: "hh",
count: 12,
label: "12 hours"
}, {
period: "MAX",
label: "MAX"
}]
}
});
}
Anybody have an idea how to get around this problem, thanks in advance.
Try setting the ID on the div by using ng-attr-. For example: <div ng-attr-id="title" style="height: 40vh;"></div>

Issues with amcharts

I am making stock charts with amcharts library . Here is what I have achieved
And here is what I want
You can compare both picture and see I have cylindrical and moving avg graph (dashed lines) but I am not able to add spikes which are showing at the bottom of graph in original one. (Pink and orange color). I don't know how to add those spikes in stock graph .
My data is dynamic so I can't create a js fiddle but I can provide my function here-
function load_stock_graph(graph_type, history, title, aggregate){
// DEFINE CHART PLUGINS
AmCharts.averageGraphs = 0;
AmCharts.addMovingAverage = function (dataSet, panel, field, aggregate, col ,graph) {
// update dataset
var avgField = "avg"+AmCharts.averageGraphs;
dataSet.fieldMappings.push({
fromField: avgField,
toField: avgField});
// calculate moving average
var fc = 0;
var sum = 0;
for (var i = 0; i < dataSet.dataProvider.length; i++) {
// console.log(aggregate[i].ema_0008)
var dp = dataSet.dataProvider[i];
if (dp[field] !== undefined) {
sum += dp[field];
fc++;
if (aggregate[i] !== undefined){
if(col == '08'){
dp[avgField] = aggregate[i].ema_0008;
}else if(col == '15'){
dp[avgField] = aggregate[i].ema_0015;
}else if(col == '20'){
dp[avgField] = aggregate[i].ema_0020;
}
}
}
}
// create a graph
graph.valueField = avgField;
panel.stockGraphs.push(graph);
// increment average graph count
AmCharts.averageGraphs++;
}
// CHART DATA
var chartData = [];
var chartData1 = [];
generateChartData(history);
function generateChartData(history) {
var firstDate = new Date();
firstDate.setHours(0, 0, 0, 0);
firstDate.setDate(firstDate.getDate() - 2000);
for (var i = 0; i < history.length; i++) {
var date = new Date(history[i].date);
var val = Math.round(Math.random() * (30) + 100);
chartData[i] = ({
date: date,
open: history[i].open,
close: history[i].close,
high: history[i].high,
low: history[i].low,
volume: history[i].volume,
value: val
});
}
}
// CHART CONFIG
var chartConfig = {
type: "stock",
pathToImages : "/static/img/amcharts/",
dataSets: [{
fieldMappings: [{
fromField: "open",
toField: "open"
}, {
fromField: "close",
toField: "close"
}, {
fromField: "high",
toField: "high"
}, {
fromField: "low",
toField: "low"
}, {
fromField: "volume",
toField: "volume"
}, {
fromField: "value",
toField: "val"
}],
color: "#fff",
dataProvider: chartData,
title: title,
categoryField: "date",
compared: false,
},
{
fieldMappings: [{
fromField: "value",
toField: "value"
}],
color: "#fff",
dataProvider: chartData,
title: title,
categoryField: "date"
},
],
panels: [{
title: "Value",
percentHeight: 70,
stockGraphs: [{type: graph_type,
id: "g1",
openField: "open",
closeField: "close",
highField: "high",
lowField: "low",
valueField: "close",
lineColor: "#fff",
fillColors: "#fff",
negativeLineColor: "#db4c3c",
negativeFillColors: "#db4c3c",
fillAlphas: 1,
comparedGraphLineThickness: 2,
columnWidth: 0.7,
useDataSetColors: false,
comparable: true,
compareField: "close",
showBalloon: false,
//proCandlesticks: true
} ],
stockLegend: {
valueTextRegular: undefined,
periodValueTextComparing: "[[percents.value.close]]%"
}
},
{
title: "Volume",
percentHeight: 40,
marginTop: 1,
columnWidth: 0.6,
showCategoryAxis: false,
valueAxes: [{
usePrefixes: true
}],
stockGraphs: [ {
valueField: "volume",
openField: "open",
type: "column",
showBalloon: false,
fillAlphas: 1,
lineColor: "#fff",
fillColors: "#fff",
negativeLineColor: "#db4c3c",
negativeFillColors: "#db4c3c",
useDataSetColors: false,
} ],
stockLegend: {
markerType: "none",
markerSize: 0,
labelText: "",
periodValueTextRegular: "[[value.close]]"
}
}
],
panelsSettings: {
color: "#fff",
plotAreaFillColors: "#333",
plotAreaFillAlphas: 1,
marginLeft: 60,
marginTop: 5,
marginBottom: 5
},
chartScrollbarSettings: {
graph: "g1",
graphType: "line",
usePeriod: "WW",
backgroundColor: "#333",
graphFillColor: "#666",
graphFillAlpha: 0.5,
gridColor: "#555",
gridAlpha: 1,
selectedBackgroundColor: "#444",
selectedGraphFillAlpha: 1
},
categoryAxesSettings: {
equalSpacing: true,
gridColor: "#555",
gridAlpha: 1
},
valueAxesSettings: {
gridColor: "#555",
gridAlpha: 1,
inside: false,
showLastLabel: true
},
chartCursorSettings: {
pan: true,
valueLineEnabled:true,
valueLineBalloonEnabled:true
},
legendSettings: {
color: "#fff"
},
stockEventsSettings: {
showAt: "high"
},
balloon: {
textAlign: "left",
offsetY: 10
},
periodSelector: {
position: "bottom",
periods: [ {
period: "DD",
count: 10,
label: "10D"
}, {
period: "MM",
count: 1,
label: "1M"
}, {
period: "MM",
count: 6,
selected: true,
label: "6M"
}, {
period: "YYYY",
count: 1,
label: "1Y"
}, {
period: "YYYY",
count: 2,
label: "2Y"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
} ]
},
"export": {
"enabled": true,
"backgroundColor": "#fff",
"dataDateFormat": "YYYY-MM-DD"
}
}
// ADD INDICATORS
// ema_0008
AmCharts.addMovingAverage(chartConfig.dataSets[0], chartConfig.panels[0], 'value',aggregate, '08', {
useDataSetColors: false,
color: "#ccffcc",
lineColor: "#F4F009",
title: "aggregate ema 0008",
dashLength: 3
});
// ema_0015
AmCharts.addMovingAverage(chartConfig.dataSets[0], chartConfig.panels[0], 'value',aggregate, '15',{
useDataSetColors: false,
color: "#ccffcc",
lineColor: "#2C7F1D",
title: "aggregate ema 0015",
dashLength: 3
});
// ema_0020
AmCharts.addMovingAverage(chartConfig.dataSets[0], chartConfig.panels[0], 'value',aggregate, '20',{
useDataSetColors: false,
color: "#ccffcc",
lineColor: "#A109E8",
title: "aggregate ema 0020",
dashLength: 3
});
// Empty chart instance so that chart loaded via ajax can work correctly
AmCharts.charts = [];
// CREATE CHART
var chart = AmCharts.makeChart("chartdiv", chartConfig);
}
Sounds like you just need to add another line graph in a separate panel.
Here's how to do it:
1) Add additional field in your data. You currently have open, high, low, close field. Let's add another one, say, "pink".
2) Update Data Set's fieldMappings property, to accommodate for the change:
[{
fromField: "open",
toField: "open"
}, {
fromField: "close",
toField: "close"
}, {
fromField: "high",
toField: "high"
}, {
fromField: "low",
toField: "low"
}, {
fromField: "volume",
toField: "volume"
}, {
fromField: "value",
toField: "val"
}, {
fromField: "pink",
toField: "pink"
}]
3) Add additional stock panel and a graph that will use the newly added data field:
{
percentHeight: 20,
showCategoryAxis: false,
stockGraphs: [{
valueField: "pink",
showBalloon: false,
lineColor: "#fb02fe",
lineThickness: 2,
useDataSetColors: false
}]
}
If you would have wanted to add the indicator to some existing panel, you would just need to define the graph in it's stockGraphs array. I.e.:
{
percentHeight: 20,
showCategoryAxis: false,
stockGraphs: [{
valueField: "pink",
showBalloon: false,
lineColor: "#fb02fe",
lineThickness: 2,
useDataSetColors: false
}, {
valueField: "red",
showBalloon: false,
lineColor: "#cc0000",
lineThickness: 2,
useDataSetColors: false
}]
}
Use this process to add as many indicators as you need.
Here's a working demo (with random values)
http://codepen.io/amcharts/pen/938b09efeabca4596c0a2cdaea60a269

Categories

Resources