In my nedb database called trades.json
, I am simulating stock trades with the following data:
{"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"}
My goal is to calculate the difference in currentPrice
between each "BUY" and "SELL" pair of trades, and then sum up those results to determine my overall profits.
I have a functional code snippet for this calculation, but I suspect it may be providing me with the total difference instead of individual profit margins 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 that I need to implement a foreach loop that constructs an array of "BUY" and "SELL" pairs, along with another array to store the sum of these pairs, but I'm facing challenges in getting it to function correctly.
Based on the example provided above, I anticipate that the expected result should be: 0.3239
.
Your guidance or assistance in solving this issue would be greatly appreciated!