首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何求和每对之间的差异,然后用nedb对每对结果进行求和

如何求和每对之间的差异,然后用nedb对每对结果进行求和
EN

Stack Overflow用户
提问于 2020-09-17 14:48:21
回答 1查看 51关注 0票数 1

我有一个nedb数据库trades.json,在这里我正在编写虚构的股票交易:

代码语言:javascript
复制
{"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的“买入”和“卖出”之间的差异,然后将这两个结果相加,给出我的总体利润。

我有这个代码,它可以工作,但我不确定结果是否有效。我认为这给了我总体上的差异,而不是显示我的“利润”的每一笔交易。

代码语言:javascript
复制
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

我将感谢任何帮助或指导!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-17 15:03:21

您可以从和中减去'BUY'值并添加'SELL'值。

代码语言:javascript
复制
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);

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63940636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档