Search code examples
javascriptarraysmathforeachnedb

How to sum the differences between each pair, then sum each pair's results using nedb


I have a nedb database trades.json where I am writing imaginary stock trades:

{"buySell":"BUY","currentPrice":431.55,"_id":"GyTaUKVOCa9x5APS"},
{"buySell":"SELL","currentPrice":431.77,"_id":"Re9VhGrW9ZoiOKFe"},
{"buySell":"BUY","currentPrice":431.65,"_id":"TJrn63bIV8sKBFYh"},
{"buySell":"SELL","currentPrice":431.7539,"_id":"qrsz2l3UVKpQEks8"}

I am trying to find the difference of currentPrice between each buySell pair of "BUY" and "SELL" then add those two results together to give me my overall profits.

I have this code, which works, but I'm not sure the result is valid. I think it's giving me the difference overall and not showing me my "profits" for each trade.

const Datastore = require('nedb')
const trades = new Datastore({ filename: 'trades.json' })
trades.loadDatabase(function (err) {
    if(err) return console.error(err)
})

let sum = []
trades.find({}).exec(function (err, docs) {

    if(err) return console.log(err)

    docs.forEach(element => {
        sum.push(element.currentPrice)
    });
    let pandle = diff(sum)
    pandle = pandle.reduce((a, b) => a + b, 0)
    
    console.log(pandle)
    
})

function diff(A) {
    return A.slice(1).map(function(n, i) { return n - A[i]; });
}

I believe my answer lies in a foreach loop that builds an array of the bySell "BUY" and "SELL" pairs, and another array that keeps track of the sum of those pairs, but I'm struggling to get it working.

In the example above, I believe I should be getting: 0.3239.

I will appreciate any help or direction!


Solution

  • You could subtract 'BUY' values from the sum and add 'SELL' values.

    const
        fns = { BUY: v => -v, SELL: v => v },
        array = [{ buySell: "BUY", currentPrice: 431.55, _id: "GyTaUKVOCa9x5APS" }, { buySell: "SELL", currentPrice: 431.77, _id: "Re9VhGrW9ZoiOKFe" }, { buySell: "BUY", currentPrice: 431.65, _id: "TJrn63bIV8sKBFYh" }, { buySell: "SELL", currentPrice: 431.7539, _id: "qrsz2l3UVKpQEks8" }],
        profit = array.reduce((p, { buySell, currentPrice }) => p + fns[buySell](currentPrice), 0);
    
    console.log(profit);