Trades are not getting squared off correctly in Back-Testing

Hi EveryOne,

Facing issue like while back-testing some of the trades are not getting squared off according to the strategy. And hence finding difficulty in evaluating the strategy robustness. For example ... if Trailing Stop Loss is designated at 2% and stop-loss is placed at-40% of Buy-Price. Still trade is not getting squared off at Trailing Stop-Loss Level. It is waiting for price to drop down all the way up to stop- loss level. Trailing stop-loss is getting plotted very well on chart.

Second problem faced is "ShapeUpArrow" for BuyPrice and "ShapeDownArrow" for ShortPrice is not getting plotted at few places. Some places it is getting plotted wisely. But found it is missing & not plotted at few places.

Please guide how to overcome these issues.

Thanks & Regards,
Tushar Gawankar

No one can possibly help you if you don't post your code.

Thanks for the suggestion.

Please find below the code on which I am working ...

Please guide ....

_SECTION_BEGIN("Donchian Breakout Strategy - Intra Bar Execution");

_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
SetChartOptions(0,chartShowArrows|chartShowDates); //Enable X-Axis (Date/Time Axis)

Plot(Close,"Candles",colorDefault,styleCandle); //Plot Candles

OptimizerSetEngine("spso");
OptimizerSetOption("Runs", 1 );
OptimizerSetOption("MaxEval", 100 );

SetChartOptions(0,chartShowArrows|chartShowDates);

HA_Close[0]=(High[0]+Low[0]+Open[0]+Close[0])/4;
HA_Open[0]=(Open[0]+Close[0])/2;
HA_High[0]=Max(High[0],Max(HA_Open[0],HA_Close[0]));
HA_Low[0]=Min(Low[0],Min(HA_Open[0],HA_Close[0]));

for( i = 1; i < BarCount; i++ )
{
HA_Close[i]=(High[i]+Low[i]+Open[i]+Close[i])/4;
HA_Open[i]=(HA_Open[i-1]+HA_Close[i-1])/2;
HA_High[i]=Max(High[i],Max(HA_Open[i],HA_Close[i]));
HA_Low[i]=Min(Low[i],Min(HA_Open[i],HA_Close[i]));
}

_SECTION_BEGIN("Bollinger");

r1 = Optimize("BolliTop", 143, 5, 300, 1);
r2 = Optimize("BolliBot", 29, 5, 300, 1);

BolliTop = BBandTop(C,143,3);
BolliBot = BBandBot(C,29,1);

Plot(BolliTop, "Bollinger Top", ColorGreen, StyleLine, 0,0,0,0);
Plot(BolliBot, "Bollinger Bot", ColorRed, StyleLine, 0,0,0,0);
//Plot(ATR(Periods), "Bollinger Bot", ColorBlue, StyleLine, 0,0,0,0);

d1 = DateNum() > Ref(DateNum(),-1);
to = ValueWhen(d1,O,1) ; //Today's Open Price
YC = abs(Ref(Close,-1)); // Yesterday's Close Price
PAR7 = Param("No Trade Gap%",5,1,20,1);
PAR8 = Param("No1 Trade Gap%",-0.5,-0.1,-5.00,-0.1);
gap1 = abs( ((to-YC)/to)*100 );
P7 = Optimize("SL %", 27.27,.01,100,.01)/100;
PAR9 = Param("No Trade Gap%",-5,-1,-20,-1);
PAR10 = Param("No2 Trade Gap%",0.5,0.1,5.00,0.1);

Plot(EMA(Close,200),"EMA-200",colorGold , styleLine | styleThick); //Plot Very Long EMA lines

StopLevel = 1 - Optimize("trailing sto %", 6.1, 0.1, 10, 0.1)/100;

Buy = (Cross(High,Bollitop)) AND (HA_Close > HA_Open) AND (PAR8 < gap1 AND gap1 < PAR7) AND Close >= EMA(Close,200);

BuyPrice = ValueWhen(Buy,Close);
Plot(BuyPrice, "BuyPrice", colorGreen, styleLine);

Sell1 = 0;
TrailArray = Null;
TrailStop = 0;

for(i=1; i<BarCount; i++)
{

if(trailstop == 0 AND Buy[i])
{
	trailstop = High[i]*stoplevel;
}
//else Buy[i] = 0 // Remove Excess Buy Signals

if (TrailStop > 0 AND Low[i] < TrailStop)
{
	Sell1[i] = 1;
	SellPrice1[i] = TrailStop;
	TrailStop = 0;
}

if(TrailStop > 0)
{
	trailstop = Max(High[i]*stoplevel, trailstop);	
	trailarray[i] = trailstop;
}	

}

Plot(trailArray, "Trailing Stop Level",colorWhite);

Sell = (L < (BuyPrice*(1-P7))) OR (Cross(Low,TrailArray));

SellPrice = ValueWhen(Sell,Close);
Plot(SellPrice, "SellPrice", colorRed, styleLine);

StopLevel1 = 1 + Optimize("trailing sto1 %", 6.6, 0.1, 10, 0.1)/100;

Short = (Cross(BolliBot,Low)) AND (HA_Close < HA_Open) AND par10 < gap1 < par9 AND Close <= EMA(Close,200);

ShortPrice = ValueWhen(Short,Close);
Plot(ShortPrice, "ShortPrice", colorBlue, styleLine);

Cover1 = 0;
TrailArray1 = Null;
TrailStop1 = 0;

for(i=1; i<BarCount; i++)
{

  if(trailstop1 == 0 AND Short[i])
  {
	trailstop1 = Low[i]*stoplevel1;
  }
//else Buy[i] = 0 // Remove Excess Buy Signals

  if (TrailStop1 > 0 AND High[i] > TrailStop1)
  {
	  Cover1[i] = 1;
	  CoverPrice1[i] = TrailStop1;
	  TrailStop1 = 0;
  }

  if(TrailStop1 > 0)
  {
	  trailstop1 = Min(Low[i]*stoplevel1, trailstop1);	
	  trailarray1[i] = trailstop1;
  }	

}

Plot(trailArray1, "Trailing Stop Level",colorOrange);

Cover = (H > (ShortPrice*(1+P7))) OR (Cross(High,TrailArray1));

CoverPrice = ValueWhen(Cover,Close);
Plot(CoverPrice, "CoverPrice", colorYellow, styleLine);

Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);

Buycont = Flip(Buy,Sell);
Sellcont = Flip(Sell,Buy);
Shortcont = Flip(Short,Cover);
Covercont = Flip(Cover,Short);

BuyPrice = Close;
SellPrice = Close;
ShortPrice = Close;
CoverPrice = Close;

SetTradeDelays(1,1,1,1);

SetPositionSize(30000, spsValue);

/* Plot Buy and Sell Signal Arrows */

PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Cover, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);

PlotShapes(IIf(Short, shapeSquare, shapeNone),colorBlue, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorYellow, 0, L, Offset=-40);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Cover, shapeUpArrow, shapeNone),colorBlack, 0,L, Offset=-45);

_SECTION_END();

_SECTION_END();

If some one can help me ...
I am getting at least one big false trade & due to that I am not able to check the strategy robustness.

Please guide me exactly where I am going wrong ...

Are you certain about that?

Your code may have other issues as well, but the line above and others that are similar are almost certainly incorrect. Your stop level is set to 6%, so that means your trailstop is set to 6% of the high price, i.e. a 94% loss. You probably wanted to set the trail stop to:

trailstop = High[i]*(1-stoplevel);

Thanks for the Solution.
But after trying with trailstop = High[i]*(1-stoplevel);
//instead
trailstop = High[i]*stoplevel;

It started showing further issues on chart. You can try once at your end.

Original problem I am facing is as follows :slight_smile:

  1. Trailing Stop Loss is getting plotted very well on chart but Not Always ...

  2. Few places trailing stop level is not getting plotted;

  3. One More Issue : Trade is not getting squared off despite having trailing stop level in place. That means trade is not getting squared off at Trailing Stop level despite getting plotted on chart. Instead it is waiting for price to drop down up to "Main Stop Loss Level". This is happening in Back-Testing. And hence I am not able to check robustness of the strategy.

  4. Also few places, "ShapeUpArrow" & "ShapeDownArrow" are not getting plotted. Trailing stop levels are getting plotted right from trade point. But finding "ShapeUpArrow" for "Buy" trade & "ShapeDownArrow" for "Short" trades missing. This is happening in few cases only. Majority of the times they are plotted on chart. But it is impacting my back-testing.

Please guide me with your valuable time, knowledge & expertise....

If I had time to help troubleshoot I would give it a shot.

I would start with backtest, then worry about plotting. Have to realize the two are completely different. Backtest will handle redundant signals,position sizing etc. Separate the two. Get the backtest working as you think it should run.

May need the equity() function for plotting.
https://www.amibroker.com/guide/afl/equity.html

Do believe I have seen other answers here with plotting a system using that function for stops.

No, it is not incorect.
Before the loop stoplevel is defined as 1-p/100 as well as 1+p/100 already.

The (looping) code basically is a copy of trailing stop from AmiBroker KB.
https://www.amibroker.com/kb/2007/03/24/how-to-plot-a-trailing-stop-in-the-price-chart


@tushargawankar,

your problem is that you copy and pasted multiple code and mix it together without knowing what you are doing.

First of all you trailing stop will not work because you renamed variables to Sell1, SellPrice1 and Cover1, CoverPrice1.
How it that supposed to work? They have no use anywhere.

And this


Sell = (L < (BuyPrice*(1-P7)))

and

Cover = (H > (ShortPrice*(1+P7)))

is not proper stop loss code.

Use ApplyStop (or looping for actual custom stops).

Basicallly all stop code that you want to include can be written via ApplyStop.
You do not need loop.


And as aside if you copy code from AmiBroker KB or elsewhere then you should mention via link in the code.

Thanks for the valuable guidance. I quickly removed the loop & rewritten the whole code as a new strategy.

While using ApplyStop for Max StopLevel & Trailing Stop Level, tried following 2 statements for BuyStop :slight_smile:

ApplyStop(stopTypeLoss, stopModePercent, 1-Optimize("Max StopLevel", 65, 1, 100, 1),1);
ApplyStop(stopTypeTrailing, stopModePercent, 1-Optimize("Trailing StopLevel", 15, 1, 15, 1),1,1);
Then ...
Sell = Cross(StopTypeTrailing,Low) OR Cross(StopTypeLoss,Low);

For ShortStop :slight_smile:
ApplyStop(stopTypeLoss, stopModePercent, 1+Optimize("Max1 StopLevel", 24, 1, 100, 1),1);
ApplyStop(stopTypeTrailing, stopModePercent, 1+Optimize("Trailing1 StopLevel", 9, 1, 15, 1),1,1);
Then ...
Cover = Cross(High,StopTypeTrailing) OR Cross(High,StopTypeLoss);

But not getting the expected results ...
Don't know whether it is a right way to write it ...

Searched for the exact way to utilize "ApplyStop" but not found in the codes available in library.

I will be grateful if can correct me & show me the right way to utilize "ApplyStop".

You should not search in library first but you should search in manual and in AmiBroker Knowledge base first. There you have lots of ApplyStop examples already.
Also this forum has lots of examples already.

So when you say you didn't find something then it is not equal to nothing exists. There are lots and lots of examples. Saying nothing exists is incorrect!

Also if you insert code in forum then you should apply code tags. Please do so.
Please read forum rules.


First your code is incorrect. Second BuyStop is something different than stop loss. You mean stop loss.
So to get stop loss (fix SL and trailing SL) with different amount for long and short:

Sell = Cover = 0;

amountSL_long = Optimize("Max Stop Amount Long", 65, 1, 100, 1);
amountTrail_long = Optimize("Trailing Stop Amount Long", 15, 1, 15, 1);
amountSL_short = Optimize("Max Stop Amount Short", 24, 1, 100, 1);
amountTrail_short = Optimize("Trailing Stop Amount Short", 9, 1, 15, 1);

ApplyStop(stopTypeLoss, stopModePercent, IIf(Buy, amountSL_long, amountSL_short), 1);
ApplyStop(stopTypeTrailing, stopModePercent, IIf(Buy, amountTrail_long, amountTrail_short), 1);

Thank you so much for the guidelines. This will certainly help me.
Also I will ensure & shall follow the Forum rules for further correspondence ..
Many thanks again for the help & guidance provided ..