我有一个脚本,该脚本每30分钟间隔从Binance API中获取数据,并在终端中显示。 我想计算阵列中每项资产的平均值。
这是Node-Schedule package- const j = schedule.scheduleJob('* * * * *'
小示例:var array = ["ADABTC", "AEBTC", "AIONBTC"]
我想分别为"ADABTC"
,"AEBTC"
和"KAVABTC"
计算平均值。
完整代码
const { MongoClient } = require('mongodb');
const schedule = require('node-schedule');
const fetch = require('node-fetch');
const symbols = ["ADABTC", "AEBTC", "AIONBTC", "ALGOBTC", "ARDRBTC", "ARKBTC", "ATOMTC"]
const getBTCData = async symbol => {
let data = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=30m&limit=1`).then(res => res.json());
const btcusdtdata = data.map(d => {
return {
Volume: parseInt(d[5]),
Timespan: 30,
}
});
console.log(btcusdtdata);
};
const sleep = ms => new Promise(res => setTimeout(res, ms));
const j = schedule.scheduleJob('* * * * *', async() => {
for (let symbol of symbols) {
await getBTCData(symbol);
await sleep(4000);
}
});
目标:如果我每30分钟收到一次资产,如何计算这部分的平均值-Volume: parseInt(d[5]),
?
答案 0 :(得分:1)
收集平均值(和其他统计数据)的一种简单方法是创建一个以符号为键的地图。
我们将保留每个符号的历史记录,然后在每次获得新数据点时计算例如交易量的平均值。
一个例子可能看起来像这样(出于演示目的,我已将呼叫频率更新为每10秒一次!)
const schedule = require('node-schedule');
const fetch = require('node-fetch');
const symbols = ["ADABTC", "AEBTC", "AIONBTC", "ALGOBTC", "ARDRBTC", "ARKBTC", ]
const symbolSummary = {};
const getBTCData = async symbol => {
let data = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=30m&limit=1`).then(res => res.json());
const btcusdtdata = data.map(d => {
return {
Volume: parseInt(d[5]),
Timespan: 30,
symbol
}
});
console.log(btcusdtdata);
return btcusdtdata;
};
const appendBTCDataToSummary = (btcData, summary) => {
if (!summary[btcData.symbol]) {
summary[btcData.symbol] = { history: [], symbol: btcData.symbol };
}
let symbolHistory = summary[btcData.symbol].history;
symbolHistory.push(btcData);
summary[btcData.symbol].averageVolume = symbolHistory.reduce((average, row) => {
// Calculate the average volume by scaling each volume entry by 1 / length.
return average + (row.Volume) * (1 / symbolHistory.length);
}, 0)
summary[btcData.symbol].dataPoints = symbolHistory.length;
}
const sleep = ms => new Promise(res => setTimeout(res, ms));
const j = schedule.scheduleJob('* * * * *', async() => {
for (let symbol of symbols) {
let btcData = await getBTCData(symbol);
appendBTCDataToSummary(btcData[0], symbolSummary);
// We must back off between calls as per api terms of use.
await sleep(4000);
}
console.log("Symbol summaries:", Object.values(symbolSummary).map(summary => {
return { symbol: summary.symbol, AverageVolume: summary.averageVolume, DataPoints: summary.dataPoints };
}));
});