IB's (and not only) margins are dynamical, i.e. change over time and on CFDs for example are computed as 5 standard deviations of the historical volatility.
This implies that a position could be margin called just due to the margin increase, even if it was ok before the margin change.
This happened for example in the past, see this class action ,https://financefeeds.com/customers-interactive-brokers-file-class-action-complaint-management-portfolio-margin-accounts/ , and is a very serious risk.
How can the margin calls be simulated in presence of dynamic margins?
Note that the only way to do it is to compute the equity=cash+position value at each bar and check if equity>margin.
This cannot be accomplished with a stop because it requires the knowledge of the entry price to determine the value of equity. In case of a margin call it would be necessary to choose what position to close or reduce (IB does it kind of randomly), but for simplicity let's just say we want to simulate this for a single product, and exit completely the trade (in principle it would be enough to reduce the position, but with daily data it would be difficult to simulate).
Is there a way to do it without custom backtesting? Any code already doing it?
I would be surprised if it has not been done already since it is such a common scenario
So far I just used the maximum historical margin as a worst case scenario and never used a smaller one but it is severely limiting the leverage, and there could always be a situation in which the margins are greater than they have ever been in the past.
Margin calls are very common so there must be a way to simulate them realistically or any backtesting would be (and it actually is) completely unreliable.