Chart.js Show ETH Price
Websocket simple sample for Get ETC Price from Bitfinex
by no2don
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<div style=" width: 500px;height:500px">
<canvas id="canvas"></canvas>
</div>
JavaScript
//放時間
var yAxis= [];
var datas=[];
var ctx = document.getElementById('canvas').getContext('2d');
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels:yAxis,
datasets: [{
label: 'ETH 價格',
data: datas,
backgroundColor: "rgba(0,199,255,0.5)"
}]
}
});
var timeFormat = 'HH:mm:ss';
// Websocket call bitfinex
var websocket = new WebSocket( "wss://api.bitfinex.com/ws",);
websocket.onopen = function() {
var sendObj={event:"subscribe",channel:"ticker",pair:"ETHUSD"};
websocket.send(JSON.stringify(sendObj));
};
websocket.onmessage = function(str) {
//最多顯示10個
if(yAxis.length>10){
yAxis.shift();
}
if(datas.length>10){
datas.shift();
}
//過濾掉heartbeating
if(JSON.parse(str.data).length>2){
yAxis.push(new moment().format(timeFormat));
datas.push(JSON.parse(str.data)[1]);
}
lineChart.update();
};