Insufficient funds error for withdrawal via API

Hey, I’m trying to automate some trades and then a withdrawal. I’m trying to withdraw BNB on BSC chain. As I’m just wanting to withdraw all my free BNB I’m using an account info call to give me the amount of free BNB and then inputting that value into a withdraw request.

For some reason I’m getting failures with the error : code: -4026, msg: ‘The user has insufficient balance available.’ I originally thought this was maybe due to withdrawals via the API not handling the fee correctly so I tried withdrawing the free value - 0.0006 (0.0001 extra to account for any rounding errors anywhere) but I’m still occasionally getting failures.

async function ftsWithdraw(){
    try{
      const accountInfo = await binanceRest.account();
      let freeFTS = new BigNumber(accountInfo.balances[search(fts, accountInfo.balances)].free).toFixed(8);
      freeFTS -= 0.0006
      freeFTS = parseFloat(freeFTS);

      let withdrawInfo = {
        coin: fts,
        network: networkName,
        address: userAddress,
        amount: freeFTS,
        };

        // console.log(withdrawInfo);
      withdrawId = await binanceRest.withdraw(withdrawInfo);
      console.log(`Withdrawing ${freeFTS - 0.0005} ${fts}...`.bgGreen);
      console.log(withdrawId);
  } catch (error) {
      console.log("Withdrawal error".bgGreen);
      console.log(error);
  }
};

Any ideas?

It seems the problem was that it was trying to withdraw too soon after making the trade to BNB. I simply added a counter and made it retry the withdrawal up to 3 times if there’s an error and this has fixed the issue.