如何在 javascript 中获取不断变化的对象的连续值

how to get consecutive value of a changing object in javascript

我是编程新手,想编写一个简单的代码,使我能够从服务器的实时提要字符串中获取连续值,我需要帮助的是如何完成以下任务

先举个例子

就像获取 Dash 硬币的实时价格更新 - 假设价格是当前

以上显示价格连续第 4 次上涨 我的问题是如何设置这个功能

#如何保守增加或减少多次后得到变化的值!

例如,如果我想在达世币价格连续 #4 次或更多次或任意 x 次上涨时收到提醒

希望在 JavaScript 中获得有关如何执行此操作的指南。

//ok first I tried the above BELOW, but I didn't get the expected results - how I used it below: What did I do wrong?

const WebSocket = require('ws');

var ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089');

var lastTick = null;

ws.onopen = function(evt) {
    ws.send(JSON.stringify({ticks:'R_100'}));
};

ws.onmessage = function(msg) {
   var data = JSON.parse(msg.data);
   var currentTickTime = data.tick.epoch;
   var currentTick = data.tick.quote;
   const timerz = 1000;
   //console.log(currentTick,'\n', balance)
   var tickTime = new Date(currentTickTime * timerz).toLocaleString();
  

   //testing code below
   
   function handleNotification(){
    if (balance > 3){
        console.log("RISE UP-3times.");
        // Send notification that price is rising.
    }

    if (balance < -3){
        console.log("FALL DOWN-3times.");
        // Send notification that price is falling.
    }

   }
   
   var currentPrice = 0;
   var balance = 0;

   setInterval(async () => {
    const previousPrice = currentPrice;
    currentPrice =  await currentTick;
    if (currentPrice > previousPrice){
        //console.log('Higher Price')
        if (balance >= 0) balance++
        else balance = 0; 
    }else if (currentPrice < previousPrice){
        //console.log('Lower Price')
        if (balance <= 0) balance--
        else balance = 0;
    }else{
        // Price remains unchanged.
    } 

    handleNotification();
    console.log(currentPrice,'\n', balance)
}, 2000); 

  
    lastTick = currentTick;

};

我也尝试了下面的第二个选项,但最高 - num_consec 值是 1 和 -1,即使有多个连续高于该值。 下面是使用的代码:

const WebSocket = require('ws');

var ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089');

////////////////////////////////////////////////////
var lastTick = null;
var lastTickTime = null;

ws.onopen = function(evt) {
    ws.send(JSON.stringify({ticks:'R_100'}));
};

ws.onmessage = function(msg) {
   var data = JSON.parse(msg.data);
   var currentTickTime = data.tick.epoch;
   var currentTick = data.tick.quote;
   const timerz = 1000;
   //console.log(currentTick,'\n', balance)
   var tickTime = new Date(currentTickTime * timerz).toLocaleString();
   //console.log('ticks update: %o', currentTick, '\n', '-----------------------',tickTime);

   //testing code below
   ////////////////////////////////////////////////////////////////////
   var price = lastTick; // or whatever initial value
   var num_consec = 0;
   var positive = true; //needs default

   setInterval(function() {
    var newprice = currentTick; // code to grab price from source, edit this to grab from your api
  
    if (Math.abs(price - newprice) >= 1) { // detect within a certain range, OP specified 1
      if (price - newprice > 0 && positive) { // consecutive up
        num_consec += 1;
      } else if (price - newprice < 0 && !(positive)) { // consecutive down
        num_consec += 1;
      } else if (price - newprice < 0 && positive) { // went down and broke streak
        num_consec = 0;
        positive = false;
      } else if (price - newprice > 0 && !(positive)) { //went up and broke streak
        num_consec = 0;
        positive = true;
      };
      price = newprice; //reset price delta
  
      console.log("Updated Info:",'\n', price, num_consec)// update price in html or elsewhere, console.log unnecessary
  
      if (num_consec > 2) {
        // do something with consec info
        console.log((positive) ? `Consecutive ${num_consec} times `+"up" : `Consecutive ${num_consec} times `+"down")
      };
    };
    newprice = null; // reset variable
  }, 1000); // check new price every 1000 ms (1s)

    //console.log(currentTick,'\n', num_consec)


    lastTick = currentTick;

    lastTickTime = tickTime;
};

感谢我能得到的所有帮助-请帮助我检查代码以了解我做错了什么

我建议按照以下方式执行此操作以避免阻塞您的线程,但要定期检查特定范围的更改。不幸的是,测量连续变化并不是非常简单,但可以使用下面的代码来完成。

setInterval():

的可能实现
var price = 50; // or whatever initial value
var num_consec = 0;
var positive = true; //needs default
setInterval(function() {
  var newprice = ...; // code to grab price from source, edit this to grab from your api

  if (Math.abs(price - newprice) >= 1) { // detect within a certain range, OP specified 1
    if (price - newprice > 0 && positive) { // consecutive up
      num_consec += 1;
    } else if (price - newprice < 0 && !(positive)) { // consecutive down
      num_consec += 1;
    } else if (price - newprice < 0 && positive) { // went down and broke streak
      num_consec = 0;
      positive = false;
    } else if (price - newprice > 0 && !(positive)) { //went up and broke streak
      num_consec = 0;
      positive = true;
    };
    price = newprice; //reset price delta

    console.log("Updated Info:", price, num_consec)// update price in html or elsewhere, console.log unnecessary

    if (num_consec > 2) {
      // do something with consec info
      console.log((positive) ? `Consecutive ${num_consec} times `+"up" : `Consecutive ${num_consec} times `+"down")
    };
  };
  newprice = null; // reset variable
}, 1000); // check new price every 1000 ms (1s)

测试用例(输出):

增加:

Test price Value:47
file.html:24 Updated Info: 47 0
file.html:40 Test price Value:46
file.html:24 Updated Info: 46 0
file.html:40 Test price Value:45
file.html:24 Updated Info: 45 1
file.html:40 Test price Value:44
file.html:24 Updated Info: 44 2
file.html:40 Test price Value:43
file.html:24 Updated Info: 43 3
file.html:28 Consecutive 3 times up
file.html:40 Test price Value:44
file.html:24 Updated Info: 44 0
file.html:40 Test price Value:43
file.html:24 Updated Info: 43 0

减少:

file.html:40 Test price Value:64
file.html:24 Updated Info: 64 0
file.html:40 Test price Value:65
file.html:24 Updated Info: 65 0
file.html:40 Test price Value:66
file.html:24 Updated Info: 66 1
file.html:40 Test price Value:67
file.html:24 Updated Info: 67 2
file.html:40 Test price Value:68
file.html:24 Updated Info: 68 3
file.html:28 Consecutive 3 times down
file.html:40 Test price Value:69
file.html:24 Updated Info: 69 4
file.html:28 Consecutive 4 times down
file.html:40 Test price Value:70
file.html:24 Updated Info: 70 5
file.html:28 Consecutive 5 times down
file.html:40 Test price Value:71
file.html:24 Updated Info: 71 6
file.html:28 Consecutive 6 times down
file.html:40 Test price Value:70
file.html:24 Updated Info: 70 0
file.html:40 Test price Value:69
file.html:24 Updated Info: 69 1

如果这没有回答您的问题,或者您需要更多帮助,请直接给我发消息,以便我们解决您的问题。

在这里快速简单地回答。

function handleNotification(){
    if (balance > 3){
        // Send notification that price is rising.
    }

    if (balance < -3){
        // Send notification that price is falling.
    }
}

var currentPrice = 0;
var balance = 0;

setInterval(async () => {
    const previousPrice = currentPrice;
    currentPrice = await getDashPrice();
    if (currentPrice > previousPrice){
        if (balance >= 0) balance++
        else balance = 0;
    }else if (currentPrice < previousPrice){
        if (balance <= 0) balance--
        else balance = 0;
    }else{
        // Price remains unchanged.
    }

    handleNotification();
}, 60000);

没什么复杂的。我们只是跟踪价格。如果价格低于我们上次检查时的价格,我们会减少余额值。如果它更高,我们会增加它。如果余额为正且价格下降,我们将其设置回 0,因为它不再连续。然后反之亦然。

余额只是跟踪出现了多少负面或正面的连续结果。如果价格变化非常小,这对您没有多大帮助。如果您想减少对 if 语句的精细控制,则需要在 if 语句中添加一个阈值。

编辑:这是设置阈值的方法。

var currentPrice = 0;
var balance = 0;
const threshold = 0.01; // 1%

setInterval(async () => {
    const previousPrice = currentPrice;
    const currentPriceTemp = await getDashPrice();
    if (currentPriceTemp > (previousPrice * (1 + threshold))){
        if (balance >= 0) balance++
        else balance = 0;
        currentPrice = currentPriceTemp;
    }else if (currentPriceTemp < (previousPrice * (1 - threshold))){
        if (balance <= 0) balance--
        else balance = 0;
        currentPrice = currentPriceTemp;
    }else{
        // Price remains unchanged.
    }

    handleNotification();
}, 60000);

这会将之前的价格乘以 1.01 或 0.99,具体取决于我们测试的是更高还是更低。基本上,价格变化需要比之前的值高或低 1% 以上。在此示例中,如果更改不符合 1% 的标准,我也不设置 currentPrice。如果变化小于 1%,这可以避免爬行(例如连续 100 次上升 0.5%,连续函数永远不会触发)。

您可以将 threshold 变量修改为您想要的任何值,只有当值上升或下降该百分比时,代码才会认为它是连续的。 const threshold = 0.01; 是 1%,const threshold = 0.99; 是 99%。