我有一个nedb数据库trades.json,在这里我正在编写虚构的股票交易:
{"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"}我试图找出currentPrice在每对buySell的“买入”和“卖出”之间的差异,然后将这两个结果相加,给出我的总体利润。
我有这个代码,它可以工作,但我不确定结果是否有效。我认为这给了我总体上的差异,而不是显示我的“利润”的每一笔交易。
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]; });
}我相信我的答案在于一个前程循环,它构建了一个bySell "BUY“和"SELL”对的数组,以及另一个跟踪这些对之和的数组,但我很难让它正常工作。
在上面的例子中,我认为我应该得到:0.3239。
我将感谢任何帮助或指导!
发布于 2020-09-17 15:03:21
您可以从和中减去'BUY'值并添加'SELL'值。
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);
https://stackoverflow.com/questions/63940636
复制相似问题