"Margin insufficient" error while placing stop loss order

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;

  1. Place buy order
  2. Place stop loss order
  3. 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 :slight_smile:

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)

You might want to try out STOP_MARKET & TAKE_PROFIT_MARKET orders, since your price and stopPrice are the same. This would mean you have to remove the price and timeinforce parameters.

Also, I would suggest adding a parameter closePosition=True to these orders, but I am not sure what your requirements are so I can’t say for sure

1 Like