How to apply a correct initial stop loss in portfolio backtesting

Hi - I have an issue I cannot seem to solve.

I am using portfolio testing, and the nature of my system means many buy & sell signals are generated on each stock.

Whether each buy & sell signal is taken depends on if there is enough $ capital is free at that point in time.

The problem is coding an initial stop loss at the low of the entry bar.

Because at time of creating the Buy array I never know which Buy signal will be taken by Amibroker's backtester, so I cannot use:

Sell = L<Valuewhen(Buy==1, Low, 1);

because there can be several Buys before a sell.
eg:

Buy#1 - Buy#2 - Buy#3 - Sell#1

Using the AFL above:

If buy#1 is taken, as soon as buy#2 is encountered, the initial stop loss for buy#1 will change to the stop loss of buy#2.

I do not know which Buy signal is used by Amibroker, because I have 3000 stocks in my portfolio and am only using 5% equity per trade, with 20 max positions. It depends on the Positionscore.

Buy = Exrem(Buy,Sell) will not work either, because that will assume that Buy#1 is taken and Sell#1 is used - and Buys#2 and 3 are cancelled.

My questions:

  • How to code this initial stop?

  • If I then code a 20% trailing percentage stop with:

ApplyStop(stopTypeTrailing,stopModePercent, 20);

will this stop be applied on the correct Buy bar?

Thanks :slight_smile: