Hey so I've been playing around with JavaScript learning in my free time and had a quick question. I am using websockets to look at crypto prices as shown in the code below:
let ethws = new WebSocket('wss://stream.binance.com:9443/ws/ethusdt@trade');
let btcws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let ethstockPriceElement = document.getElementById('eth-stock-price')
let btcstockPriceElement = document.getElementById('btc-stock-price')
let ethlastPrice = null;
let btclastPrice = null;
ethws.onmessage = (event) => {
let ethstockObject = JSON.parse(event.data)
let ethprice = parseFloat(ethstockObject.p).toFixed(2)
ethstockPriceElement.innerText = ethprice
ethstockPriceElement.style.color = !ethlastPrice || ethlastPrice === ethprice ? 'black' : ethprice > ethlastPrice ? 'green' : 'red';
ethlastPrice = ethprice
}
btcws.onmessage = (event) => {
let btcstockObject = JSON.parse(event.data)
let btcprice = parseFloat(btcstockObject.p).toFixed(2)
btcstockPriceElement.innerText = btcprice
btcstockPriceElement.style.color = !btclastPrice || btclastPrice === btcprice ? 'black' : btcprice > btclastPrice ? 'green' : 'red';
btclastPrice = btcprice
}
I was wanting to use push the price into an "updating" variable outside of the event so I could do something like 2btc price 3eth price then btcprice + ethprice to get a total live updating price of 2btc and 3eth. However I am unable to use the data outside of the event. What would be the best way to achieve this?