我制作了一个个人网络工具,以图形方式收集有关价格变化的数据。价格每20秒通过websocket馈入我的脚本中。截至目前,每一次价格变化都会在图表上创建一个新点。这样很好!
问题:
大多数商品每1-2小时会收到一次实际的价格更新,但有些商品似乎抖动了几美分。这意味着一项商品的价格可能从1.50欧元上涨至1.51欧元,然后每20秒返回几小时,从而产生无穷无尽的图形点。来自websocket的数据将始终包含数百个商品的完整价格表-即使它们的价格没有变化。
我对此的方法似乎部分起作用。我将每个项目的最近两个已知价格保存在一个简短的数组中。如果价格发生变化,它将检查是否最后两个变化包括此新价格,如果是这样的话:没有新点,只需更新旧价格。如果新价格未包含在“黑名单”数组中(因此是“实际”价格变化),请生成一个新点并相应地更新黑名单数组。问题是,如果某项在“真实”更新后再次开始抖动,它将产生一个带有附加点的微小尖峰。
有没有更聪明的方法来做到这一点,没有错误?
var db = { // Example object in my database
apple: {currentPrice: 1.44, graphX: [1.42, 1.41, 1.44], graphY: [1534175049283, 1534175019374, 1534175082191], blackList = [1.44, 1.41]}
}
function newPrice(name, price){
if(db[name].currentPrice != price){ // Check if the price changed at all
if(db[name].blackList.indexOf(.price) == -1){ // Check if the price has been seen within the last 2 changes, if not, treat it as a new price
db[name].graphX.push(price); // Add price...
db[name].graphY.push(Date.now()); // ...and timestamp to X and Y arrays for a plotly graph to read when requested
db[name].currentPrice = price; // Update the current price (for easier access)
db[name].blackList[1] = db[name].blackList[0]; // Move the blacklist array by one up, delete the oldest one
db[name].blackList[0] = price; // set the new price to [0] on the blacklist
console.log("New graph point created!")
} else { // If it's one of the recent prices, dont add a new graph point, just update the old one
db[name].currentPrice = price; // Update the current price (for easier access)
db[name].graphX[db[name].graphX.length - 1] = price; // update the last array segment (price)
db[name].graphY[db[name].graphY.length - 1] = Date.now(); // update the last array segment (time)
console.log("Jittering price, updated last graph point!");
}
}
}
newPrice("apple", 1.41) // Gets called by a websocket every ~30 seconds, providing a name and a price
最佳答案
如果实际价格除了每小时左右都没有更新,为什么不每小时运行一次,而不是每20秒运行一次呢?考虑研究有关如何在设定的时间间隔上运行脚本的选项。
参见:Running a node.js script every 10 seconds
并进行编辑以满足您的需求。
关于javascript - 确定某个值是在两个价格之间跳跃还是在实际变化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51826539/