When placing market orders, I want to be able to buy for 100% of my remaining balance.
Say I have 1000 USDT, and I want to buy BTCUSDT, then I could calculate the quantity of BTC to pass along in the buy order:
last_price = float(ticker['price'])
available_balance = float(balance['availableBalance'])
percentage = 1
quantity = percentage * available_balance / (last_price)
But, what if the market is volatile. Just getting the last price does not guarantee that is the price I can sell at.
What logic should I implement so that all the orders go through and the amount gets lowered if price goes up.
I could just do 99 or 98% orders to be safe, but my use case would work better if I can calculate it exactly.
One alternative I am thinking of is to ping the orderbook and take the 5th price or so, to account for some leeway, then use that as the current price. Not super clean though, there must be a nicer way to do this…