SetTradeDelays(0,0,0,0);
SetOption("CommissionMode",3);
SetOption("CommissionAmount",2.32);
SetOption("FuturesMode",True);
NumContracts=1;
PositionSize=NumContracts*MarginDeposit;
SetOption("MaxOpenPositions",4);
OptimizerSetEngine("cmae");
p1=Optimize("Period 1",7,1,20,1);
p2=Optimize("Period 2",17,10,50,1);
res1=HHV(H,p1);
sup1=LLV(L,p1);
tsl1=IIf(ValueWhen(IIf(C>Ref(res1,-1),1,IIf(C<Ref(sup1,-1),-1,0))!=0,IIf(C>Ref(res1,-1),1,IIf(C<Ref(sup1,-1),-1,0)),1)==1,sup1,res1);
res2=HHV(H,p2);
sup2=LLV(L,p2);
tsl2=IIf(ValueWhen(IIf(C>Ref(res2,-1),1,IIf(C<Ref(sup2,-1),-1,0))!=0,IIf(C>Ref(res2,-1),1,IIf(C<Ref(sup2,-1),-1,0)),1)==1,sup2,res2);
trend=IIf(C>tsl2,1,IIf(C<tsl2,-1,0));
Buy=C>tsl1 AND trend==1;Buy=Ref(Buy,-1);BuyPrice=O;
Sell=C<tsl1;Sell=Ref(Sell,-1);SellPrice=O;
Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);
Short=C<tsl1 AND trend==(-1);Short=Ref(Short,-1);ShortPrice=O;
Cover=C>tsl1;Cover=Ref(Cover,-1);CoverPrice=O;
Short=ExRem(Short,Cover);
Cover=ExRem(Cover,Short);
SetChartOptions(0,chartShowArrows|chartShowDates);
SetChartBkColor(colorBlack);
Plot( C, "Close", ParamColor("Color", colorLightGrey ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
Plot(tsl1,"", colorBlue, styleStaircase);
Plot(tsl2,"", colorYellow, styleStaircase);
PlotShapes(IIf(Buy,shapeUpArrow,shapeNone),colorDarkGreen,0,L,-15);
PlotShapes(IIf(Buy,shapeSmallCircle,shapeNone),colorWhite,0,BuyPrice,0);
PlotShapes(IIf(Sell,shapeDownArrow,shapeNone),colorRed,0,H,-15);
PlotShapes(IIf(Sell,shapeSmallCircle,shapeNone),colorWhite,0,SellPrice,0);
PlotShapes(IIf(Short,shapeSmallDownTriangle,shapeNone),colorRed,0,H,IIf(Short AND Sell,-30,-15));
PlotShapes(IIf(Short,shapeSmallCircle,shapeNone),colorWhite,0,ShortPrice,0);
PlotShapes(IIf(Cover,shapeSmallUpTriangle,shapeNone),colorDarkGreen,0,L,IIf(Cover AND Buy,-30,-15));
PlotShapes(IIf(Cover,shapeSmallCircle,shapeNone),colorWhite,0,CoverPrice,0);