Hello, I am trying to develop a bot that trades on the Futures Market using the Binance API.
I have a function called “place_order”. It performs the following operations in order;
- Place buy order
- Place stop loss order
- Place take profit order
Buy order works without any problems. But when it comes to stop loss order, I get an error like “Margin insufficient”. The strangest thing is that I don’t get the error every time. Sometimes they all work without any problems, sometimes it gives a “Margin insufficient” error.
What do you think I missed?
Many thanks in advance for your help
My code is below;
def place_order(client, leverage, balance, close, stop_loss, take_profit):
# Set leverage
client.futures_change_leverage(symbol="ETHUSDT", leverage=leverage)
# Calculate quantity
quantity = float("{:.3f}".format(((balance * 0.9) / close) * leverage))
print("Quantity :", quantity)
# Place buy order
buy_sell_order = client.futures_create_order(symbol="ETHUSDT", side="BUY", type="LIMIT", timeinforce="GTC", quantity=quantity, price=close)
print("Buy Order :", buy_sell_order)
# Place stop loss order
stop_loss_order = client.futures_create_order(symbol="ETHUSDT", side="SELL", type="STOP", timeinforce="GTC", quantity=quantity, price=stop_loss, stopPrice=stop_loss)
print("Stop Loss Order :", stop_loss_order)
# Place take profit order
take_profit_order = client.futures_create_order(symbol="ETHUSDT", side="SELL", type="TAKE_PROFIT", timeinforce="GTC", quantity=quantity, price=take_profit, stopPrice=take_profit)
print("Take Profit Order", take_profit_order)