问题描述
我有一个nedb数据库Trades.json
,用于编写虚构的股票交易:
{"buySell":"BUY","currentPrice":431.55,"_id":"GyTaUKVOCa9x5APS"},{"buySell":"SELL","currentPrice":431.77,"_id":"Re9VhGrW9ZoiOKFe"},{"buySell":"BUY","currentPrice":431.65,"_id":"TJrn63bIV8sKBFYh"},"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]; });
}
我相信我的答案在于一个foreach循环,该循环建立bySell
“ BUY”和“ SELL”对的数组,以及另一个跟踪这些对之和的数组,但是我很挣扎使其正常工作。
在上面的示例中,我认为我应该得到:0.3239
。
我将不胜感激!
解决方法
您可以从总和中减去'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" },currentPrice: 431.7539,_id: "qrsz2l3UVKpQEks8" }],profit = array.reduce((p,{ buySell,currentPrice }) => p + fns[buySell](currentPrice),0);
console.log(profit);