Calculate average in NodeJS from API

Viewed 797

I have a script which is taking data from Binance API every 30 minute interval and shows it in terminal. I would like to calculate the average for every asset which I have in array.

This is Node-Schedule package - const j = schedule.scheduleJob('* * * * *'

Small example: var array = ["ADABTC", "AEBTC", "AIONBTC"] I want to calculate separate average for "ADABTC", for "AEBTC" and for "KAVABTC".

Full Code

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

Goal: How I can calculate the average of Volume which is this part - Volume: parseInt(d[5]), for every asset if I will receive them every 30 minute?

1 Answers

A simple way of collecting averages (and other stats) would be to create a map keyed by symbol.

We would keep a history for each symbol, then compute an average for, say, volume each time we get a new data point.

An example might look like so (I've updated the call frequency to once every 10 seconds for demo purposes!)

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