let data;
let exchangeName = [], longRate = [], shortRate = [];
fetch("https://fapi.coinglass.com/api/futures/longShortRate?symbol=BTC&timeType=3")
.then(response => response.json()
)
.then (data => {
console.log(data['data'][0]);
for (i = 0; i < data['data'][0]['list'].length; i++) {
longRate[i] = data['data'][0]['list'][i]['longRate'];
shortRate[i] = data['data'][0]['list'][i]['shortRate'];
exchangeName[i] = data['data'][0]['list'][i]['exchangeName'];
}
});
if ($('#sales').length) {
var options = {
series: [{
name: 'Лонг',
data: longRate,
}, {
name: 'Шорт',
data: shortRate,
},
],
chart: {
id: 'longshortratio',
type: 'bar',
height: 350,
stacked: true,
stackType: '100%'
},
plotOptions: {
bar: {
horizontal: true,
},
},
xaxis: {
categories: exchangeName,
labels: {
formatter: function (val) {
return val
}
}
},
};
var chart = new ApexCharts(
document.querySelector("#sales"),
options
);
chart.render();
}
let data,
chart,
result = {longRate: [], shortRate: [], exchangeName: []}, // объявляем сразу как объект
options = { series: [], chart: {}, plotOptions: {}, xaxis: {}}; // тоже объявляем сразу как объект
fetch("https://fapi.coinglass.com/api/futures/longShortRate?symbol=BTC&timeType=3")
.then(response => response.json()
)
.then (data => {
console.log(data['data'][0]);
if(data['data'].length > 0){ // нужно проверить хотя бы так
for (i = 0; i < data['data'][0]['list'].length; i++) {
result.longRate[i] = data['data'][0]['list'][i]['longRate'];
result.shortRate[i] = data['data'][0]['list'][i]['shortRate'];
result.exchangeName[i] = data['data'][0]['list'][i]['exchangeName'];
}
checkSales(result); // вызываем проверку #sales (внутри then )
}else{
console.log('no data');
}
});
function checkSales(result){ // это теперь отдельная функция
if ($('#sales').length) {
options.series: [{ // без var
name: 'Лонг',
data: result.longRate, // < -- result['longRate']
}, {
name: 'Шорт',
data: result.shortRate, // < -- result['shortRate']
},
];
options.chart: {
id: 'longshortratio',
type: 'bar',
height: 350,
stacked: true,
stackType: '100%'
};
options.plotOptions: {
bar: {
horizontal: true,
},
};
options.xaxis: {
categories: result.exchangeName, // < -- result['exchangeName']
labels: {
formatter: function (val) {
return val
}
}
};
chart = new ApexCharts( // без var
document.querySelector("#sales"),
options
);
chart.render();
}
}