InsufficentMargin will happen in futures mode and NegativeBalance in spot mode.
Do you have multiple routes? Then you need to make sure that each route only uses a fraction of your capital / available margin. An example would be: / fraction_to_use
fraction_to_use should equal the weight you want to assign the route. The sum of all fraction_to_use mustn't exceed 1. To assign the same amount to all routes you can set fraction_to_use to the number of routes.
Do you use `risk_to_qty`? There might be situations where this helper returns a qty exceeding the available capital leading to an exception. The reason for this is a very close stop loss (often due to the usage of the ATR). You can check this with this calculator. That's not an error, but the expected behavior of the formula. You might want to add a logic limiting the qty to a maximum percentage of the capital. For example:

def position_size(self, entry, stop):
risk_qty = utils.risk_to_qty(self.available_margin, 30, entry, stop, fee_rate=self.fee_rate)
# never risk more than 30 percent
max_qty = utils.size_to_qty(0.30 * self.available_margin, entry, fee_rate=self.fee_rate)
qty = min(risk_qty, max_qty)
return qty
Was this article helpful?
Thank you!