function buyAndSell(value) { let balance = 100000; // initial balance let holding = 0; // initial holding // loop every 0.3 seconds setInterval(() => { let price = getPrice(); // get current price from API or data source // buy if value is less than or equal to current price and balance is greater than or equal to value if (value <= price && balance >= value) { holding += (balance / price); // buy as much as possible balance -= value; // deduct value from balance } // sell if price is greater than or equal to 1.2 times value and holding is greater than 0 if (price >= (value * 1.2) && holding > 0) { balance += (holding * price); // sell all holdings holding = 0; // reset holding to 0 } }, 300); // run every 0.3 seconds }