2

I have a trading script that gets values from "coin" object, which is filled by an API call, then iterates inside async forEach loop, then sends trade orders to the server.

The server requires at least 100 ms between each request. I used setTimeout with promise, but I can see results coming to console all at once so server bans after a while.

How should I design delaying?
js

Object.keys(coin).forEach(async function(key) {
 const coinz = coin[key];
  let line1 = sellcoinCalc("sell", coinz.usdPair, coinz.usdOrder)
  let line2 = buycoinCalc("buy", coinz.usdtPair, line1)          
  let result = line2-line1
 if (result > 0){
  console.log(result)
  }
 if (result >= profit){
      await sellcoinTrade("sell", coinz.usdPair, coinz.usdOrder)
      await buycoinTrade("buy", coinz.usdtPair, line1)            
  }
      await new Promise(r => setTimeout(r, 200));
  });
Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29
trmt
  • 137
  • 1
  • 14
  • 3
    Does this answer your question? [How do I add a delay in a JavaScript loop?](https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – Zydnar Jan 07 '20 at 13:14
  • You can use a setTimeout function – Luis Louis Jan 07 '20 at 13:15
  • Another solution would be using streams like in rxjs library. – Zydnar Jan 07 '20 at 13:15
  • i need a solution within asynchronous functions – trmt Jan 07 '20 at 13:20
  • In order for this to work the `forEach` callback would have to be `await`ed by the inner workings of forEach. Pretty sure that's not the case. You will have to add the wait part some other way. – James Jan 07 '20 at 14:04

1 Answers1

3

Use for loop instead of forEach and wrap the whole stuff into an async function:

const sleep = ms => new Promise(r => setTimeout(r, ms))

const tradeFn = async () => {
  try {
    for (let i in coin) {
      await sleep(200);
      const coinz = coin[i];
      await sellcoinTrade(coinz /* etc */);
      // etc
    }
  } catch(e) {
    // handle rejections
  }
}
gazdagergo
  • 6,187
  • 1
  • 31
  • 45