Backtest Raw Multi Mode Seperate Stop for Long and Stop Positions

Hello AFL Community,

I hope this message finds you well. I have been working hard on a new trading strategy that involves opening multiple long and short positions simultaneously using the backtestRawMulti mode. However, I am struggling to figure out how to set variable stop sizes for long and short positions separately. Despite spending hours going through relevant posts on the forum, I have not been able to find a suitable solution. While I have come across several solutions that suggest using variable stop loss, unfortunately, it does not work with backtestRawMulti.

I would be extremely grateful if someone could take a look at my code below and offer any insights on how I can set variable stop sizes for my long and short positions separately. Your expertise and guidance would be much appreciated. Thank you in advance for your time and help.


SetBacktestMode(backtestRegular);//RawMulti );//set this in order to make it open more than one positions on the same ticker
SetOption("MaxOpenLong",2);
SetOption("MaxOpenShort",1);

RoundLotSize = 0.01;// If default size is set also to zero it meansthat fractional number of shares/contracts are allowed.

SetPositionSize(PositionSize,spsPercentOfEquity);

//Long
l_entry_signal = Condition_for_long_entry;
l_exit_signal = Condition_for_long_exit; 

Buy = Condition_for_long_entry;
Sell = Condition_for_long_exit;

//short

s_entry_signal = Condition_for_short_entry; 
s_exit_signal = Condition_for_short_exit;

Short = Condition_for_short_entry;
Cover = Condition_for_short_exit;

//Position Size & Stop
LongSize = 1;
ShortSize = 1;
IsLong = Ref( Buy, -1 );
pos_size= IIf( IsLong, LongSize, ShortSize);
SetPositionSize(pos_size,spsPercentOfEquity);

stopAmount = IIf( IsLong, 0.005, 0.025);
ApplyStop( stopTypeLoss, stopModePoint, stopAmount,True);

This code will have the variable stop won't support by backtestRaw error. Is there any walk around?

As error message says, raw mode does not support dynamic stop.

This is so because for dynamic stop to work you need to know your entry bar in FIRST phase of backtest so stop can be evaluated in first phase too. But in "raw" mode you don't know that as signals don't get filtered in first phase and stops can only be evaluated in second phase of backtest.

There are two solutions:

  1. Use regularBacktest mode
  2. Implement your own stops in custom backtester procedure Porfolio Backtester Interface Reference
    It is relatively simple as you just iterate thru open positions, call GetProfit() and exit (call ExitTrade) when loss exceeds your desired level
1 Like

Thank you Tomas. I will check out the Portfolio Backtester method :+1: