brighter-trading/static/communication.js

79 lines
2.6 KiB
JavaScript

class Communication {
constructor(interval, ocu, occ, oiu) {
// Register callbacks
this.on_candle_update = ocu;
this.on_candle_close = occ;
this.on_indctr_update = oiu;
// Open connections.
this.set_app_con();
this.set_exchange_con(interval);
}
candle_update(new_candle){
this.on_candle_update(new_candle);
}
candle_close(new_candle){
// Send a copy of the data to the server
this.app_con.send( JSON.stringify({ message_type: "candle_data", data :new_candle }));
this.on_candle_close(new_candle);
}
indicator_update(data){
this.this.on_indctr_update(data);
}
set_app_con(){
// Create a web socket connection to our app.
this.app_con = new WebSocket('ws://localhost:5000/ws');
this.app_con.onopen = () => this.app_con.send("Connection OK");
this.app_con.addEventListener('message', ev => {
if(ev.data){
// Get the message received from server
let msg = JSON.parse(ev.data)
// Handle a request from the server
if (msg.request) {
//handle request
console.log('Received a request from the server');
console.log(msg.request);
}
// Handle a reply from the server
if (msg.reply) {
// Handle indicator updates
if (msg.reply == 'i_updates'){
// console.log(msg.data);
this.indicator_update(msg.data)
}
}
}
})
}
set_exchange_con(interval){
let ws = "wss://stream.binance.com:9443/ws/btcusdt@kline_" + interval;
this.exchange_con = new WebSocket(ws);
// Set the on-message call-back for the socket
this.exchange_con.onmessage = (event) => {
// Convert message to json obj
let message = JSON.parse(event.data);
// Isolate the candle data from message
let candlestick = message.k;
//console.log(message.k)
// Reformat data for lightweight charts
let new_candle={
time: candlestick.t / 1000,
open: candlestick.o,
high: candlestick.h,
low: candlestick.l,
close: candlestick.c,
vol: candlestick.v
};
// Update frequently updated objects
this.candle_update(new_candle);
// Update less frequently updated objects.
if (candlestick.x == true) { this.candle.close(new_candle); }
}
}
}