i Need to add trailing stop loss coding in this strategy. Also pls rectify if any error with this code.
N = Optimize(“ATR”,Param(“ATR”,19,1,20,1,0),1,20,1);
K = Optimize(“Factor”,Param(“Factor”,2.4,0.5,5,0.05,0),0.5,5,0.05);
f=ATR(n);
/*R Resistance */
R[0] = C[0];
/*S Support */
S[0] = C[0];
for( i = n+1; i < BarCount; i++ )
{
R[i]=R[i-1];
S[i]=S[i-1];
if (( S[i-1]<=C[i-1]) AND (C[i-1] <=R[i-1] ) AND (C[i-1]+k*f[i-1])<=RV)
R[i] = C[i-1]+k*f[i-1];
if (( S[i-1]<=C[i-1]) AND (C[i-1]<=R[i-1] ) AND (C[i-1]-k*f[i-1])>=SV)
S[i]= C[i-1]-k*f[i-1];
if ( C[i-1] >R[i-1] )
{
R[i] = C[i-1]+kf[i-1];
S[i]= C[i-1]-kf[i-1];
RV=R[i];
SV=S[i];
}
if ( C[i-1] <S[i-1] )
{
R[i] = C[i-1]+kf[i-1];
S[i]= C[i-1]-kf[i-1];
RV=R[i];
SV=S[i];
}}
Buy=cover = Close>R;
Short=Sell= Close<S;
Buy[BarCount-1]=Null;
Sell[BarCount-1]=Null;
Short[BarCount-1]=Null;
Cover[BarCount-1]=Null;
Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);
short=ExRem(short,cover);
cover=ExRem(cover,short);
Long=Flip(Buy,Sell);
Shrt=Flip(Short,Cover);
Relax = NOT Long AND NOT Buy AND NOT shrt AND NOT Sell AND NOT Sell AND NOT Cover;
Plot(IIf(long,S,Null), “Sup:”,colorGreen,styleDots|styleNoLine);
Plot(IIf(shrt,R,Null), “Rez:”,colorRed,styleDots|styleNoLine);
BarsSincebuy = BarsSince( Buy );
BarsSinceshort = BarsSince( Short );
LastSignal = IIf( BarsSincebuy < BarsSinceshort, 1, -1 );
BuyPrice=ValueWhen(Buy,C);
SellPrice=ValueWhen(Sell,C);
ShortPrice=ValueWhen(Short,C);
CoverPrice=ValueWhen(Cover,C);
Title = EncodeColor(colorWhite)+ Name() + " - " + EncodeColor(colorRed)+ Interval(2) + EncodeColor(colorWhite) +
" - " + Date() +" - “+”\n" +EncodeColor(colorwhite) +“Op-”+O+" “+“Hi-”+H+” “+“Lo-”+L+” "+
“Cl-”+C+" "+ “Vol= “+ WriteVal(V)+”\n”+
EncodeColor(colorLime)+
WriteIf (Buy , " GO LONG / Reverse Signal at “+C+” “,”")+
WriteIf (Sell , " EXIT LONG / Reverse Signal at “+C+” “,”")+"\n"+EncodeColor(colorYellow)+
WriteIf(Sell , “Total Profit/Loss for the Last Trade Rs.”+(C-BuyPrice)+"","")+
WriteIf(Buy , “Total Profit/Loss for the Last trade Rs.”+(SellPrice-C)+"","");
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
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);
Plot( Close, “Price”, Colorwhite, stylebar );
_SECTION_END();