3

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));
  });
5
  • 3
    Does this answer your question? How do I add a delay in a JavaScript loop? Commented Jan 7, 2020 at 13:14
  • You can use a setTimeout function Commented Jan 7, 2020 at 13:15
  • Another solution would be using streams like in rxjs library. Commented Jan 7, 2020 at 13:15
  • i need a solution within asynchronous functions Commented Jan 7, 2020 at 13:20
  • In order for this to work the forEach callback would have to be awaited by the inner workings of forEach. Pretty sure that's not the case. You will have to add the wait part some other way. Commented Jan 7, 2020 at 14:04

1 Answer 1

4

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
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Do i have to use for loop ? , forEach method is simpler for complex coin object
Yes, but do not work asynchronously for some reason. This basic for loop or the for (let i in coin) solution will work.
Alternatively you can use for...await loop but it requires custom iterator function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.