How to set dynamic MaxOpenPositions

Hello, I would like to dynamically change the maximum number of open positions depending on a market filter. I tried the code below, but I'm not allowed to define it that way. Could you help me

MarketIndex = Foreign("$SPX","C");
MarketFilter = MarketIndex > WMA(MarketIndex,150);
NumberHeld = IIf(MarketFilter, 15, 8); // Position Quantity: max number of positions    

SetOption( "MaxOpenPositions", NumberHeld );// Maximum number of simlutaneously open positions (trades) in portfolio backtest/optimization

As I explained many times "MaxOpenPositions" is the MAXIMUM, not actual number of open positions. It is GLOBAL MAXIMUM (the most number of positions you would EVER wish during duration of entire backtest) set per backtest, not on bar-by-bar basis.

To limit the number of currently open positions you should:

  • make your trading rules limit number of entry signals
    OR
  • use custom backtester to skip signals / generate sell
    OR
  • use POSITION SIZING to make sure you don't have funds to open more than desired number of open positions

Thing to consider is that you would need to generate a SELL SIGNAL if your market condition change and you already have more positions that you want.

There are dozens of threads already covering that, use search:

https://forum.amibroker.com/search?q=MaxOpenPositions