Chart.js Show BTC Price
Websocket simple sample for Get BTC Price from Bitfinex
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: 'BTC',
data: datas,
backgroundColor: "rgba(255,199,0,0.3)"
}]
}
});
var timeFormat = 'HH:mm:ss';
var websocket = new WebSocket( "wss://api.bitfinex.com/ws");
websocket.onopen = function() {
var sendObj={event:"subscribe",channel:"ticker",pair:"BTCUSD"};
websocket.send(JSON.stringify(sendObj));
};
websocket.onmessage = function(str) {
if(yAxis.length>10){
yAxis.shift();
}
if(datas.length>10){
datas.shift();
}
if(JSON.parse(str.data).length>2){
yAxis.push(new moment().format(timeFormat));
datas.push(JSON.parse(str.data)[1]);
}
lineChart.update();
};