Advice on ATR trailing stop on futures

I am trying to visualize ATR trailing stop on 5 minutes futures data.

But sometimes the visualization doesnot match the backtest. For example:

ATRstop

In number 1 I should be out earlier as Low was lower than stop-line.
In number 2 the exit does not correspond with the stop-line at all.

The code I am using:

_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();


SetTradeDelays(0,0,0,0);
SetPositionSize(1, spsShares);  

tn = TimeNum();
dn = DateNum();

Buy =  tn==090000;
BuyPrice = O;
Sell = dn != Ref(dn,1);
SellPrice = Close;

stopLoss=3*Ref(ATR(5),-1);

ApplyStop(stopTypeTrailing, stopModePoint, stopLoss, True, True );

Equity( 1, 0 ); 

InTrade = Flip( Buy, Sell );

SetOption("EveryBarNullCheck", True );
stopline = IIf( Ref(InTrade,-1), HighestSince( Buy, H-stopLoss), Null );

PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);
PlotShapes(Sell*shapeDownArrow,colorRed,0,High);

Plot( stopline, "trailing stop line", colorRed );

Any hint why is not the ApplyStop function showing the same results like the plot function?

Thank you.

Hi @peterfin,

It's been a while since I looked at backtesting stuff, so I'm a little bit rusty.

Have another read of the AB User Manual on the ApplyStop() function, and try the following code, to see if the slight changes I've made actually get you "out" on the stop line:

SetTradeDelays(0,0,0,0);
SetPositionSize(1, spsShares);  

tn = TimeNum();
dn = DateNum();

//Buy =  tn==090000;
// My intra-day data doesn't have bars at nice round min:sec boundaries -> need to know when it's in the "zone"
cnsEntryTime	= 090000 ;
Buy =  (tn >= cnsEntryTime) AND (Ref(tn, -1) < cnsEntryTime) ;	
BuyPrice = O;

// This looks into the future - _not_ a good idea, especially for backtesting, search for topic on "future leak"
//Sell = dn != Ref(dn,1);		
Sell = dn != Ref(dn, -1);	// This gets you out the next day, but there's no future leak.
SellPrice = Close;

stopLoss=3*Ref(ATR(5),-1);

// This doesn't look "right" - read the help docs again, do some experimenting.
//ApplyStop(stopTypeTrailing, stopModePoint, stopLoss, True, True );
SetOption( "ActivateStopsImmediately", False) ;
ApplyStop(stopTypeTrailing, stopModePoint, stopLoss, 1, False);

Equity( 1, 0 ); 

InTrade = Flip( Buy, Sell );

SetOption("EveryBarNullCheck", True );
stopline = IIf( Ref(InTrade,-1), HighestSince( Buy, H-stopLoss), Null );

PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);
PlotShapes(Sell*shapeDownArrow,colorRed,0,High);

Plot( stopline, "trailing stop line", colorRed );
1 Like