Very often (cca 20% of time) I am getting following error in my backtesting:

Backtest Handled Error: Order Error: id: 11, Insufficient buying power to complete order (Value:24955.9785), Reason: Id: 11, Initial Margin: 12478.9892365, Free Margin: 154.669432942

Derek Melchin proposed the lower percentage in self.SetHoldings function and using cash buffers, that is using self.Settings.FreePortfolioValuePercentage function.

I implemented both things using:

self.Settings.FreePortfolioValuePercentage = 0.5

self.SetHoldings("SPY", .5)

but it didn't help. I am still getting trhe same error (not as often as before, but still).

Attached you can find the whole code of the backtest. It's relatively long, but most important are the lines of code above.

I can try with even lower percentage values and higher cash bufferrs, but that changes my strategy a lot since I invest only small fraction of available cash when I want to invest almost everything (say 90%).