How to get open, baseAssetVolume of a json. I'm working with Binance NodeJs package, and I'll like to query open
and other values.
This is the code from the site docs to get the full data
const api = require('binance');
const binanceWS = new api.BinanceWS(true);
const streams = binanceWS.streams;
binanceWS.onCombinedStream(
[
streams.ticker('BNBBTC')
],
streamEvent => {
switch (streamEvent.stream) {
case streams.ticker('BNBBTC'):
console.log(
'Ticker event, update market stats\n',
streamEvent.data
);
break;
}
}
);
This is the data returned.
{
eventType: '24hrTicker',
eventTime: 1619369591449,
symbol: 'BNBBTC',
priceChange: '0.00014790',
priceChangePercent: '1.474',
weightedAveragePrice: '0.01006976',
previousClose: '0.01003790',
currentClose: '0.01018500',
closeQuantity: '40.36000000',
bestBid: '0.01018460',
bestBidQuantity: '7.55000000',
bestAskPrice: '0.01018500',
bestAskQuantity: '58.91000000',
open: '0.01003710',
high: '0.01026090',
low: '0.00977950',
baseAssetVolume: '401687.43000000',
quoteAssetVolume: '4044.89583374',
openTime: 1619283191026,
closeTime: 1619369591026,
firstTradeId: 136462988,
lastTradeId: 136653082,
trades: 190095
}
In node.js, you can declare variables using let
and declare constants using const
. You can access properties of an object with a dot, as well as like an array key.
switch (streamEvent.stream) {
case streams.ticker('BNBBTC'):
// declaring constant, accessing the `open` property with a dot
const open = streamEvent.data.open;
// declaring variable, accessing the property as it was an array key
let baseAssetVolume = streamEvent.data['baseAssetVolume'];
break;
}
You might also run into scoping issues. In Javascript, variables are visible only in the block that created them (in your case streamEvent => {
) and nested blocks.
If you want to access the values in a higher scope, you need to define the variables in the higher scope.
const api = require('binance');
const binanceWS = new api.BinanceWS(true);
const streams = binanceWS.streams;
let open; // declaring the variable here
binanceWS.onCombinedStream(
[
streams.ticker('BNBBTC')
],
streamEvent => {
switch (streamEvent.stream) {
case streams.ticker('BNBBTC'):
open = streamEvent.data.open; // assigning the value here
break;
}
}
);
Mind that the onCombinedStream
event handler is probably going to be executed multiple times, and open = streamEvent.data.open
is going to assign a new value each time it's executed.
To prevent this from happening, you can check whether the value has been already assigned (default value is null
).
/*
* Three equal signs for strict comparison.
* Not necessary in this case, but it's a good practice.
*/
if (open === null) {
open = streamEvent.data.open; // assigning the value here
}
instead of the previous
open = streamEvent.data.open; // assigning the value here