ApplyStop with an extra condition

Hi guys,

For my backtestings, I would like using ApplyStop with an extra volatility condition.
I mean I want to sell by stop only if the volatility is not too high

ApplyStop(stopTypeLoss,stopModePercent,10,0); (general stop condition)

but only if VIX index <30 at close (extra volatility condition)

How can I program that in AFL language?

Thanks for your help

You can't modify stop mode on bar by bar basis. ApplyStop is the on/off switch. Per backtest not per bar. The only thing that can change on bar-by-bar basis in ApplyStop is the amount. To effectively disable stop, set the "amount" to sufficiently large value (like 99% for percent stop)


Ah, OK. Thank you for information.

So correction,

/// @link
SetTradeDelays(0, 0, 0, 0);
SetOption("ActivateStopsImmediately", 0);
VIX = Foreign("^VIX", "C"); // 
vola_cond = VIX < 30;
// stop mode is not bar-by-bar setting 
// so we would have to tackle stop amount 
// by setting it to large value to "disable" stop
// if condition returns false
stop_amount = IIf(vola_cond, 10, 99);// percent stop amount
Sell = 0;
SellPrice = Close;
ApplyStop(stopTypeLoss, stopModePercent, stop_amount, exitatstop = 0);

Thank you all for assistance

But, it doesn't work yet

in example attached 'BHP' stock has exited and VIX >30 (58)14-03-2020%2019-09-59

SetTradeDelays(0, 0, 0, 0);
SetOption("ActivateStopsImmediately", 0);



stopamount = IIf(VIX<30,9.5,99);

Buy=dist30>2.6 AND dist30<8.8 AND cap52>20000000 AND distmax<2.2 AND C>=3;
Sell=(dist30>40 AND Close>mm30) OR (distmax>27 AND VIX<30);


Stop loss amount is set at entry bar but not at exit.
It is a fix stop loss. Once stop loss is set at entry it is kept till exit trigger (price break).
I.e. if VIX is below threshold at entry then stop amount is 10 till price break.
If VIX is above threshold at entry then stop amount is 99 till price break.

So I think you would have to write custom stop code via looping.

Try setting the "volatile" parameter in the ApplyStop function to true or 1:


I did a quick test with your code and it appears to me that this works.


Yes, I've just done it. it seems to work. Tomorrow I'm going to check it deeply

Thank you very much

Yes, volatile at true seems to work (double checked with custom looping stop code and getting same results) and I misunderstood the volatile setting documentation in that case as I thought (if volatile = true) then price levels from which stop target is calculated from would vary too (since Chandelier exit is mentioned there).

volatile -
decides if amount (or distance) (3rd parameter) is sampled at the trade entry and remains fixed during the trade (Volatile = FALSE - old behaviour) or if can vary during the trade (Volatile = TRUE) (allows single line Chandelier exit implementation)(2)

The solution was


I got what I was looking for with your help
Thank you all guys, you are fantastic

Best regards

1 Like