首页 > 解决方案 > 从 Binance Data 中的 json 打开、关闭

问题描述

如何打开,一个json的baseAssetVolume。我正在使用 Binance NodeJs 包,我想查询open和其他值。

这是网站文档中用于获取完整数据的代码

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;
        }
    }
);

这是返回的数据。

   {
  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
}

标签: javascriptnode.jsjsonbinance

解决方案


在 node.js 中,您可以使用声明变量let和使用声明常量const。您可以使用点访问对象的属性,也可以访问数组键。

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;
}

您可能还会遇到范围界定问题。在 Javascript 中,变量仅在创建它们的块(在您的情况下streamEvent => {)和嵌套块中可见。

如果要访问更高范围内的值,则需要在更高范围内定义变量。

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;
        }
    }
);

请注意,onCombinedStream事件处理程序可能会被执行多次,并且open = streamEvent.data.open每次执行时都会分配一个新值。

为防止这种情况发生,您可以检查该值是否已分配(默认值为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
}

而不是以前的

open = streamEvent.data.open; // assigning the value here

推荐阅读