this might help to improve your thing not sure
this is my coding for ATR
I made for my market but looks good on NIFTY too 5 M
multi=Param("multi",2.5,0,10,0.25);
pds=Param("pds",10,1,252,1);
pds1=Param("pds1",21,1,252,1);
//plo=Param("plot",1,1,3,1);
adv=Param("todayTrailingStop",0,0,1,1);
delay=Param("delay",0,0,5,1);
//TrailingStop
StLong = HHV(C-multi*EMA(ATR(1),pds),pds1);
StShort = LLV(C+multi*EMA(ATR(1),pds),pds1);
stopLong = IIf(C<Ref(C,-1),StLong,Max(Stlong,Ref(StLong,-1)));
stopShort = IIf(C>Ref(C,-1),StShort,Min(StShort,Ref(StShort,-1)));
//Trade flags/signals
In = Cross(C,Ref(stopShort,-1));
Out = Cross(Ref(stopLong,-1),C);
Init = Cum(IsTrue(In+Out))==1;
x = ValueWhen((In-Out)!=0 OR Init,In-Out,1);
lg = x==1 AND ((x!=1 OR Ref(x,-1)!=1) OR Init);
Sh = x==-1 AND ((x!=1 OR Ref(x,-1)!=1) OR Init);
Signals = lg-Sh;
flag = ValueWhen(Signals!=0 OR Init, Signals,1);
//Switch between Long/Short stops
stop = Ref(IIf(flag==1,stopLong,stopShort),-1+adv);
//Plot(Ref(stopLong,-1+adv),"stopLong",colorRed,styleLine);
//Plot(Ref(stopShort,-1+adv),"stopShort",colorBrightGreen,styleLine);
Plot(stop,"stop",colorYellow,styleLine);
Buy = ExRem(lg,sh);
Sell = ExRem(Sh,Buy);
shapeB = Buy * shapeUpArrow + Sell * shapeDownArrow;
PlotShapes( shapeB, IIf( Buy, colorBrightGreen, colorOrange ), 0, IIf( Buy, Low, High ) );
GraphXSpace = 5;
_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", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();