Highcharts datepicker - multiple series - javascript

I'm trying to use highcharts to visualize some numbers out of my database :)
After fetching them from the db I'm encoding the outcome (currently 2 categories) as JSON:
Name
Category
Data
[{"name":"Something 1","category":["2014-07-13 00:00:00","2014-07-13 01:00:00","2014-07-13 02:00:00","2014-07-13 03:00:00","2014-07-13 04:00:00","2014-07-13 05:00:00","2014-07-13 06:00:00","2014-07-13 07:00:00","2014-07-13 08:00:00","2014-07-13 09:00:00","2014-07-13 10:00:00","2014-07-13 11:00:00","2014-07-13 12:00:00","2014-07-13 13:00:00","2014-07-13 14:00:00","2014-07-13 15:00:00","2014-07-13 16:00:00","2014-07-13 17:00:00","2014-07-13 18:00:00","2014-07-13 19:00:00","2014-07-13 20:00:00","2014-07-13 21:00:00","2014-07-13 22:00:00","2014-07-13 23:00:00"],"data":[1,1,0,1,0,0,0,1,0,0,7,6,3,4,4,10,8,9,7,12,5,8,2,0]},{"name":"Something 2","category1":["2014-07-13 00:00:00","2014-07-13 01:00:00","2014-07-13 02:00:00","2014-07-13 03:00:00","2014-07-13 04:00:00","2014-07-13 05:00:00","2014-07-13 06:00:00","2014-07-13 07:00:00","2014-07-13 08:00:00","2014-07-13 09:00:00","2014-07-13 10:00:00","2014-07-13 11:00:00","2014-07-13 12:00:00","2014-07-13 13:00:00","2014-07-13 14:00:00","2014-07-13 15:00:00","2014-07-13 16:00:00","2014-07-13 17:00:00","2014-07-13 18:00:00","2014-07-13 19:00:00","2014-07-13 20:00:00","2014-07-13 21:00:00","2014-07-13 22:00:00","2014-07-13 23:00:00"],"data":[1,1,1,1,0,0,0,0,2,1,4,2,3,2,4,3,4,6,3,5,3,5,2,1]}]
which is later be used by my example.html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Diagram</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("data.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Something and Anything',
x: -20 //center
},
subtitle: {
text: 'bla bla bla',
x: -20
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 30,
formatter: function() {
return Highcharts.dateFormat('%l%p', Date.parse(this.value +' UTC'));
}
}
},
yAxis: {
title: {
text: 'Orders'
},
plotLines: [{
value: 0,
width: 0,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +':00 => '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
y: 100,
borderWidth: 0
},
series: json
});
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- Bla Bla Bla Highcharts Container -->
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
so far so good - what I finally want to add is the possibility of adding a datepicker now.
My "data.php" file is already able to handle a "Date" Parameter:
data.php?dateParam=2014-05-08
But still I'm not finding a valid way to add the datepicker into my code.
Also wanted to let you know that I'm pretty new to JS and aware of the fact
that this script could have been written way better...
So long and thanks for all the cheese,
Jo3rg

A few tips
if you use categories, dateFormat will not work, it is based on timestamp
you should set type of xAxis (i.e category) or datetime
if you use datetime, your dates should be parsed to timestamp (Date.UTC functon or Date.parse()
in the series you should define which data is used, becuase your json is invalid (incorrect structure for highcharts)

Related

HighCharts add space to Y-Axis Label gutter

I have created a chart using the HighCharts javascript library, the problem I have is that my y-Axis labels are cut by the Y-Axis vertical line. I would like to add more space in the y-axis label gutter area to allow for the labels to be fully visible and so i can add some annotations to the in that area, see image below:
Ideally I would like to add 40px, to the Y-Axis gutter. I have read through the api reference and tried using "yAxis.labels.padding", "yAxis.margin" and "yAxis.offset".
My code is as follows:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
#container {
height: 400px;
width: 350px;
}
.highcharts-tick{display: none;}
.highcharts-grid-line{opacity: 0.2}
</style>
</head>
<body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script src="https://code.highcharts.com/stock/modules/accessibility.js"></script>
<div id="container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id=container2></div>
<script type="text/javascript">
$(function() {
const options = {
chart: {
backgroundColor: '#1B191B', // Background Color
type: 'line',
zoomType: "",
},
rangeSelector : {
enabled: false,
selected : 2,
inputEnabled: false
},
title: {
text: 'APPLE INC', // Title of the Chart
align: 'left',
style: {
color: '#dedbde', // Custom CSS for the title
fontWeight: 'bold'
}
},
scrollbar: { enabled: false },
exporting: {
enabled: false
},
yAxis: {
lineWidth: 2,
tickWidth: 1,
labels: {
style: {
color: '#dedbde'
},
align: 'right',
},
opposite: true,
offset: -1
},
xAxis: {
labels: {
style: {
color: '#dedbde'
}
},
gridLineWidth: 1,
},
navigator: {
enabled: false
},
series: [{
name: 'AAPL Stock Price',
data: [],
type: 'areaspline',
threshold: null,
color: '#5861B3',
tooltip: {
valueDecimals: 2
},
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
}
}]
}
const url = 'https://demo-live-data.highcharts.com/aapl-c.json'
const chart = Highcharts.stockChart('container', options)
$.getJSON(url, function(data) {
chart.series[0].setData(data)
// Execute callback
if (chart.options.chart.events && chart.options.chart.events.dataLoad) {
const dataLoad = chart.options.chart.events.dataLoad.bind(chart)
dataLoad(data)
}
})
})
</script>
</body>
</html>
Been banging my head around this for while, but I cant seem to figure it out any help would be very much appreciated. Thanks
In Highstock, the yAxis is inverted by default, so aligning the labels is reversed as well.
The only thing you need to change is setting yAxis.labels.align to 'left'.
Demo:
https://jsfiddle.net/BlackLabel/10ae8g9d/

Javascript Code not running in Wordpress Pages

EDIT here is the error from the console https://imgur.com/a/OvP9cRr
I want to run a bit of code in a Wordpress Pages which works in jsfiddle. https://jsfiddle.net/w9ta5x2e/.
I am just putting my code in the editor and I don't see anything. However the script will run if its something simple like: courtesy of https://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_inner_html
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>
</body>
</html>
I don't know how to create a .js file, it's a university setup wordpress site so I doubt I have much control with the root.
I can't make files on my Wordpress website, it is managed by a university and it doesn't allow me to
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
jQuery(function() {
$.getJSON(
'https://cdn.jsdelivr.net/gh/highcharts/highcharts#v7.0.0/samples/data/usdeur.json',
function (data) {
Highcharts.chart('container', {
chart: {
zoomType: 'x'
},
title: {
text: 'USD to EUR exchange rate over time'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Exchange rate'
}
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'USD to EUR',
data: data
}]
});
}
);
});
</script>
Wordpress usually runs jQuery in noConflict mode making $ undefined
Try changing
jQuery(function() {// $ undefined here
To
jQuery(function($) { // $ is jQuery here

Highcharts and PHP [duplicate]

This question already has answers here:
How to add PHP array to JS array in Highcharts
(5 answers)
Closed 6 years ago.
I was trying to pull data from DB to Highcharts polar chart, and when I try to load it on browser I get this error in the browser's inspector tools:
SyntaxError: missing } after property list on Line 78
This is the code I've used.
EDIT: IVE PUT DIFFERENT CODE FIRST TIME
<?php
$connection = mysqli_connect("localhost","root","","uwguru");
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
polar: true,
type: 'line'
},
title: {
text: 'Muscle Summary',
x: -80
},
pane: {
size: '80%'
},
xAxis: {
categories: [
<?php
$sql="SELECT * FROM exercises";
$result= mysqli_query($connection,$sql);
while ($registros = mysqli_fetch_array($result))
{
?>
<?php echo $registros['main_muscle']?>,
<?php
}
?>
],
tickmarkPlacement: 'on',
lineWidth: 0
},
yAxis: {
gridLineInterpolation: 'polygon',
lineWidth: 0,
min: 0
},
tooltip: {
shared: true,
pointFormat: '<span style="color:{series.color}">{series.name}: <b>${point.y:,.0f}</b><br/>'
},
legend: {
align: 'right',
verticalAlign: 'top',
y: 70,
layout: 'vertical'
},
series: [{
name: 'Test',
data: [
<?php
$sql="SELECT * FROM exercises";
$result= mysqli_query($connection,$sql);
while ($registros = mysqli_fetch_array($result))
{
?>
<?php echo $registros['muscle_string']?>,
<?php
}
?>
]
pointPlacement: 'on'}],
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/highcharts-more.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; max-width: 600px; height: 400px; margin: 0 auto"></div>
</body>
</html>
RENDERED SOURCE CODE
<
!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
polar: true,
type: 'line'
},
title: {
text: 'Muscle Summary',
x: -80
},
pane: {
size: '80%'
},
xAxis: {
categories: [
["1","14","13","1","14","1","7","9","16"]
],
tickmarkPlacement: 'on',
lineWidth: 0
},
yAxis: {
gridLineInterpolation: 'polygon',
lineWidth: 0,
min: 0
},
tooltip: {
shared: true,
pointFormat: '<span style="color:{series.color}">{series.name}: <b>${point.y:,.0f}</b><br/>'
},
legend: {
align: 'right',
verticalAlign: 'top',
y: 70,
layout: 'vertical'
},
series: [{
name: 'Test',
data: [
["6","745","7547","4","5","1","2","634234","325235"]
]
pointPlacement: 'on'}
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/highcharts-more.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; max-width: 600px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Check the output of your while loop.
Also, consider building your array and outputting it to JSON using json_encode().
Note that you will still have to parse the JSON on the JavaScript side. If you are going to mix javascript and PHP, it's usually better practice output the JS data separately (like as a variable above the JS logic) and then parse it where you need it. It makes maintaining the code in the future a lot easier.
<?php
// put this in above the `$('#container').highcharts({` line
//and you can access it as a proper JS variable as you need to.
$sql="SELECT * FROM exercises";
$result= mysqli_query($connection,$sql);
$output = [];
while ($registros = mysqli_fetch_array($result)) {
$output[] = $registros['muscle_string'];
}
echo "var muscleString = JSON.parse('".json_encode($output)."');";
?>
That said, the error you are getting is that you probably need this:
series: [{
name: 'Test',
data: [
["6","745","7547","4","5","1","2","634234","325235"]
]
pointPlacement: 'on'}
To ultimately look like this:
series: [{
name: 'Test',
data: [
["6","745","7547","4","5","1","2","634234","325235"]
], // <-- add comma here
pointPlacement: 'on'
}] // <-- close your array with a closing square bracket

Dyanamic highchart with csv/txt input file

I am new on highchart. I have gone through the help portal of this and I am unable to fulfill my requirement so need you help/guide to complete this task .
My task is to read the data from a csv/TXT file which contains TPS details as per below format and show it on a dynamic running chart ( it's ok if the chart will refresh in one minute ) .
DATA format:
16:08:02,3
16:08:04,5
16:08:05,1
16:09:01,10
The above file is appending on every second , will read the last one minute data from file and plot this on chart .
I have tried this using below code. Don't know what I am missing.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>TPS Example</title>
<script type="text/javascript" src="C:/Backup/SUNIL/Software/library/jquery-2.2.0.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'TPS Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 3,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});
</script>
</head>
<body>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<div id="container" style="min-width: 50px; height: 200px; margin: 0 auto"></div>
</body>
</html>
You probably have incorrect paths to your script files.
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
The code works fine: http://jsfiddle.net/tmp3pty2/

HighCharts - Getting chart to display - Simple example (markit API)

I am new to programming with JavaScript and am having some troubles implementing a HighCharts chart. The API I am using is markit (https://github.com/markitondemand/DataApis/blob/master/MarkitTimeseriesServiceSample.js) to produce a chart as shown halfway down this page http://dev.markitondemand.com/
Now I thought I had to add that js script in place of the js shown in this fiddle (http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-basic/) but it doesn't seem to be working.
I think it may be because I am not assigning where I actually want to put it but I am not 100% sure.
Please see below for my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script>
/**
* Version 1.1, Jan 2012
*/
var Markit = {};
/**
* Define the TimeseriesService.
* First argument is symbol (string) for the quote. Examples: AAPL, MSFT, JNJ, GOOG.
* Second argument is duration (int) for how many days of history to retrieve.
*/
Markit.TimeseriesService = function(symbol,duration){
this.symbol = symbol;
this.duration = duration;
this.PlotChart();
};
Markit.TimeseriesService.prototype.PlotChart = function(){
//Make JSON request for timeseries data
$.ajax({
beforeSend:function(){
$("#chartDemoContainer").text("Loading chart...");
},
data: {
symbol: this.symbol,
duration: this.duration
},
url: "http://dev.markitondemand.com/Api/Timeseries/jsonp",
dataType: "jsonp",
context: this,
success: function(json){
//Catch errors
if (!json.Data || json.Message){
console.error("Error: ", json.Message);
return;
}
this.BuildDataAndChart(json);
},
error: function(){
alert("Couldn't generate chart.");
}
});
};
Markit.TimeseriesService.prototype.BuildDataAndChart = function(json){
var dateDS = json.Data.SeriesDates,
closeDS = json.Data.Series.close.values,
openDS = json.Data.Series.open.values,
closeDSLen = closeDS.length,
irregularIntervalDS = [];
/**
* Build array of arrays of date & price values
* Market data is inherently irregular and HighCharts doesn't
* really like irregularity (for axis intervals, anyway)
*/
for (var i=0; i<closeDSLen;i++){
var dat = new Date(dateDS[i]);
var dateIn = Date.UTC(dat.getFullYear(), dat.getMonth(), dat.getDate());
var val = closeDS[i];
irregularIntervalDS.push([dateIn,val]);
}
//set dataset and chart label
this.oChartOptions.series[0].data = irregularIntervalDS;
this.oChartOptions.title.text = "Price History of " + json.Data.Name + " (1 year)";
//init chart
new Highcharts.Chart(this.oChartOptions);
};
//Define the HighCharts options
Markit.TimeseriesService.prototype.oChartOptions = {
chart: {
renderTo: 'chartDemoContainer'
},
title:{},
subtitle: {
text: 'Source: Thomson Reuters DataScope / Markit On Demand'
},
xAxis: {
type: 'datetime'
},
yAxis: [{ // left y axis
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}, { // right y axis
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}],
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
marker: {
lineWidth: 1
}
}
},
series: [{
name: "Close price",
lineWidth: 2,
marker: {
radius: 0
}
}]
//,credits:{ enabled:false },
};
new Markit.TimeseriesService("GOOG", 365);
/**
* Need help? Visit the API documentation at:
* http://dev.markitondemand.com
*/
</script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Thanks a lot for the help.
In your <div> change the id to #chartDemoContainer
Replace your jQuery libraries with these,
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
And here's a working version of your example - http://jsbin.com/behicetivi/edit?html,output
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script>
/**
* Version 1.1, Jan 2012
*/
var Markit = {};
/**
* Define the TimeseriesService.
* First argument is symbol (string) for the quote. Examples: AAPL, MSFT, JNJ, GOOG.
* Second argument is duration (int) for how many days of history to retrieve.
*/
Markit.TimeseriesService = function(symbol,duration){
this.symbol = symbol;
this.duration = duration;
this.PlotChart();
};
Markit.TimeseriesService.prototype.PlotChart = function(){
//Make JSON request for timeseries data
$.ajax({
beforeSend:function(){
$("#chartDemoContainer").text("Loading chart...");
},
data: {
symbol: this.symbol,
duration: this.duration
},
url: "http://dev.markitondemand.com/Api/Timeseries/jsonp",
dataType: "jsonp",
context: this,
success: function(json){
//Catch errors
if (!json.Data || json.Message){
console.error("Error: ", json.Message);
return;
}
this.BuildDataAndChart(json);
},
error: function(){
alert("Couldn't generate chart.");
}
});
};
Markit.TimeseriesService.prototype.BuildDataAndChart = function(json){
var dateDS = json.Data.SeriesDates,
closeDS = json.Data.Series.close.values,
openDS = json.Data.Series.open.values,
closeDSLen = closeDS.length,
irregularIntervalDS = [];
/**
* Build array of arrays of date & price values
* Market data is inherently irregular and HighCharts doesn't
* really like irregularity (for axis intervals, anyway)
*/
for (var i=0; i<closeDSLen;i++){
var dat = new Date(dateDS[i]);
var dateIn = Date.UTC(dat.getFullYear(), dat.getMonth(), dat.getDate());
var val = closeDS[i];
irregularIntervalDS.push([dateIn,val]);
}
//set dataset and chart label
this.oChartOptions.series[0].data = irregularIntervalDS;
this.oChartOptions.title.text = "Price History of " + json.Data.Name + " (1 year)";
//init chart
new Highcharts.Chart(this.oChartOptions);
};
//Define the HighCharts options
Markit.TimeseriesService.prototype.oChartOptions = {
chart: {
renderTo: 'chartDemoContainer'
},
title:{},
subtitle: {
text: 'Source: Thomson Reuters DataScope / Markit On Demand'
},
xAxis: {
type: 'datetime'
},
yAxis: [{ // left y axis
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}, { // right y axis
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}],
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
marker: {
lineWidth: 1
}
}
},
series: [{
name: "Close price",
lineWidth: 2,
marker: {
radius: 0
}
}]
//,credits:{ enabled:false },
};
new Markit.TimeseriesService("GOOG", 365);
/**
* Need help? Visit the API documentation at:
* http://dev.markitondemand.com
*/
</script>
</head>
<body>
<div id="chartDemoContainer" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>

Categories