よくやりたくなるのでひな形として残しておく。
ソースをテキストに張り付けてブラウザで開くとグラフが表示される。
サンプルの内容は、BINANCEの直近の取引内容を集計して棒グラフ化するだけ。
ソース
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Sample</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body><canvas id="chart"></canvas></body>
<script>
const ctx = document.getElementById("chart");
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'BTCUSDT',
data: [],
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
}],
},
options: {
title: {
display: true,
text: 'BINANCE TRADES'
},
scales: {
yAxes: [{
ticks: {
suggestedMax: 50,
suggestedMin: 0,
stepSize: 10,
callback: function(value, index, values){
return value;
}
}
}]
},
animation: false,
}
})
function request() {
fetch('https://api.binance.com/api/v3/trades?symbol=BTCUSDT', {
method: 'GET',
// header: {},
// body: '',
// mode: 'cors'
}).then(response => {
if(response.ok) {
return response.json();
} else {
throw new Error(`Request failed: ${response.status}`);
}
}).then(data => {
capture(data)
}).catch(error => {
console.log(error)
});
}
function capture(data){
const aggregated = {};
data.forEach(d => {
const price = Math.round(d.price);
let qty = 0;
if (aggregated[price]) {
qty = aggregated[price];
}
aggregated[price] = Number(qty) + Number(d.qty);
chart.data.labels = Object.keys(aggregated);
chart.data.datasets[0].data = Object.values(aggregated);
chart.update();
})
console.log(aggregated);
setTimeout(request, 3000);
}
request();
</script>
</html>
参考
![](https://mendo.work/wp-content/uploads/cocoon-resources/blog-card-cache/adec6b7fe735d4bf667370b32e75dcc6.png)
フェッチ API の使用 - Web API | MDN
フェッチ API は、リクエストやレスポンスといったプロトコルを操作する要素にアクセスするための JavaScript インターフェイスです。グローバルの fetch() メソッドも提供しており、簡単で論理的な方法で、非同期にネットワーク越しでリソースを取得することができます。
![](https://mendo.work/wp-content/uploads/cocoon-resources/blog-card-cache/10d18bb47b599b5569a0d21c56f77916.png)
Chart.js
Simple yet flexible JavaScript charting library for the modern web
Binance API Documentation