// Downloaded From https://www.WiseStockTrader.com
_SECTION_BEGIN("MACD_SignalLineWithStopLoss&Target&buyPrice");
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() );

SL=Param("trailing stop %", 0.4, 0.1, 10, 0.1);
StopLevel1 = 1 - SL/100;
StopLevel2 = 1 + SL/100;

FirstEMAPeriod= Param("FirstEMAPeriod",5,1,100,1);
SecondEMAPeriod=Param("SecondEMAPeriod",10,1,100,1);

EMA5= EMA(C,FirstEMAPeriod);
EMA10= MA(C,SecondEMAPeriod);

EMA5P=Ref(EMA(C,FirstEMAPeriod),-1);
EMA10P=Ref(MA(C,SecondEMAPeriod),-1);

Buy1=EMA10P>=EMA5P AND EMA10<EMA5;
Sell1=EMA10P<=EMA5P AND EMA10>EMA5; 


Buy=Buy1;

Short=Sell1;


Sell=0;
Cover=0;
trailARRAY =trailARRAYs= Null;
trailstop =tstop= 0;

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

   if( trailstop == 0 AND Buy[ i ] ) 
   { 
      trailstop = High[ i ] * stoplevel1;
   }
   else Buy[ i ] = 0; // remove excess buy signals

   if( trailstop > 0 AND (Low[ i ] < trailstop OR Sell1[i]) )
   {
      Sell[ i ] = 1;
      SellPrice[ i ] = trailstop;
      trailstop = 0;
   }

   if( trailstop > 0 )
   {   
      trailstop = Max( High[ i ] * stoplevel1, trailstop );
      trailARRAY[ i ] = trailstop;
   }
	if( tstop == 0 AND Short[ i ]) 
   { 
      tstop = Low[ i ]*stoplevel2;
   }
   else Short[ i ] = 0; // remove excess buy signals

   if( tstop > 0 AND (High[i]>tstop OR Buy1[i]) )
   {
      Cover[ i ] = 1;
      CoverPrice[ i ] = tstop;
      tstop= 0;
   }

   if( tstop> 0 )
   {   
      tstop= Min( Low[ i ]*stoplevel2, tstop);
      trailARRAYs[ i ] = tstop;
   }
}
Plot(trailarray, "", colorGreen, styleThick);
Plot(trailarrays, "", colorRed, styleThick);

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( Sell, shapeDownArrow, shapeNone ), colorRed, 0, H, Offset = -65 );

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, shapeUpArrow, shapeNone ), colorBlue, 0, L, Offset = -65 );
_SECTION_END();