//+------------------------------------------------------------------+
//|                                            Veinticinco_cacus.mq4 |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, Juan Cruz Baudino"
#property link      ""

extern int HoraComienzo = 3;
extern double Lotes = 0.10;
//extern double LotesRed = 0.01;
extern int rangoMaximo = 400;
extern int rangoMinimo = 200;
extern double divOP = 4;
extern double divTP = 2;
extern int Separacion = 10;
extern int noDia1 = 0;
extern int noDia2 = 0;
extern int noDia3 = 0;
extern int noDia4 = 0;
extern int TrailingStop = 0;
//extern int PeriodoMM = 200;
extern int numMagico = 10;

int init(){return(0);}
int deinit(){return(0);}
int start()
  {
  static datetime MarcaTiempo = 0;
   datetime NuevaTiempo = Time[0];
   // A cada nueva barra

TrailingAlls(TrailingStop);


    if(MarcaTiempo != NuevaTiempo)
   {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   //CIERRO LAS CONTRARIAS en la medida que una de las operaciones se haya abierto
/*if (OrderSelect(ticket1,SELECT_BY_TICKET,MODE_TRADES) && (OrderType()==OP_BUY))
   {
   Comment("Compra abierta... cerrando Venta pendiente");
   OrderDelete(ticket2);
   }
if (OrderSelect(ticket2,SELECT_BY_TICKET,MODE_TRADES) && (OrderType()==OP_SELL))
   {
   Comment("Venta abierta... cerrando Compra pendiente");
   OrderDelete(ticket1);
   }   */     

if (Hour()<HoraComienzo || Hour()>HoraComienzo){bool hecho=false;} 
 if (Hour()==HoraComienzo && !hecho && /*DayOfWeek()!=5 &&*/ DayOfWeek()!=6)
   {
   
      //Comment("Haciendo los deberes, si este mensaje queda por mucho tiempo en la pantalla del gráfico verifique por cuelgues...");
      Print("Calculando los valores y las operaciones del día ", Day(), " de ", Month()," de ", Year());

      if(!ObjectCreate(DoubleToStr(MathRand(),2),OBJ_VLINE,0,TimeCurrent(),0))
        {
          Print("error: cant create object! code #",GetLastError());
          return(0);
        }
      

      
      //Fijo el punto de cierre de la última barra del día anterior...
      double cierre=Close[1];
      
      //Busco máximos y mínimos...
      double max=0,min=2000000;
      for (int i=1;i<=24;i++)
         {
         if (High[i]>max){max=High[i];}
         if (Low[i]<min){min=Low[i];}
         }
      
      //Rango...
      double rang=(max-min)/Point;
      double rango=MathRound(rang);
      
      
      Print("Máximo: ",max);
      Print("Mínimo: ",min);
      Print("Cierre: ",cierre);
      Print("Rango: ",rango," pips");
      
      double cuartoArriba= MathRound((cierre+(MathRound(rango/divOP)*Point))/Point)*Point;
      double medioArriba=  MathRound((cierre+(MathRound(rango/divTP)*Point))/Point)*Point;
      double cuartoAbajo=  MathRound((cierre-(MathRound(rango/divOP)*Point))/Point)*Point;
      double medioAbajo=   MathRound((cierre-(MathRound(rango/divTP)*Point))/Point)*Point;
      
      Print("Buy stop: ",cuartoArriba);
      Print("Sell stop: ",cuartoAbajo);
      Print("Buy TP: ",medioArriba);
      Print("Sell TP: ",medioAbajo);
      
      ObjectDelete("Compra");ObjectDelete("Venta");
      
      if(!ObjectCreate("Compra",OBJ_HLINE,0,0,cuartoArriba))
        {
          Print("error: cant create object! code #",GetLastError());
          return(0);
        }
        
      if(!ObjectCreate("Venta",OBJ_HLINE,0,0,cuartoAbajo))
        {
          Print("error: cant create object! code #",GetLastError());
          return(0);
        }
      
      //Comienzo a operar...
      //        symbol   cmd       volume      price          slippage  stoploss                takeprofit   comment                            magic         expiration    arrow_color
      if (OrdersTotal()!=0){
      for (i=1;i<=OrdersTotal();i++)
         {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if ((OrderMagicNumber()==numMagico) || (OrderMagicNumber()==numMagico+1)){
            if (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP){OrderDelete(OrderTicket());}
            if (OrderType()==OP_BUY){OrderClose(OrderTicket(),OrderLots(),Bid,3,Red);}
            if (OrderType()==OP_SELL){OrderClose(OrderTicket(),OrderLots(),Bid,3,Red);}
         }
         }}
        
      if (((rango<=rangoMaximo)&&(rango>=rangoMinimo)) && DayOfWeek()!=noDia1 && DayOfWeek()!=noDia2 && DayOfWeek()!=noDia3  && DayOfWeek()!=noDia4){
      //if (rango>170 && rango<300){
      //if ((iMA(Symbol(),0,PeriodoMM,0,MODE_SMA,PRICE_CLOSE,0)-iMA(Symbol(),0,PeriodoMM,0,MODE_SMA,PRICE_CLOSE,2))>0){
      int ticket1=OrderSend(Symbol(),OP_BUYSTOP,Lotes,cuartoArriba,3,(cuartoAbajo+Separacion*Point),medioArriba,"Cacus tradeando: Compra Pendiente",numMagico,TimeCurrent()+(3600*21),Blue);
      //}
      //if ((iMA(Symbol(),0,PeriodoMM,0,MODE_SMA,PRICE_CLOSE,0)-iMA(Symbol(),0,PeriodoMM,0,MODE_SMA,PRICE_CLOSE,2))<0){
      int ticket2=OrderSend(Symbol(),OP_SELLSTOP,Lotes,cuartoAbajo,3,(cuartoArriba-Separacion*Point),medioAbajo,"Cacus tradeando: Venta Pendiente",numMagico+1,TimeCurrent()+(3600*21),Red);
      //}
      //if ((rango<150) || (rango>300)){
      //ticket1=OrderSend(Symbol(),OP_BUYSTOP,LotesRed,cuartoArriba,3,(cuartoAbajo+Separacion*Point),medioArriba,"Cacus tradeando: Compra Pendiente",numMagico,TimeCurrent()+(3600*21),Blue);
      //ticket2=OrderSend(Symbol(),OP_SELLSTOP,LotesRed,cuartoAbajo,3,(cuartoArriba-Separacion*Point),medioAbajo,"Cacus tradeando: Venta Pendiente",numMagico+1,TimeCurrent()+(3600*21),Red);
      //}
      }

      hecho=true;
      
   }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   MarcaTiempo = NuevaTiempo;
   }

   return(0);
  }
  
  void TrailingAlls(int trail)
  {
   if(trail==0)
      return;
//----
   double stopcrnt;
   double stopcal;
   int trade;
   int trades=OrdersTotal();
   double profitcalc;
   for(trade=0;trade<trades;trade++)
     {
      OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()==Symbol())
         {
         //continue;
         //LONG
         if(OrderType()==OP_BUY)
           {
            stopcrnt=OrderStopLoss();
            stopcal=Bid-(trail*Point);
            profitcalc=OrderTakeProfit()+(trail*Point);
            if (stopcrnt==0)
              {
               OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,profitcalc,0,Blue);
              }
            else
               if(stopcal>stopcrnt)
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,profitcalc,0,Blue);
                 }
            }
         }//LONG
         //Shrt
         if(OrderType()==OP_SELL)
           {
            stopcrnt=OrderStopLoss();
            stopcal=Ask+(trail*Point);
            profitcalc=OrderTakeProfit()-(trail*Point);
            if (stopcrnt==0)
              {
               OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,profitcalc,0,Red);
              }
            else
               if(stopcal<stopcrnt)
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,profitcalc,0,Red);
                 }
           }
      }
  }//Shrt