//+------------------------------------------------------------------+
//|                                               HolyGrailEA_v7.mq4 |
//|                         Copyright © 2010, Metex Investments Inc. |
//|                                       http://www.metexinvest.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2010, Metex Investments Inc."
#property link      "http://www.metexinvest.com"


#define MAGICGRAIL  20100917
//---- input parameters
//------------------- input parameters ------------------------------+
extern string    Name_Expert       = "HolyGrail_v7";
extern string    Contact_Copyright = "forex4capital@yahoo.ca";
//-------------------------------------------------------------------+
extern double TakeProfit = 70.0;
extern double StopLoss = 5000.0;
extern double Lots = 0.1;
extern int TrailingStop=50;
extern int MinProfit=30;
extern int Slippage=0;
int     TrailingStopMethod = 3;
//extern int Delayed_TrailingStop=90;
//extern string  ts12 = "Settings for Type 2";
//int Immediate_TrailingStop = 30;
int    cnt;
int    HLPeriod = 3;
int    MAPeriod = 7;
int    MASlope = 10;
int    TgtThreshold = 30;
//---- Globals & Buffers
double Threshold, HEntry = 0, LEntry = 0, PrevHigh, PrevLow, Spread;
double MA1,MA2;
int MADir;
datetime prevtime = 0; //Used to determine opening bar
//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
  {
Comment ("DISCLAIMER: Author will be not liable",
         "\n","for any losses or damages !!",
         "\n","Use Holy Grail EA at your own risk !! ");
if (TimeYear(TimeCurrent()) >= 2011 && TimeMonth(TimeCurrent()) >= 11 && TimeDay(TimeCurrent()) >= 31)
         {
  Alert(" Your License Has Expired !!",
         "\n"," The Holy Grail Robot Has Ceased To Operate ",
         "\n"," Please Contact forex4capital@yahoo.ca ",
         "\n"," For A New Subscription!! ");
         return(0);
         }
if( (TimeCurrent()-OrderOpenTime())<30 ) return(0);         
//-------------------------------------------------
bool demo_account = IsDemo();
   
   if (!demo_account)
   {
      Alert ("You can not use the program with a real account!"); 
      return(0);
   }
   //------------------------- MinProfit ------------------------
int total; 
   total  = OrdersTotal();        
   for(int cnt=0;cnt<total;cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      //OrderPrint();
      if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
        {
         if(OrderType()==OP_BUY) 
           {
            if(MinProfit>0 )//&& lots==0.1 && OrderProfit()>0 && UseMinProfit)
              {                 
               if(Bid-OrderOpenPrice()>Point*MinProfit)
                 {
                  if(OrderStopLoss()<Bid-Point*MinProfit)
                    {
                     //OrderClose(OrderTicket(),OrderOpenPrice(),Bid,OrderTakeProfit(),Slippage,Blue);
                     OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Violet);
                     return(0);
                    }
                 }
              }
           }
         else // go to short position
           {
            if(MinProfit>0) //&& lots==0.1 && OrderProfit()>0 && UseMinProfit) 
              {                 
               if((OrderOpenPrice()-Ask)>(Point*MinProfit))
                 {
                  if((OrderStopLoss()>(Ask+Point*MinProfit)) || (OrderStopLoss()==0))
                    {
                     //OrderClose(OrderTicket(),OrderOpenPrice(),Ask,OrderTakeProfit(),Slippage,Red);
                     OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Purple);
                     return(0);
                    }
                 }
              }
           }
        }
     }

   //------------------------------- Trailing Stop --------------------------------------------+
//int total;
//total  = OrdersTotal();     
     for(cnt=0;cnt<OrdersTotal();cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      //OrderPrint()
      
      if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
        {
         if(OrderType()==OP_BUY)   // long position is opened
           {      
            if(TrailingStop>0) //&& OrderLots()==0.10)  
              {                 
               if(Bid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-Point*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-Point*TrailingStop,OrderTakeProfit(),0,Green);
                     
                     return(0);
                    }
                 }
              }
           }
         else // go to short position,check for trailing stop
           {
            if(TrailingStop>0) //&& OrderLots()==0.10)  
              {                 
               if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+Point*TrailingStop,OrderTakeProfit(),0,Red);
                                           
                     return(0);
                    }
                 }
              }
           }
        }
     }
    
    
   int Dir;
   Threshold = TgtThreshold * Point;
//---- Calc Buffers
   if(prevtime == Time[0])
     {
       // IntraBar Tick
       // Determine if H[0] or L[0] over previous
       if(Low[0] < PrevLow)
         {
           LEntry = Low[0] + Threshold + (TakeProfit * Point);
           Spread = PrevHigh - Low[0];
           if (Spread < (2 * Threshold) + (TakeProfit * Point)) LEntry = 0;
         }
       //----
       if(High[0] > PrevHigh)
         {
           HEntry = High[0] - Threshold - (TakeProfit * Point);
           Spread = High[0] - PrevLow;
           if(Spread < (2 * Threshold) + (TakeProfit * Point)) 
               HEntry = 0;
         }
       // Check to see if price has broken entry barrier
       Dir = 0;
       //----
       if(Ask < HEntry && HEntry != 0 && MADir ==1) 
           Dir = 1;
       //----
       if(Bid > LEntry && LEntry != 0 && MADir ==-1) 
           Dir = -1;    
     }
   else
     {
       // Calc MA
       MA1 = iMA(NULL, 0, MAPeriod, 0, MODE_EMA, PRICE_TYPICAL, 0);
       MA2 = iMA(NULL, 0, MAPeriod, 0, MODE_EMA, PRICE_TYPICAL, 1);
       if(MA1 > MA2 + (MASlope*Point)) 
       if (MA1 < MA2 - (MASlope*Point))
           MADir = 1;
       else 
         {
           if (MA1 < MA2 - (MASlope*Point))
           if(MA1 > MA2 + (MASlope*Point)) 
           if (MA1 < MA2 - (MASlope*Point)) 
               MADir = -1;
           else 
               MADir = 0;
         }
       // Find High & Low of previous x Bars
       PrevHigh = High[Highest(NULL, 0, MODE_HIGH, HLPeriod, 1)];
       PrevLow = Low[Lowest(NULL, 0, MODE_LOW, HLPeriod, 1)];
       if(HEntry + Threshold + (TakeProfit * Point) > PrevHigh) 
           HEntry = 0;      
       if(LEntry - Threshold - (TakeProfit * Point) < PrevLow) 
           LEntry = 0;
     }
   //---- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol()) == 0) 
       CheckForOpen(Dir);
   else
     {
       HEntry = 0;
       LEntry = 0;
     }
   //----- reset time         
   prevtime = Time[0];
//----
  }
  
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys = 0, sells = 0;
//----
   for(int i = 0; i < OrdersTotal(); i++)
     {
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) 
           break;
       if(OrderSymbol() == Symbol() && OrderMagicNumber() == MAGICGRAIL)
         {
           if(OrderType() == OP_BUY)  
               buys++;
           if(OrderType() == OP_SELL) 
               sells++;
         }
     }
//---- return orders volume
   if(buys > 0) 
       return(buys);
   else
       //return(-sells);
       return(sells);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen(int Dir)
  {
   int ticket;

//---- sell conditions
   if(Dir == -1)
     {
       /*ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, 0, Bid + StopLoss*Point, 
                          Bid - TakeProfit*Point, "HolyGrailEA_v7", MAGICGRAIL, 0, Red);*/
       ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, 0,0,0, "HolyGrailEA_v7", MAGICGRAIL, 0, Red);
       OrderSelect(ticket,SELECT_BY_TICKET);
       OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+StopLoss*Point,OrderOpenPrice()-TakeProfit*Point,0,Red);
                          
       if(ticket < 1) 
           Print("Error opening SELL order : ", GetLastError()); 
       return(0);
     }
    
//---- buy conditions
   if(Dir == 1)
     {
       ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, 0,0,0, "HolyGrailEA_v7", MAGICGRAIL, 0, Blue);
                           OrderSelect(ticket,SELECT_BY_TICKET);
       OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-StopLoss*Point,OrderOpenPrice()+TakeProfit*Point,0,Blue);
       if(ticket<1) Print("Error opening BUY order : ", GetLastError());
       return(0);
     }
     }
//----
//+------------------------------------------------------------------+
//| HandleTrailingStop                                               |
//| Type 1 is do not trail                                           |
//| Type 2 waits for price to move the amount of the trailStop       |
//|        before moving stop loss then moves like type 4            |
//| Type 3 moves the stoploss without delay.                         |
//+------------------------------------------------------------------+
/*void HandleTrailingStop(int cmd, int ticket, double op, double os, double tp)
{
   switch (TrailingStopMethod)
   {
     //case 1 : Do not trail (cmd, ticket, op, os, tp);
    // case 2 : Delayed_TrailingStop (cmd, ticket, op, os, tp);
              //break;
     case 3 : Immediate_TrailingStop (cmd, ticket, op, os, tp);
             // break;
	}
}*/
 
//+------------------------------------------------------------------+