// Downloaded From https://www.WiseStockTrader.com
SetOption("ActivateStopsImmediately",True);
SetOption("ReverseSignalForcesExit",True);
SetTradeDelays( 0,0,0,0 ) ;
Equity();

EMAfast = Param("First Period",9,3,21,1);
EMAslow = Param("Second Period",63,21,200,1);
// virada da média
EMA9 = EMA(Close,EMAFast);
EMA63 = EMA(Close,EMASlow);
Media = EMA9 - Ref(EMA9,-1);

//Inicializa Variáveis
SellPrice[0] = StopLoss[0] = Trend[0] = 0;
BuyPrice[0] = EntryPrice[0] = 100000;

for( i = 1; i < BarCount; i++ ) 
{ 
  //Recupera Valores 
  BuyPrice[i] = BuyPrice[i-1];
  SellPrice[i] = SellPrice[i-1];
  StopLoss[i] = StopLoss[i-1];
  Trend[i] = Trend[i-1];
  EntryPrice[i] = EntryPrice[i-1];

  //Calcula Tendência 
  if (Media[i]>0) Long[i]=1; else Long[i]=0;
  if (Media[i]<0) Shrt[i]=1; else Shrt[i]=0;


  if (Trend[i] < 1 AND (i>23)) 
  {
		//Virada para Cima
     	if ((Long[i]==1) AND (Long[i-1]==0))
  		{		
       		BuyPrice[i] = EntryPrice[i] = High[i]+0.01;   //Define Preço de Compra;
       		StopLoss[i] = Low[i]-0.01;    //Define Valor do Stop;
  		}
  		// Verifica entrada e dispara sinal de compra
  		if ((High[i]>=EntryPrice[i])) 
  		{    
				Trend[i] = 1; //Entrada no Modo Compra
       		EntryPrice[i] = 0;
  		}
  }
  if (Trend[i] == 1 AND (i>23))
  {
  		// Virada para Baixo
  		if ((Shrt[i]==1) AND (Shrt[i-1]==0)) 
       {
          		StopLoss[i] = Low[i]-0.01; 
      			SellPrice[i] = StopLoss[i];               //Define Preço de Venda para fins de Backtest.
       }          
		// Verifica se o STOP foi acionado
  		if ((Low[i]<=StopLoss[i])) 
  		{
      			SellPrice[i] = StopLoss[i];               //Define Preço de Venda para fins de Backtest.
				Trend[i] = -1;                        	//Sai do Modo Compra
      			StopLoss[i] = 0;
      			if (Long[i]==1) BuyPrice[i]= EntryPrice[i] = High[i]+0.01; 
else BuyPrice[i] = EntryPrice[i] = 100000; //Se Tendência de alta, arma nova Compra.
  		}

  }
} 
//Risk Manager
//PositionSize = (0.04 * Equity(0))/(BuyPrice-SellPrice)*BuyPrice;

//Trading System
Buy   = Trend == 1;
Sell  = Trend == -1;
Buy   = ExRem(Buy,Sell);
Sell  = ExRem(Sell,Buy);

T1    = ExRem(Long,Shrt);
T2    = ExRem(Shrt,Long);

//Plot(EMA9 ,"EMA-Fast", ParamColor("EMA-Fast Color", colorPaleBlue),styleThick);
Plot(EMA63,"EMA-Slow", ParamColor("EMA-Slow Color",colorRed),styleThick);

Entry = T1 * shapeSmallCircle + T2 * shapeSmallCircle;
PlotShapes(Entry, IIf(T1, colorBlue, colorBlack), 0, IIf( T1,Low, High));
PlotShapes( Buy* shapeUpArrow, IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy,Low, High) );
PlotShapes( Sell* shapeDownArrow, IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy,Low, High) );

// Explorer
Filter = T1 OR T2;
AddTextColumn(WriteIf(T1,"Buy",WriteIf(T2,"Sell","None")),"TS",colorGreen,colorBlue);
AddColumn(IIf(T1,BuyPrice,IIf(T2,SellPrice,0)),"START",5.2,colorWhite,colorBlue);
AddColumn(IIf(T1,SellPrice,IIf(T2,BuyPrice,0)),"STOP ",5.2,colorWhite,colorBlue);
AddColumn(EMA9, "EMAFast"+EMAFast,5.2,colorWhite,colorBlue);
AddColumn(EMA63,"EMASlow"+EMASlow,5.2,colorWhite,colorBlue);
AddColumn(RSI(2),"RSI(2)",2.2);


_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowDates|chartShowArrows|chartLogarithmic|chartWrapTitle);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ))+"\n"+ 
EncodeColor(colorBlue)+
WriteIf (T1 , " GO LONG   / "+EncodeColor(colorGreen)+"START "+Prec(BuyPrice,2)+" / "+EncodeColor(colorRed)+"STOP "+Prec(SellPrice,2)+"  ","")+
WriteIf (T2 , " EXIT LONG / "+EncodeColor(colorRed)+"STOP "+Prec(SellPrice,2)+"  ",""));

Plot( C, "", IIf(Close > Open, colorGreen, colorRed), styleBar + styleNoLabel);
_SECTION_END();

_SECTION_BEGIN("trending ribbon");
uptrend= Media > 0;
downtrend= Media < 0;
Plot( 2, "",IIf( uptrend, colorGreen, IIf( downtrend, colorRed, 0 )), styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );
_SECTION_END();

_SECTION_BEGIN("Background text");
GfxSetOverlayMode(1);
GfxSelectFont("Tahoma", Status("pxheight")/6 );
GfxSetTextAlign( 6 );// center alignment
GfxSetTextColor( ColorRGB( 60, 45, 80 ) );
GfxSetBkMode(0); // transparent
GfxTextOut( Name(), Status("pxwidth")/2, Status("pxheight")/12 );
GfxSelectFont("Tahoma", Status("pxheight")/12 );
//GfxTextOut( "EMA9.1 System", Status("pxwidth")/2, Status("pxheight")/3 );
GfxSelectFont("Tahoma", Status("pxheight")/20 );
_SECTION_END();