Fetch data from Binance API to Javascript Array - javascript

I just started to work with API's and got a little bit confused of how can I transfer the data which I receive to a JavaScript array.
I have this code which receive the data from Binance API and show it in console.
var burl ='https://api.binance.com';
var query ='/api/v3/klines';
query += '?symbol=BTCUSDT&interval=15m&limit=2';
var url = burl + query;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
console.log(ourRequest.responseText);
}
ourRequest.send();
I also have a hard-scripted chart from FusionCharts Library.
The source code of a chart is here - FusionChart Candlestick Chart
const dataSource = {
chart: {
caption: "Bitcoin Price",
subcaption: "Q4-2017",
numberprefix: "$",
pyaxisname: "Price (USD)",
showvolumechart: "1",
vnumberprefix: "$",
vyaxisname: "Volume traded",
exportenabled: 1,
theme: loadedTheme || ThemeAliases.light
},
categories: [
{
category: [
{
label: "Jan",
x: "1"
},
{
label: "Feb",
x: "32"
},
{
label: "Mar",
x: "62"
},
{
label:"Apr",
x:"12"
}
]
}
],
dataset: [
{
data: [
{
tooltext:
"<b>Oct 01, 2017</b><br>Open: <b>$openDataValue</b><br>Close: <b>$closeDataValue</b><br>High: <b>$highDataValue</b><br>Low: <b>$lowDataValue</b><br>Volume: <b>$volumeDataValue</b>",
open: 4341.05,
high: 4403.74,
low: 4269.81,
close: 4403.74,
volume: 1208210000,
x: 1
},
FusionCharts.ready(function() {
var myChart = new FusionCharts({
type: "candlestick",
renderAt: "chart-container",
width: "75%",
height: "100%",
dataFormat: "json",
dataSource
}).render();
});

The result ourRequest.responseText is returned as a string, and not as an array. To fix it, simply use the JSON.parsemethod. You also store it in a variable, example :
var burl ='https://api.binance.com';
var query ='/api/v3/klines';
query += '?symbol=BTCUSDT&interval=15m&limit=2';
var url = burl + query;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
// Will convert the string to something Javascript can understand
var result = JSON.parse(ourRequest.responseText);
// You can now use it as an array
console.log(result);
}
ourRequest.send();
Does that answer the question?

Related

Cant display data from JSON in canvasjs

hi and sorry for silly question i miss some part of code and cant figure it out, I did from this lesson https://canvasjs.com/javascript-charts/json-data-api-ajax-chart/ and when I'm editing code to put my json api and values nothing happens....(values from json are telemetry only 'timestamp' and 'cpu' value)
my code is :
window.onload = function() {
var dataPoints = [];
var cpuPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "consume timeline"
},
axisY: {
title: "cpu use",
titleFontSize: 24,
},
data: [{
type: "column",
yValueFormatString: "#,### Units",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: new Date(data[i].timestamp),
y: data[i].cpu
});
}
chart.render();
}
$.getJSON("http://192.168.13.60:12345/api/metric/cpu", addData);
}
please can somebody help me figure it out. I think i miss some variable to declare

all series on a given axis must be of the same data type .google chart api error

i am using google chart api in which i am fetching values from json .i am sharing my javascript with json here.its giving me error like it must be same data type but as for my knowledge it is of same type.
function drawChart2() {
var jsa = [
{
"date": "01-APR-16",
"creditCardCount": 3,
"invoiceCount": 1
},
{
"date": "06-APR-16",
"creditCardCount": 2,
"invoiceCount": 3
},
{
"date": "29-MAR-16",
"creditCardCount": 3,
"invoiceCount": 1
},
{
"date": "30-MAR-16",
"creditCardCount": 4,
"invoiceCount": 3
},
{
"date": "31-MAR-16",
"creditCardCount": 1,
"invoiceCount": 1
}
]
var outputArrayForInvoiceAndCredit = new Array();
// header
var headerArray1 = ['Day', 'CreditCard', 'Invoice'];
outputArrayForInvoiceAndCredit.push(headerArray1);
for (var i = 0; i < jsa.length; i++){
var obj1 = jsa[i];
var innerArray = new Array();
innerArray[0] = obj1.date;
innerArray[1] = obj1.creditCardCount;
innerArray[2] = obj1.InvoiceCount;
outputArrayForInvoiceAndCredit.push(innerArray);
}
var data2 = google.visualization.arrayToDataTable(outputArrayForInvoiceAndCredit);
var options2 = {
title: 'CreaditCard/Invoice Details',
curveType: 'function',
legend: {
position: 'bottom'
}
};
var chart2 = new google.visualization.LineChart(document.getElementById('cc/invoice'));
chart2.draw(data2, options2);
}
meanwhile if i use it without json it is working fine
below is the script which works fine
function drawChart3() {
var data3 = google.visualization.arrayToDataTable([
['Day', 'Sales','exp'],
['4-APRIL-16', 1000,200],
['5-APRIL-16', 1170,300],
['6-APRIL-16', 660,400],
['7-APRIL-16', 1030,500]
]);
var options3 = {
title: 'Company Performance',
curveType: 'function',
legend: {
position: 'bottom'
}
};
var chart3 = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart3.draw(data3, options3);
}
can anyone help me into this.Thank you

File loading a Csv file into highcharts

I'm plotting Csv column data in highcharts. Instead of the:
$.get('5.csv', function(data)
I want input a local desktop Csv file using:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
My current Javascript code is below :
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {
text: 'Test'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units',
}
},
series: []
};
// $.get('5.csv', function(data) {
var file = event.target.file;
var reader = new FileReader();
var txt=reader.readAsText(file);
var lines = txt.split('\n');
var c = [], d = [];
$.each(lines, function(lineNo, line) {
if(lineNo > 0 ){
var items = line.split(',');
var strTemp = items[0];
c = [parseFloat(items[0]), parseFloat(items[1])];
d.push(c);
console.log(c);
}
});
options.xAxis.categories = c;
options.series = [{
data: d
}];
chart = new Highcharts.Chart(options);
});
How would I go about doing this ? I want to upload a Csv file from a local desktop machine. How do I link the File Reader upload of the file to highcharts to plot, instead of using the $.get(5.csv', function(data) { ? Or am I better using jquery-csv (https://github.com/evanplaice/jquery-csv). I know there are browser security issues. My file is a 3 column Csv with a one line header, column 1 is the x-axis, 2 is the y-axis, 3 will be the error bar, which I haven't yet implemented:
Q,I,E
0.009,2.40E-01,5.67E-02
0.011,2.13E-01,3.83E-02
0.013,2.82E-01,2.28E-02
etc ....
This works now upload by File API
function processFiles(files) {
var chart;
options = {
chart: {
zoomType: 'x',
renderTo: 'container',
type: 'line',
zoomType: 'x'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
type: 'linear',
minorTickInterval: 0.1,
title: {
text: 'Q'}
},
yAxis: {
type: 'linear',
minorTickInterval: 0.1,
title: {
text: 'I(ntensity)'
},
},
tooltip: {
shared: true
},
legend: {
enabled: true
},
plotOptions: {
area: {
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, Highcharts.getOptions().colors[0]],
[0, 'rgba(2,0,0,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 5
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
series: [{
name: 'Series'}]
};
var file = files[0]
var reader = new FileReader();
reader.onload = function (e) {
str = e.target.result;
var lines = str.split("\n");
var c = [], d = [], er = [];
$.each(lines, function(lineNo, line) {
if(lineNo > 0 ){
var items = line.split(',');
var strTemp = items[0];
er = parseFloat(items[2])
a = parseFloat(items[0])
b = parseFloat(items[1])
min = (b - (er/2))
max = b + ((er/2))
c = [a , b];
var q = [], e = [];
q = [min, max]
e.push(q);
d.push(c);
console.log(c);
console.log(q);
}
});
options.xAxis.categories = c.name;
lineWidth: 1
options.series = [{
data: d,
type: 'scatter'
}, {
name: 'standard deviation',
type: 'errorbar',
color: 'black',
data : e }
];
$("#Linear").click(function(){
$('#container').highcharts().yAxis[0].update({ type: 'linear'});
});
$("#Log").click(function(){
$('#container').highcharts().yAxis[0].update({ type: 'logarithmic'});
});
$("#Guinier").click(function(){
$('#container').highcharts().yAxis[0].update({ data: Math.log(d)});
options.xAxis.categories = c.name;
lineWidth: 1
options.series = [{
data: d
}]
});
chart = new Highcharts.Chart(options);
}
reader.readAsText(file)
var output = document.getElementById("fileOutput")
};
Due to security reasons you can't load a file directly on the client-side
To do this you need to use the HTML5 File API which will give the user a file dialog to select the file.
If you plan to use jquery-csv here's an example that demonstrates how to do that.
File Handling Demo
I'm biased but I say use jquery-csv to parse the data, trying to write a CSV parser comes with a lot of nasty edge cases.
Source: I'm the author of jquery-csv
As an alternative, if jquery-csv doesn't meet your needs, PapaParse is very good too.

In jqxGrid, how do I add a new calculated column from JSON data?

In jqxGrid, how do I add a new calculated column from JSON data?
My JSON data has fields baseQuantity and unitCost. I want to add a new field called totalCost which would be baseQuantity * unitCost.
I'm trying to add the data using loadComplete, but it doesn't seem to work.
ANOTHER alternative I could do is to loop through objData and inject a new field with the calculated value. But aside from that, is there any way I could do it via jqxGrid's API?
var jsonString = [{ "baseQuantity":"1", "unitCost":"2"}, { "baseQuantity":"3", "unitCost":"4"}];
var objData = $.parseJSON(jsonString);
var srcData = {
datatype: "json",
datafields: [
{ name : 'baseQuantity', type : 'number' },
{ name : 'unitCost', type : 'number' }
],
localdata : objData
};
var adapterData = new $.jqx.dataAdapter(srcData, {
loadComplete: function (records) {
var modifiedDataArray = new Array();
for (var i = 0; i < records.length; i++) {
var modifiedData = records[i];
modifiedData.totalPayment = modifiedData.baseQuantity * modifiedData.unitCost;
modifiedDataArray.push(programme);
}
return modifiedDataArray;
}
});
$('div#jqxGrid').jqxGrid({
width: '100%',
source: adapterData,
theme: getTheme(),
pageable: true,
autoheight: true,
sortable: true,
altrows: true,
columns: [
{ datafield: 'baseQuantity', text: 'Base Qty.', width: 120 }
{ datafield: 'unitCost', text: 'Unit Payment' , width: 120 }
]
});
Use the cellrenderer function:
http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxgrid/jquery-grid-api.htm
{ text: 'totalCost', datafield: 'totalCost', width: 70, cellsalign: 'right', columntype: 'number',
cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
var rowData = $("#jqxGrid").jqxGrid('getrowdata', row);
return rowData.baseQuantity * rowData.unitCost;
}
}
Don't use the event "loadComplete" but "beforeLoadComplete" instead. Here is an example :
var dataAdapter = new $.jqx.dataAdapter(source,
{
beforeLoadComplete: function (records) {
records[0]['firstname'] = "Michael";
return records;
}
}
);
Than you can loop through all records, and generate you computed column. This is the official solution they seems to give here : http://www.jqwidgets.com/community/topic/computed-column/

Unable to plot data json data on highcharts

I am trying to load json data to high-charts. I am receiving json data from DB using $.getJSON function. Here is my sample json that i am receiving from DB,
My sample json
[
{
"target":"collectd.matrix.oracle.avg_resp_time","datapoints":[[8.0, 1365158480],[null, 1365158490],[null, 1365158500],[null, 1365158510],[null, 1365158520],[null,1365158530],[8.0, 1365158540],[null, 1365158550],[null, 1365158560],[null, 1365158570],[null, 1365158580],[null, 1365158590]]
}
]
$.getJSON("myURL", createOrderDurationChart);
On success response from $.getJSON i call function below,
I am using scala framework.
I am not getting what is wrong in code or json. I can plot this json by embedding code in simple javascript and run through html directly as sample.
Here is the sample code,
function createOrderDurationChart(durationMap){
//var target=durationMap[0].target;
//var jsonstr=durationMap[0].datapoints;
//alert(target);
//alert(jsonstr);
var orderDurationChart = new Highcharts.Chart({
chart: {
renderTo: "order_duration_div",
type: "column",
margin: [10, null, null, null],
//marginRight: 10,
zoomType: 'xy',
},
title: {
text: "order duration"
//y: 5
},
xAxis: {
type: "datetime",
//tickInterval: 60*1000*10
},
yAxis: {
title: {
text: "seconds"
},
startOnTick : false,
endOnTick: false
},
series: [{
name:"avg",
data: (function (){
var data = [], i;
var jsondata = [];
jsondata= durationMap[0].datapoints;
alert(jsondata)
var datapoints=JSON.parse(jsondata);
// var jsonstr=parsejson[0].datapoints;
console.log('jsotn ' + datapoints);
// var mydata = JSON.parse(jsonstr);
// alert(mydata);
// datapoints = mydata[0].datapoints;
//alert("initial:" + json[0].time + ':' + json[0].value);
for (i = 0; i < datapoints.length; i++) {
data.push({
x:datapoints[i][1],
y:datapoints[i][0]
});
console.log('x: ' + datapoints[i][1] + ', y: ' + datapoints[i][0]);
}
return data;
})
()}]
});
}
Update code after json fix,
function createOrderDurationChart(durationMap){
//var target=durationMap[0].target;
//var jsonstr=durationMap[0].datapoints;
//alert(target);
//alert(jsonstr);
var orderDurationChart = new Highcharts.Chart({
chart: {
renderTo: "order_duration_div",
type: "column",
margin: [10, null, null, null],
//marginRight: 10,
zoomType: 'xy',
},
title: {
text: "order duration"
//y: 5
},
xAxis: {
type: "datetime",
//tickInterval: 60*1000*10
},
yAxis: {
title: {
text: "seconds"
},
startOnTick : false,
endOnTick: false
},
series: [{
name:"avg",
data: (function (){
var data = [], i;
var jsondata = [];
datapoints= durationMap[0].datapoints;
console.log('jsotn ' + datapoints);
for (i = 0; i < datapoints.length; i++) {
data.push({
x:datapoints[i][1],
y:datapoints[i][0]
});
console.log('x: ' + datapoints[i][1] + ', y: ' + datapoints[i][0]);
}
return data;
})
()}]
});
}
Any suggestions most welcome.
Thanks

Categories

Resources