Need help in Trailing Stop Loss

Dear Members,

I am looking for help with one of my Code in which i had defined Two exit parameters however as per the Back test report it did work well for almost 23 scrip however for last two scrip it failed to trigger trailing stop loss. i am sure i am missing some thing would request seniors to kindly help.

I am attaching the screen shot of 2 missed scrip and the Code which i used.

Also need a help for my requirement to exit the trade in below three condition which i have achieved partially .

  1. Exit 50% if the First profit % is achieved
  2. Exit another 50% if the Second profit % is achieved
  3. Exit 100% on trailing stop loss is hit.Untitled1 Untitled
_SECTION_BEGIN("30 Min Time Frame - Deepak Tiwari");
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g,Hi %g,Lo %g, Close %g (%.1f%%) 
Vol " +WriteVal( V, 1.0 ) +" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 )) ));

//Initial Capital & Risk//  
SetTradeDelays( 1, 0, 1, 0 );
SetOption("InitialEquity", 1500000);  
SetOption( "UsePrevBarEquityForPosSizing", 1 ); //*set the use of last bars
SetPositionSize( 10 , spsPercentOfEquity); // 10% positionsize
SetOption( "AllowPositionShrinking", True ); // Shrink Position on Loss // 
RoundLotSize = 1; // Lot Size // 
SetOption("RefreshWhenCompleted",True); // Refresh when completed // 

SetOption("CommissionMode", 1); // Percent Mode  
SetOption("CommissionAmount",0.30); // 0.30% of Trade Value  

var1=Close>Ref(Close,-1) AND Close>Ref(Close,-2);
var2=Ref(var1,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
var3=Ref(var2,-1) AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
var4=Ref(var3,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
var5=Ref(var4,-1) AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
var6=Ref(var5,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
var7=Ref(var6,-1) AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
var8=Ref(var7,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
var9=Ref(var8,-1) AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
varA=Ref(var9,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
varB=Ref(varA,-1) AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
varC=Ref(varB,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
varD=Close<Ref(Close,-1) AND Close<Ref(Close,-2);
varE= Ref(varD,-1)  AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
varF= Ref(varE,-1)  AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
var10=Ref(varF,-1)  AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
var11=Ref(var10,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
var12=Ref(var11,-1) AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
var13=Ref(var12,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
var14=Ref(var13,-1) AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
var15=Ref(var14,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
var16=Ref(var15,-1) AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
var17=Ref(var16,-1) AND Close<=Ref(Close,-1) AND Close>=Ref(Close,-2);
var18=Ref(var17,-1) AND Close>=Ref(Close,-1) AND Close<=Ref(Close,-2);
down=varD OR varE OR varF OR var10 OR var11 OR var12 OR var13 OR var14 
     OR var15 OR var16 OR var17 OR var18;

var19=Ref(varD OR varE OR varF OR var10 OR var11 OR var12 OR var13 OR 
     var14 OR var15 OR var16 OR var17 OR var18,-1) AND var1;

var1A=Ref(var1 OR var2 OR var3 OR var4 OR var5 OR var6 OR var7 OR 
     var8 OR var9 OR varA OR varB OR varC,-1) AND varD;

up=IIf(var1 OR var2 OR var3 OR var4 OR var5 OR var6 OR var7 OR var8 OR var9 OR varA OR varB OR varC,1,0);
barcolor =IIf(up, ParamColor("Up candlestick", colorBrightGreen ), ParamColor("Down candlestick", colorOrange ));
prevCloseValue = Ref(C,-1); 
//PlotOHLC( bot,top,bot,top, "Close", barColor);

//Buying Rules//
BuyPrice= LastValue(C);
Buy = Close > Ref(Close, -1) AND Ref(Close, -1) > Ref(Close, -2) AND Ref(Close, -1) < Ref(Close, -3) AND IIf(Ref(Close, -3) < Ref(Close, -4), 1, IIf(Ref(Close, -4) < Ref(Close, -5),Ref(Close, -1) < Ref(Close, -4) OR( Ref(Close, -2) < Ref(Close, -4) AND Ref(Close, -3) >= Ref(Close, -5) ),IIf(Ref(Close, -5) < Ref(Close, -6), 1,Ref(Close, -6) < Ref(Close, -7))));

//Selling Rules//
Sell = 0;
SellPrice = LastValue(C);

//Profit Booking//
ApplyStop( stopTypeProfit, stopModePercent, 4); //4% Profit Target

//Trailing StopLoss//
pctStop = 3; // 3% trailing stop loss.
pctStepSize = 3; // 3% trailing stop loss to Move further.
InLong = Flip(Buy, Sell);
InTrade = InLong;
entryPrice = ValueWhen(Buy, BuyPrice);
maxPctChange = 100 * (HighestSince(Buy,High) / entryPrice -1);
numSteps = floor(maxPctChange/pctStepSize );
highestStep = entryPrice * (1 + numSteps * pctStepSize/100);
StopLevel = iif( intrade , highestStep *(1- pctStop/100),Null);
Sell = Cover = 0; // 0 or False means exit only by ApplyStop

/* Remove excess signals */
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
//Short = ExRem(Short, Cover);
//Cover = ExRem(Cover, Short);
//InLong = Flip(Buy, Sell);
//InShort = Flip(Short, Cover);
//InTrade = InLong OR InShort;

PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ),  colorBrightGreen, layer = 0, yposition = bot, offset = -25  ); 
PlotShapes( IIf( Sell, shapeDownArrow, shapeNone ), colorRed, layer = 0, yposition = top, offset = -25  );

MaxGraph = 12;

BuyOffSet = 18;//Optimize("BuyOffSet",-18,-15,-20,-1);
SellOffset = BuyOffSet;//Optimize("SellOffset",-2,-2,-14,-2);
RegLength = 5;//Optimize("RegLength",5, 2,-11,-2);
BuyATRPeriod = 2;//Optimize("BuyATRPeriod",-2,-2,5,-1);
SellATRPeriod = BuyATRPeriod;//Optimize("SellATRPeriod",4,-2,-11,-2);
ATRMultiplier = 0.5;//Optimize("ATRMultiplier",-1,0.7,-1.25,.05);

Graph8 = HHV(H-ATRMultiplier*ATR(BuyATRPeriod),BuyOffset);
Graph9 = LLV(L+ATRMultiplier*ATR(SellATRPeriod),SellOffset); 

Graph8Style=Graph9Style = 1;
Graph9Color=  7;
Graph8Color = 6;

_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() ); 

I have already tested example 4 in, however it doesn't suite to my requirement as it apply the stoploss on purchase priced rather moving priced as per above example.

This might help you:

To add if you search this forum with keyword "Trailing Stop Loss", it will give you plenty of discussion and ideas - search link. There is this dedicated KB article on - How to plot a trailing stop in the Price chart.

Also avoid writing AFL this way - it is illegitimate - use loops instead:

Before anything else, please spend some time on these articles:

  1. Understanding how AFL works
  2. QuickAFL facts - It took a long time for me to realize the below graphic.:slightly_smiling_face:
  3. IIf function versus if statement
  4. Common Coding mistakes in AFL

Responding here such that the posts remain structured to the original query, instead of haphazard responses and discussions spread randomly over the Forum. It will concisely help future users going through the same learning curve.

In lieu of the same, if possible, requesting Moderator to please split the following three posts from another thread and merge those here (Thank You):

You're Welcome!

Sure take your time! Not so long back, I had also failed to take care, as basic a thing as, Magic Numbers in my AFLs, although I was aware of those concepts but still a kindhearted Expert had to correct me. Call it my negligence or lack of focus or lack of ability, whatever! It's okay, as long as you scale-up!

I am quite sure, if you implement the examples (as shown in the KB Article or from here) you will be able to easily Plot a TSL for your strategy. However, the reason I am writing this post is to highlight few other things that can be observed from your shared code.

  1. AFL is not a Low-Level Assembly Programming Language but when it comes to Speed, it is nothing less either. AFL is highly efficient Polymorphed (more here) Humane High-level Languange with unmatched Vector Processing power. When you write Codes as below, it is a bit of disrespect to the Person who has spent more than two decades of his life perfecting it. I know you did not mean it, but that's what it implies. :slightly_smiling_face:

Still not sure what you really want to attain from the above, aren't these functions available to meet your needs:


(Source: Categorized list of functions)

Kindly do not judge AFL from the perspective of your problem, it will be hard to find the solution, often, you will get stuck with the problem only. Rather understand AFL as it is, and you will automatically find a way to solve the problem.

  1. This other section of your code:

Hope you are going to run that many Optimizers responsibly, and have already done research for the same.

(Source: How to optimize trading system guide)

Also aware of:

Math 101: Over-fitting
Optimization and exploration together ?


It seems I have asked a stupid question which is too tough for expert to answer hence withdrawing the same.