ApplyStop Volatility paramater not behaving as expected

Hi all,

I am trying to vary the 3rd parameter (amount) in Applystop by setting volatile = True, as inspired by this thread.

Below is my code for varying it, which should be based on whether the current close is above or below the current open:

stop_amount = IIf(C<O, 5, 90);// percent stop amount
ApplyStop(stopTypeLoss, stopModePercent, stop_amount, exitatstop = 2, volatile=True, 0,4,-1,0);

I'm trading on the next open, fwiw:
image

With the logic above, I would assume that the system would only exit after a green candle if there is a drawdown of 90% - therefore very very rarely.
However, I see that it does sometimes exit after a green candle.
Using CMG as an example, it enters a trade on 06-07-2012 and exits it on 10-08-2012 as shown here by the actual trade arrows:
image

Does anyone know what I might do wrong here and why it doesn't work as intended?

Thanks in advance and please let me know if you need any additional info.

You have set exit at stop = 2.

From Manual page:

AFL Function Reference - APPLYSTOP

ExitAtStop = 2 - check High-Low prices but exit NEXT BAR on regular trade price.

So it just does what you told it to do.


So read about the other two exit at stop options:

AFL Function Reference - APPLYSTOP

ExitAtStop = 0 - means check stops using only trade price and exit at regular trade price(1)
(if you are trading on close it means that only close price will be checked for exits and exit will be done at close price)
ExitAtStop = 1 - check High-Low prices and exit intraday on price equal to stop level on the same bar when stop was triggered

stop_amount = IIf(C<O, 5, 90);// percent stop amount
exitatstop = 0; 
volatile=True;
Sell = 0;
SellPrice = Close;
ApplyStop(stopTypeLoss, stopModePercent, stop_amount, exitatstop, volatile, 0,4,-1,0);

Good point, and thanks a lot for answering @fxshrat :slight_smile:

Checking here on AKAM with ExitAtStop = 0, it exits after a green candle which shouldn't be happening here.
image

Please post full code or analysis project file.
Apparently you have delays larger zero.

It is not supposed to be guessing game... being much waste of time such games...

Sorry, should have posted full code.

Please see the code below:

// Trade settings
BuyPrice = Open;
SellPrice = Open;
SetTradeDelays(1,1,1,1);
//SetTradeDelays(0,0,0,0);
#include_once "Formulas\Norgate Data\Norgate Data Functions.afl"
Numpos = 6; // 6 for SPX, 8 for RUI, 12 for RUA. 
SetOption("MaxOpenPositions", Numpos);
SetPositionSize(100/Numpos, spsPercentOfEquity);
minbars = 4;
indexlen = 20;
hlength = 3;
securityGoneToGod = DateTime() >= GetFnData("DelistingDate");
botw = 3;
roclonglen = 30;
rocshortlen = 20;
roclongval = 5;
rocshortval = 10;
index_symbol = "$SPX";

// Index and index trend
Index = Foreign(index_symbol, "C", True);
IndexMA = EMA(Index,indexlen);


// Buy and Sell conditions
Buy =   Ref(ROC(C,roclonglen),-1)>roclongval AND Ref(ROC(C,rocshortlen),-1)>rocshortval and NorgateIndexConstituentTimeSeries(index_symbol)
	  AND Index>IndexMA AND C<Ref(LLV(L,botw),-1) AND Ref(C,-1)>Ref(O,-1) AND C>MA(C,50);
	  
Sell = ((((C>Ref(HHV(H,hlength),-1) ) OR (BarsSince(Buy)>15) )) AND BarsSince(Buy)>minbars)  
		  OR Ref(securityGoneToGod, 0);

// Position ranking if portolio is full
PositionScore =  (StDev(log(C/Ref(C,-1)),rocshortlen)*(52^.5)*100) - RSI(2);

stop_amount = IIf(C<O, 5, 90);// percent stop amount
ApplyStop(stopTypeLoss, stopModePercent, stop_amount, exitatstop = 0, volatile=True, 0,4,-1,0);


// Plotting values
Equity(1); // THIS EVALUATES STOPS
PlotShapes(IIf( Ref(Buy,0), shapeUpArrow, shapeNone), colorYellow, 0, L,-50);
PlotShapes(IIf( Ref(Sell,0), shapeDownArrow, shapeNone), colorYellow, 0, H,-50);
PlotShapes(IIf( Ref(Buy,-1), shapeHollowSmallSquare, shapeNone), colorWhite, 0, Open,0);
PlotShapes(IIf( Ref(Sell,-1), shapeHollowSmallSquare, shapeNone), colorWhite, 0, Open,0);
Plot( .5, "Ribbon", IIf(Index>IndexMA, colorGreen, IIf( Index<IndexMA, colorRed, 0 )), styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );
for( i = 1; i < BarCount; i++ )
{
if( Buy[i-1] ) 
PlotText( "Buy\n"+Open[i], i, L[ i ], colorWhite,colorDefault,-15);
if( Sell[i-1] ) PlotText( "Sell\n"+Open[i], i, H[ i ], colorWhite,colorDefault,20);
}

Really appreciate your time and help!! :slight_smile:

C'mon, you have additional Sell rule that's why there may be exits that are not based on ApplyStop.
So for testing set Sell = 0; and since you really want to use exitatstop = 2 kep at at value 2 not zero.

BTW, as for this line stop_amount = IIf(C<O, 5, 90);// percent stop amount ...
It does not mean that you tell ApplyStop "Do always exit after red candle". It just sets stop amount.

But there are some other flaws in your code (which is a bit of a mess BTW).

And instead of that Sell rule you should use ApplyStop nbar stop. BarSince(Buy) in Sell rule is not that great. But I think you would rather have to use looping since you combine BarsSince with C>Ref(HHV(H,hlength),-1)


And BTW, since you use delays larger zero set Equity first argument to 2 from 1 (but only executed in indicator otherwise in analysis it would delay by further bar with your code).

eq = Equity(2);

Here is modified test code:
Note, I have commented all Norgate stuff since not all users use them. So uncomment on your end and set back to symbol "$SPX" from "^GSPC".

But I think instead of using ApplyStop you should write looping code for all your custom exits (e.g. stop exit always after read candle etc.).

// Trade settings
BuyPrice = Open;
SellPrice = Open;
SetTradeDelays(1,1,1,1);
//SetTradeDelays(0,0,0,0);
//#include_once "Formulas\Norgate Data\Norgate Data Functions.afl"
bi = BarIndex();
exitLastBar = bi == LastValue( bi - 1 );
Numpos = 6; // 6 for SPX, 8 for RUI, 12 for RUA. 
SetOption("MaxOpenPositions", Numpos);
SetOption("ActivateStopsImmediately", 0);

//SetPositionSize(100/Numpos, spsPercentOfEquity);
SetPositionSize(1, spsShares);// for testing

minbars = 4;
indexlen = 20;
hlength = 3;
securityGoneToGod = DateTime() >= GetFnData("DelistingDate");
barsBeforeSecurityGoneToGod = (LastValue(ValueWhen(DateTime() == GetFnData("DelistingDate"), BarIndex(), 1))) - BarIndex();
botw = 3;
roclonglen = 30;
rocshortlen = 20;
roclongval = 5;
rocshortval = 10;
index_symbol = "^GSPC";// "$SPX";

// Index and index trend
Index = Foreign(index_symbol, "C", True);
IndexMA = EMA(Index,indexlen);
trailArray = Null;


// Buy and Sell conditions
Buy =  Ref(ROC(C,roclonglen),-1)>roclongval AND Ref(ROC(C,rocshortlen),-1)>rocshortval /*and NorgateIndexConstituentTimeSeries(index_symbol)*/
	  AND Index>IndexMA AND C<Ref(LLV(L,botw),-1) AND Ref(C,-1)>Ref(O,-1) AND C>MA(C,50);

//Sell = (((C>Ref(HHV(H,hlength),-1)) OR (BarsSince(Buy)>15) ) AND BarsSince(Buy)>minbars)  OR Ref(securityGoneToGod, 0);
Sell = 0;

// Position ranking if portolio is full
PositionScore =  (StDev(log(C/Ref(C,-1)),rocshortlen)*(52^.5)*100) - RSI(2);

stop_amount = IIf(C<O, 5, 90);// percent stop amount
exitatstop = 2;
volatile = True;
ApplyStop(stopTypeLoss, stopModePercent, stop_amount, exitatstop, volatile, 0,4,-1,0);

Plot( C, "Price", colorDefault, styleCandle );

// Plotting values
if ( Status("action") == actionIndicator ) {
	eq = Equity(2); // THIS EVALUATES STOPS
	PlotShapes(IIf( Ref(Buy,0), shapeUpArrow, shapeNone), colorYellow, 0, L,-50);
	PlotShapes(IIf( Ref(Sell,0), shapeDownArrow, shapeNone), colorRed, 0, H,-50);
	PlotShapes(IIf( Ref(Buy,0), shapeHollowSmallSquare, shapeNone), colorWhite, 0, BuyPrice,0);
	PlotShapes(IIf( Ref(Sell,0), shapeHollowSmallSquare, shapeNone), colorWhite, 0, SellPrice,0);
	Plot( .5, "Ribbon", IIf(Index>IndexMA, colorGreen, IIf( Index<IndexMA, colorRed, 0 )), styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );

	for( i = 1; i < BarCount; i++ )
	{
		if( Buy[i] )
			PlotText( "Buy\n" + BuyPrice[i], i, L[ i ], colorWhite, colorDefault, -15 );
		if( Sell[i] ) PlotText( "Sell\n" + SellPrice[i], i, H[ i ], colorWhite, colorDefault, 20 );
	}
}

As you can see backtest arrows and PlotShapes arrows are in line.

31

You might try this one

stop_amount = IIf(Ref(C<O,-1), 5, 99);// percent stop amount

to see whether it does what you look for

The orange square (in below picture) marks ApplyStop exits where previous bar before exit was C<O being TRUE.

Note: eq = Equity(2); uses analysis range. If you want to apply all bars in chart then set eq = Equity(2,0);

// Trade settings
BuyPrice = Open;
SellPrice = Open;
SetTradeDelays(1,1,1,1);
//SetTradeDelays(0,0,0,0);
//#include_once "Formulas\Norgate Data\Norgate Data Functions.afl"
bi = BarIndex();
exitLastBar = bi == LastValue( bi - 1 );
Numpos = 6; // 6 for SPX, 8 for RUI, 12 for RUA. 
SetOption("MaxOpenPositions", Numpos);

//SetPositionSize(100/Numpos, spsPercentOfEquity);
SetPositionSize(1, spsShares);// for testing

SetOption("ActivateStopsImmediately", 0);
minbars = 4;
indexlen = 20;
hlength = 3;
securityGoneToGod = DateTime() >= GetFnData("DelistingDate");
barsBeforeSecurityGoneToGod = (LastValue(ValueWhen(DateTime() == GetFnData("DelistingDate"), BarIndex(), 1))) - BarIndex();
botw = 3;
roclonglen = 30;
rocshortlen = 20;
roclongval = 5;
rocshortval = 10;
index_symbol = "^GSPC";// "$SPX";

// Index and index trend
Index = Foreign(index_symbol, "C", True);
IndexMA = EMA(Index,indexlen);
trailArray = Null;


// Buy and Sell conditions
Buy =  Ref(ROC(C,roclonglen),-1)>roclongval AND Ref(ROC(C,rocshortlen),-1)>rocshortval /*and NorgateIndexConstituentTimeSeries(index_symbol)*/
	  AND Index>IndexMA AND C<Ref(LLV(L,botw),-1) AND Ref(C,-1)>Ref(O,-1) AND C>MA(C,50);

//Sell = (((C>Ref(HHV(H,hlength),-1)) OR (BarsSince(Buy)>15) ) AND BarsSince(Buy)>minbars)  OR Ref(securityGoneToGod, 0);
Sell = 0;

// Position ranking if portolio is full
PositionScore =  (StDev(log(C/Ref(C,-1)),rocshortlen)*(52^.5)*100) - RSI(2);

stop_amount = IIf(Ref(C<O,-1), 5, 99);// percent stop amount
exitatstop = 2;
volatile = True;
ApplyStop(stopTypeLoss, stopModePercent, stop_amount, exitatstop, volatile, 0,4,-1,0);

Plot( C, "Price", colorDefault, styleCandle );

// Plotting values
if ( Status("action") == actionIndicator ) {
	eq = Equity(2); // THIS EVALUATES STOPS
	PlotShapes(IIf( Ref(Buy,0), shapeUpArrow, shapeNone), colorYellow, 0, L,-50);
	PlotShapes(IIf( Ref(Sell,0), shapeDownArrow, shapeNone), colorRed, 0, H,-50);
	PlotShapes(IIf( Ref(Buy,0), shapeHollowSmallSquare, shapeNone), colorWhite, 0, BuyPrice,0);
	PlotShapes(IIf( Ref(Sell,0), shapeHollowSmallSquare, shapeNone), colorWhite, 0, SellPrice,0);
	PlotShapes(((Sell==2) AND Ref(C<O,-1)) * shapeSmallSquare, colorOrange, 0, H, 70);
	Plot( .5, "Ribbon", IIf(Index>IndexMA, colorGreen, IIf( Index<IndexMA, colorRed, 0 )), styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );

	for( i = 1; i < BarCount; i++ )
	{
		if( Buy[i] )
			PlotText( "Buy\n" + BuyPrice[i], i, L[ i ], colorWhite, colorDefault, -15 );
		if( Sell[i] ) PlotText( "Sell\n" + SellPrice[i], i, H[ i ], colorWhite, colorDefault, 20 );
	}
}

31

Thank you so much for your help!

stop_amount = IIf(Ref(C<O,-1), 5, 99);// percent stop amount

Made it work :slight_smile:

Apologies for my poor coding structure. Have a great evening!

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.