//===========================================================================================================================//
#property copyright "Rodolfo Leonardo"
#property link      "rodolfo.leonardo@gmail.com"
//===========================================================================================================================//
extern string  Comment_1 = "settings";
extern int     Plus= 50;
extern int     TakeProfit = 300;
extern int     Distanciya = 300;
extern double  Lots    = 0.00;
extern double  Percent    = 1;

extern bool    Martin     = true;

extern string  Comment_2 = "signalStoch";
extern bool    SignalStoch = true;
extern int     Stoch_k = 10;
extern int     Stoch_d = 3;
extern int     Stoch_slowing = 3;
extern int     Stoch_pricefield = 0;//Price field parameter. Can be one of this values: 0 - Low/High or 1 - Close/Close.
extern int     Stoch_shift = 0;// Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago).
extern int     Stoch_lo = 30 ;
extern int     Stoch_up = 70 ;

extern string  Comment_3 = "SignalMegaFX";
extern bool    SignalMegaFX = true;
extern int     PeriodMegaFX = 6 ;
int  mper[10]={0,1,5,15,30,60,240,1440,10080,43200};

extern string  Comment_4 = "signalProc";
extern bool    Proc    =true;
extern double  Procent    =1.3;

extern string  Comment_5 = "Monitor";
extern color   background_color = Red;
extern bool    Monitor =  true;
extern int     CORNER = 0;
extern int     Slip=2;
extern int     Magic=1;

extern bool Trade_in_Monday  =true; 
extern bool Trade_in_Tuesday =true; 
extern bool Trade_in_Wednesday=true;
extern bool Trade_in_Thursday=true; 
extern bool Trade_in_Friday  =true;

extern string StartHour = "00:00"; 
extern string EndHour   = "23:00";  

extern double MaxSpread = 24.0; // Maximo de Spread p/ abertura de Ordem

double var_g_d__unused_220 = 0.01;
double var_g___maxlot_228 = 0.01;
double var_g___lotstep_236 = 0.01;
int var_g_i__unused_244 = 100000;
double var_g___marginrequired_248 = 1000.0;
double var_g_d__256 = 0.0001;
bool var_g_i__264 = FALSE;
double var_g___minlot_268 = 0.0;
double var_g_d__unused_276 = 0.0;
int var_g_i__unused_284 = 0;
int var_g___lotsize_288 = 0;
int var_g___stoplevel_292 = 0;

 bool Gi_596 = true;
int start() 
  {
  
    //Caso o spreed seja maior que o parametrizado foge
   double vSpread = MarketInfo(Symbol(), MODE_SPREAD);
   if (vSpread > MaxSpread ) return (0);
   
    if(!TimeFilter()) return (0);
     if(!IsExpertEnabled()) return (0);
     
     
double Lots_New=0;
 string Symb   =Symbol();               
   double One_Lot=MarketInfo(Symb,MODE_MARGINREQUIRED);
   double Min_Lot=MarketInfo(Symb,MODE_MINLOT);
   double Step   =MarketInfo(Symb,MODE_LOTSTEP);
   double Free   =AccountFreeMargin();      
   
    var_g___stoplevel_292 = MarketInfo(Symbol(), MODE_STOPLEVEL);
      var_g___minlot_268 = MarketInfo(Symbol(), MODE_MINLOT);
      var_g___maxlot_228 = MarketInfo(Symbol(), MODE_MAXLOT);
      var_g___lotsize_288 = MarketInfo(Symbol(), MODE_LOTSIZE);
      var_g___lotstep_236 = MarketInfo(Symbol(), MODE_LOTSTEP);
      var_g___marginrequired_248 = MarketInfo(Symbol(), MODE_MARGINREQUIRED);
                                          
//--------------------------------------------------------------- 3 --
   if (Lots<0)                               
     {                                        
      double Money=Lots*One_Lot;          
      if(Money<=AccountFreeMargin())         
         Lots_New=Lots;                   
      else                                
         Lots_New=MathFloor(Free/One_Lot/Step)*Step;
     }
//--------------------------------------------------------------- 4 --
   else                                    
     {     
    
      if (Percent > 100)                  
         Percent=100;                    
      if (Percent==0)                
         Lots_New=Min_Lot;                  
      else                      
         //Lots_New=MathFloor(Free*Percent/100/One_Lot/Step)*Step;//����
          Lots_New = MathMax(var_g___minlot_268, MathMin(var_g___maxlot_228, MathCeil(MathMin(100, Percent) / 100.0 * AccountFreeMargin() / var_g___lotstep_236 / (var_g___lotsize_288 / 100)) * var_g___lotstep_236));
        // Lots_New=CalculaQtdLotesRisco(Percent);
     }
//--------------------------------------------------------------- 5 --
   if (Lots_New < Min_Lot)                  
      Lots_New=Min_Lot;                  
   if (Lots_New*One_Lot > AccountFreeMargin())
     {                                         
      return(false);                        
     }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
   ObjectCreate("R",OBJ_LABEL,0,0,0);
   ObjectSet("R",OBJPROP_CORNER,2);
   ObjectSet("R",OBJPROP_XDISTANCE,10);
   ObjectSet("R",OBJPROP_YDISTANCE,10);
   ObjectSetText("R","ROBO X",15,"Arial Black",Red);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
   double opB=2000; double opS=0; double orderProfitbuy=0; double Sum_Profitbuy=0; double orderProfitsel;  double Sum_Profitsel; int orderType;
   double LotB=Lots_New;
   double LotS=Lots_New;
   int total=OrdersTotal();
   int b=0,s=0,n=0;
   for(int i=total-1; i>=0; i--)
     {
      if(OrderSelect(i, SELECT_BY_POS))
        {
         if(OrderSymbol()==Symbol()      )
           {
            n++;
            if(OrderType()==OP_BUY && OrderMagicNumber()==Magic)
              {
               b++;
               LotB=OrderLots();
               double ProfitB=OrderTakeProfit(); double openB=OrderOpenPrice();
               if(openB<opB)
                 {opB=openB;}
              }
            //---------------------------------      
            if(OrderType()==OP_SELL && OrderMagicNumber()==Magic)
              {
               s++;
               LotS=OrderLots();
              double ProfitS=OrderTakeProfit(); double openS=OrderOpenPrice();
               if(openS>opS)
                 {opS=openS;}
              }
           }
        }
     }
   double max = NormalizeDouble(iHigh(Symbol(),1440,0),Digits);
   double min = NormalizeDouble(iLow (Symbol(),1440,0),Digits);
   double opp=NormalizeDouble(iOpen(Symbol(),1440,0),Digits);
   double cl=NormalizeDouble(iClose(Symbol(),1440,0),Digits);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
   double dis   =NormalizeDouble(Distanciya*Point,Digits);
   double spred =NormalizeDouble(MarketInfo(Symbol(),MODE_SPREAD)*Point,Digits);
   double  CORR=NormalizeDouble(Plus            *Point,Digits);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//   
int sigup=0;
int sigdw=0;
int vSinalStoch = 0;
int vSinalMegaFX = 0;

if (SignalStoch == true)
{ 
   vSinalStoch =  Sinalstochastic();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
if (SignalMegaFX == true)
{
     vSinalMegaFX =  SignalMega();   
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
if (Proc    ==true)
{
   if(cl>min) { double x=NormalizeDouble(cl*100/min-100,2); }
   if(cl<max) { double y=NormalizeDouble(cl*100/max-100,2); }
   
if (Procent*(-1)<=y&&Close[1]>Open[1]){ sigup=1; sigdw=0; }
if (Procent     >=x&&Close[1]<Open[1]){ sigup=0; sigdw=1; }  
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
   int f=0;
   if(Martin==true)
     {
        if (total==0){f=1    ;}
        if (total>=1){f=total;}
         LotB=LotB*f *2;
         LotS=LotS*f *2;
     }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
if(Martin==false)
  {
LotB=LotS;
LotS=LotB;
  }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// 


if (SignalStoch == true && SignalMegaFX == false){
   if((b==0&&sigup==1&&s==0 && vSinalStoch == 1)||(Ask<opB-dis+spred&&b>=1&&s==0)) { OrderSend(Symbol(),OP_BUY ,LotB,Ask,Slip,0,0,"Buy ",Magic,0,Green); }
   if((s==0&&sigdw==1&&b==0 && vSinalStoch == -1)||(Bid>opS+dis+spred&&s>=1&&b==0)) { OrderSend(Symbol(),OP_SELL,LotS,Bid,Slip,0,0,"Sell",Magic,0,Green); }
}

if (SignalStoch == true && SignalMegaFX == true){
   if((b==0&&sigup==1&&s==0 && vSinalStoch == 1 && vSinalMegaFX == 1)||(Ask<opB-dis+spred&&b>=1&&s==0)) { OrderSend(Symbol(),OP_BUY ,LotB,Ask,Slip,0,0,"Buy ",Magic,0,Green); }
   if((s==0&&sigdw==1&&b==0 && vSinalStoch == -1 && vSinalMegaFX == -1)||(Bid>opS+dis+spred&&s>=1&&b==0)) { OrderSend(Symbol(),OP_SELL,LotS,Bid,Slip,0,0,"Sell",Magic,0,Green); }
}

if (SignalStoch == false && SignalMegaFX == false){
   if((b==0&&sigup==1&&s==0 )||(Ask<opB-dis+spred&&b>=1&&s==0)) { OrderSend(Symbol(),OP_BUY ,LotB,Ask,Slip,0,0,"Buy ",Magic,0,Green); }
   if((s==0&&sigdw==1&&b==0 )||(Bid>opS+dis+spred&&s>=1&&b==0)) { OrderSend(Symbol(),OP_SELL,LotS,Bid,Slip,0,0,"Sell",Magic,0,Green); }
}


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
double TP= NormalizeDouble (spred+TakeProfit*Point,Digits);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
   for (int iq=total-1; iq>=0; iq--)
   {
    if(OrderSelect(iq, SELECT_BY_POS))
     {
      if(OrderSymbol()==Symbol()&&OrderMagicNumber()==Magic)
       {   
        if (OrderType()==OP_BUY  &&  OrderTakeProfit()==0 && b==1) 
         {
          OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),NormalizeDouble(OrderOpenPrice()+TP,Digits),0,Blue);  
         }     
        if (OrderType()==OP_SELL && OrderTakeProfit()==0 && s==1) 
         {
          OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),NormalizeDouble(OrderOpenPrice()-TP,Digits),0,Blue);  
         }
}}}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
double nn=0,bb=0;
for(int ui=total-1; ui>=0; ui--)
  {
   if(OrderSelect(ui,SELECT_BY_POS))
     {
      if(OrderSymbol()==Symbol())
        {
         if(OrderType()==OP_BUY && OrderMagicNumber()==Magic)
           {
            double op=OrderOpenPrice();
            double llot=OrderLots();
            double itog=op*llot;
            bb=bb+itog;
            nn=nn+llot;
            double factb=bb/nn;
           }
        }
     }
  }
double nnn=0,bbb=0;
for(int usi=total-1; usi>=0; usi--)
  {
   if(OrderSelect(usi,SELECT_BY_POS))
     {
      if(OrderSymbol()==Symbol())
        {
         if(OrderType()==OP_SELL && OrderMagicNumber()==Magic)
           {
            double ops=OrderOpenPrice();
            double llots=OrderLots();
            double itogs=ops*llots;
            bbb=bbb+itogs;
            nnn=nnn+llots;
            double facts=bbb/nnn;
           }
        }
     }
  }

for(int uui=total-1; uui>=0; uui--)
  {
   if(OrderSelect(uui,SELECT_BY_POS))
     {
      if(OrderSymbol()==Symbol())
        {
         if(b>=2 && OrderType()==OP_BUY && OrderMagicNumber()==Magic)
           {
            OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),factb+CORR,0,Blue);
           }
         if(s>=2 && OrderType()==OP_SELL && OrderMagicNumber()==Magic)
           {
            OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),facts-CORR,0,Blue);
           }
        }
     }
  }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
if ( Monitor == true )
{
Informacoes();
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//


void Informacoes() {
   double Ld_0;
   double Ld_8;
   double Ld_16;
   double Ld_24;
   double Ld_32;
   double Ld_40;
   double Ld_48;
   double Ld_56;
   string Ls_64;
   string Ls_72;
   int Li_84;

   if (!IsTesting() && !IsOptimization())
    {
     
      Ls_64 = "==========================\n";
      Ls_64 = Ls_64 + "               " + "ROBO BETA OOO v1.00" 
      + "\n";
      Ls_64 = Ls_64 + "==========================\n";
      for (int count_80 = 0; count_80 <= MathMod(Seconds(), 20); count_80++) Ls_72 = Ls_72 + "|";
      Ls_64 = Ls_64 + "  Status: RUNNING " + Ls_72 
      + "\n";
     
      + "\n";
      Ls_64 = Ls_64 + "==========================\n";
      //Ls_64 = Ls_64 + "  Base Lot Size: " + DoubleToStr(Gda_524[0], 2) + " lots\n";
     // Ls_64 = Ls_64 + "  Slippage: " + DoubleToStr(slippage, 2) + " pips\n";
      Ls_64 = Ls_64 + "==========================\n";
      Comment(Ls_64);
      //f0_38("Breakeven_buy", Ld_48, Green, "Breakeven Line");
      //f0_38("Breakeven_sell", Ld_56, Red, "Breakeven Line");
      Li_84 = 11;
    
      if (Gi_596 || Seconds() % 5 == 0) {
         Gi_596 = FALSE;
         for (int count_88 = 0; count_88 < 9; count_88++) {
            for (int count_92 = 0; count_92 < Li_84; count_92++) {
               ObjectDelete("background" + count_88 + count_92);
               ObjectDelete("background" + count_88 + ((count_92 + 1)));
               ObjectDelete("background" + count_88 + ((count_92 + 2)));
               ObjectCreate("background" + count_88 + count_92, OBJ_LABEL, 0, 0, 0);
               ObjectSetText("background" + count_88 + count_92, "n", 30, "Wingdings", background_color);
               ObjectSet("background" + count_88 + count_92, OBJPROP_XDISTANCE, 20 * count_88);
               ObjectSet("background" + count_88 + count_92, OBJPROP_YDISTANCE, 23 * count_92 + 9);
            }
         }
      }
   }
}

// tamanho de ponto na moeda de cota��o
double TamanhoPonto(string a_symbol_0 = "0") 
{
   if (a_symbol_0 == "0") a_symbol_0 = Symbol();
   int digits_8 = MarketInfo(a_symbol_0, MODE_DIGITS);
   double vretorno = 0.0;
   double vMODE_POINT = MarketInfo(a_symbol_0, MODE_POINT);
   if (digits_8 == 5 || digits_8 == 3) vretorno = 10.0 * vMODE_POINT;
   else vretorno = vMODE_POINT;
   return (vretorno);
}


bool TimeFilter(){

 bool _res = false;
   datetime _time_curent = TimeCurrent();
   datetime _time_start = StrToTime(DoubleToStr(Year(),0)+"."+DoubleToStr(Month(),0)+"."+DoubleToStr(Day(),0)+" "+StartHour);
   datetime _time_stop = StrToTime(DoubleToStr(Year(),0)+"."+DoubleToStr(Month(),0)+"."+DoubleToStr(Day(),0)+" "+EndHour);
   if(((Trade_in_Monday==true) && (TimeDayOfWeek(Time[0]) == 1)) ||
   ((Trade_in_Tuesday==true) && (TimeDayOfWeek(Time[0]) == 2)) ||
   ((Trade_in_Wednesday==true) && (TimeDayOfWeek(Time[0]) == 3)) ||
   ((Trade_in_Thursday==true) && (TimeDayOfWeek(Time[0]) == 4)) ||
   ((Trade_in_Friday==true) && (TimeDayOfWeek(Time[0]) == 5)))
   
   
   if(_time_start > _time_stop){
      if(_time_curent >= _time_start || _time_curent <= _time_stop) _res = true;
   }else   
      if(_time_curent >= _time_start && _time_curent <= _time_stop) _res = true;
      
      return(_res); 
  
 }        
 



int Sinalstochastic() {

   double istochastic_0 = iStochastic(Symbol(), 0, Stoch_k, Stoch_d, Stoch_slowing, MODE_SMA, Stoch_pricefield, MODE_SIGNAL, Stoch_shift);
   int vret = 0;
     if (istochastic_0 > Stoch_up) vret= -1;
      if (istochastic_0 < Stoch_lo) vret= 1;
 
   return (vret);
}


int SignalMega()
{
  int   MegaFX = iCustom(Symbol(),mper[PeriodMegaFX],"mega_fx",6,0);

  return(MegaFX);      
}

double SomaOrderProfitDoDia() {
   int day_0 = Day();
   double ld_ret_4 = 0;
   for (int pos_12 = 0; pos_12 < OrdersHistoryTotal(); pos_12++) {
      OrderSelect(pos_12, SELECT_BY_POS, MODE_HISTORY);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != Magic) continue;
      if (TimeDay(OrderOpenTime()) == day_0) ld_ret_4 += OrderProfit();
   }
   return (ld_ret_4);
}

int SomaTrades() {
   int count_0 = 0;
   for (int pos_4 = 0; pos_4 < OrdersTotal(); pos_4++) {
      OrderSelect(pos_4, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != Magic) continue;
      count_0++;
   }
   return (count_0);
}

//Calcula a quantidade de lotes  conforme o risco
double CalculaQtdLotesRisco(double vRiskPercent) 
{
   bool vTrailingStop = TRUE;
   double minlot_12 = MarketInfo(Symbol(), MODE_MINLOT);
   double vMODE_POINT = MarketInfo(Symbol(), MODE_LOTSIZE) / AccountLeverage();
   double ld_28 = vRiskPercent / 100.0 * AccountBalance() / vMODE_POINT;
   double vRetorno = MathFloor(ld_28);
   while (vTrailingStop) 
   {
      vRetorno += minlot_12;
      if (vRetorno > ld_28) 
      {
         vTrailingStop = FALSE;
         vRetorno -= minlot_12;
      }
   }
   return (vRetorno);
}