88 lines
3.0 KiB
JavaScript
88 lines
3.0 KiB
JavaScript
class Comms {
|
|
constructor(ocu, occ, oiu) {
|
|
// Register callbacks
|
|
this.on_candle_update = ocu;
|
|
this.on_candle_close = occ;
|
|
this.on_indctr_update = oiu;
|
|
}
|
|
|
|
candle_update(new_candle){
|
|
// Call the callback provided.
|
|
this.on_candle_update(new_candle);
|
|
}
|
|
|
|
candle_close(new_candle){
|
|
// Forward a copy of the new candle to the server.
|
|
this.app_con.send( JSON.stringify({ message_type: "candle_data", data :new_candle }));
|
|
// Call the callback provided.
|
|
this.on_candle_close(new_candle);
|
|
}
|
|
|
|
indicator_update(data){
|
|
// Call the callback provided.
|
|
this.on_indctr_update(data);
|
|
}
|
|
|
|
getPriceHistory(){
|
|
let ph = fetch('http://localhost:5000/history').then((r) => r.json()).then( (data) => { return data; } );
|
|
return ph;
|
|
}
|
|
getIndicatorData(){
|
|
let id = fetch('http://localhost:5000/indicator_init').then((r) => r.json()).then( (data) => { return data; } );
|
|
return id;
|
|
}
|
|
send_to_app(message_type, data){
|
|
this.app_con.send( JSON.stringify({ message_type: message_type, data : 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'){
|
|
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;
|
|
// 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); }
|
|
}
|
|
}
|
|
} |