javascript - 从 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
}
解决方案
在 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
推荐阅读
- html - 使用填充在悬停时为图像添加边框
- android - 如何从 ArrayAdapter 类的内部匿名类调用 startActivity?
- ios - 核心图像内核语言中的纹理(iChannel0,vec2)等价是什么?
- ios - 如何查看 iOS 应用程序文档目录的内容?
- css - Fluent Design 卡片提升效果
- html - 两个div在同一行
- asp.net-mvc - 使用书签和链接将 Html 表导出到 Word
- r - R:df 标题列是序数排名,并在每个观察的列中分布
- haskell - 为什么这不是受限制的单子限制的情况?
- mongodb - 如何在 dockerfile 模式下设置 Mongo 副本集