Simple_ema_cross_Grail





//+------------------------------------------------------------------+
//|                                       Simple_EMA_Cross_Grail.mq4 |
//|                                                   Larry E. Hayes |
//|                                   BlessingsFromEarth@hotmail.com |
//+------------------------------------------------------------------+
#property copyright "Larry E. Hayes"
#property link      "BlessingsFromEarth@hotmail.com"


//---- Trades limits
extern double StopLoss       = 300;
extern int    TrailingStop   = 200;   // represents 20 lots with the extra digit
extern int    magicnumber    = 143;
extern bool   choice         = true;
extern int    MaxOrders      =  1;     // you can place multiple orders, but suffer equity risk
extern double Risk= 15;                                  // Percentage of free assets
double Lot;                         // global lot for calculating free assets
double Lots           = 0.1;           // This is legacy, no switch at this time for progressive lots
int prevtime;
bool   PolLots        = false;         // This closes half the lots at some point, without it, more earnings.


//---- EMAs paris
extern int ShortEma = 10; 
extern int LongEma = 80;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
      return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
//----
   return(0);
  }
  
int Crossed()
   {
      double EmaLongPrevious = iMA(NULL,0,LongEma,0,MODE_EMA, PRICE_CLOSE, 1); 
      double EmaLongCurrent = iMA(NULL,0,LongEma,0,MODE_EMA, PRICE_CLOSE, 0);
      double EmaShortPrevious = iMA(NULL,0,ShortEma,0,MODE_EMA, PRICE_CLOSE, 1);
      double EmaShortCurrent = iMA(NULL,0,ShortEma,0,MODE_EMA, PRICE_CLOSE, 0);
	   
	   
      if (EmaShortPrevious>EmaLongPrevious && EmaShortCurrent<EmaLongCurrent)
         return (2); //up trend
      if (EmaShortPrevious<EmaLongPrevious && EmaShortCurrent>EmaLongCurrent)
         return (1); //down trend

      return (0); //elsewhere
   }

   
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
   {
   
      Lots = GetLots();
            
      int i=0;  
      int total = OrdersTotal();   
      for(i = 0; i <= total; i++) 
         {
            OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
            if(OrderMagicNumber() == magicnumber) 
              {
                           
                  if(TrailingStop>0)  
                     {                 
                        TrailingStairs(OrderTicket(),TrailingStop);
                     }
              }
         }
      
      if(Bars<100)
         {
            Print("bars less than 100");
            return(0);  
         }
         
      if(AccountFreeMargin() > (AccountBalance()/2))
      {
            int cnt, ticket, ticket2;
            string comment = "";
            int isCrossed  = 0;
            
            if(Time[0] == prevtime) 
               return(0);
            prevtime = Time[0];
            if(!IsTradeAllowed()) 
               {
                  prevtime = Time[1];
                  return(0);
               }
            isCrossed = Crossed ();
            
            if (total < MaxOrders || MaxOrders == 0)
               {
                  if(isCrossed == 1)
                     {
                        HouseKeeper(isCrossed);
                        if (StopLoss!=0)
                           {
                              OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid-(StopLoss*Point),0,StringConcatenate("Simple_EMA_Cross_Grail_",Symbol(), "_Buy"),magicnumber,0,Green);
                           }
                        else
                           {
                              OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,0,StringConcatenate("Simple_EMA_Cross_Grail_",Symbol(), "_Buy"),magicnumber,0,Green);
                           }
                        return(0);
                     }
                  if(isCrossed == 2)
                     {
                        HouseKeeper(isCrossed);
                        if (StopLoss!=0)
                           {
                              OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Ask+(StopLoss*Point),0,StringConcatenate("Simple_EMA_Cross_Grail_", Symbol(), "_Sell"),magicnumber,0,Red);
                           }
                        else
                           {
                              OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,0,StringConcatenate("Simple_EMA_Cross_Grail_", Symbol(), "_Sell"),magicnumber,0,Red);
                           }
                        return(0);
                     }
                  return(0);
               }    

      }

      return(0);
   }

//+------------------------------------------------------------------+

int HouseKeeper(int BuySell)
   {
   
      int i=0;
      int HKtotal = OrdersTotal();   
      bool IsClosed = false;
      
      
      if (choice)
         {
            for(i = 0; i <= HKtotal; i++) 
               {
                  OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
                  IsClosed = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(),3,Yellow);
                  if (IsClosed == false)
                     {
                        // try again
                        IsClosed = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(),3,Yellow);
                     }
               }
         }
      else
         {
            for(i = 0; i <= HKtotal; i++) 
               {
                  OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
                  if(OrderMagicNumber() == magicnumber) 
                     {
                           
                        if (BuySell ==1)
                           {
                              if (OrderType() == OP_SELL)
                                 {
                                    if (OrderProfit() < 0)
                                       {
                                          IsClosed = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(),3,Yellow);
                                          if (IsClosed == false)
                                             {
                                                // try again
                                                IsClosed = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(),3,Yellow);
                                             }
                                       }
                                 }
                           }
                        else
                           {
                              if (OrderType() == OP_BUY)
                                 {
                                    if (OrderProfit() < 0)
                                       {
                                          IsClosed = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(),3,Yellow);
                                          if (IsClosed == false)
                                             {
                                                // try again
                                                IsClosed = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(),3,Yellow);
                                             }
                                       }
                                 }                     
                           }
                  }
               }
         }      
   
      return(0);
   }
   
   
double GetLots()
   {
   
   Lot = NormalizeDouble( (AccountFreeMargin()/MaxOrders)*Risk/100/1000, 1);// Calculate the amount of lots 
   Print("Lot calculation is: ", Lot); 
   if (Lot < MarketInfo(Symbol(),MODE_MINLOT))
      {
         Lot = MarketInfo(Symbol(),MODE_MINLOT);       // For testing on const. min. lots
         Print("Lot is too small, setting to minlot of: ", Lot);
      }
   return(Lot);
   }  
  
//+------------------------------------------------------------------+
void TrailingStairs(int ticket,int trldistance)
   {
    bool result;
    int error;
    int Spred=Ask - Bid;
    int spread;
    
    if (OrderType()==OP_BUY)
      {
       if((Bid-OrderOpenPrice())>(Point*trldistance))
         {
          if(OrderStopLoss()<Bid-Point*trldistance || (OrderStopLoss()==0))
            {
             result=OrderModify(ticket,OrderOpenPrice(),Bid-Point*trldistance,OrderTakeProfit(),0,Green);
             while(result!=True)
               {
                  error=GetLastError();
                  Print("LastError closing first try =",error);
                  if(error==138)
                  {
                     Sleep(10000);
                     RefreshRates();
                     result=OrderModify(ticket,OrderOpenPrice(),Bid-Point*trldistance,OrderTakeProfit(),0,Green);
                  }
                  if(error==0)
                   {
                      result=true;
                   }
               }
           
            
             if (PolLots)
                if (NormalizeDouble(OrderLots()/2,2)>MarketInfo(Symbol(), MODE_MINLOT))
                  {
                     spread=MarketInfo(Symbol(),MODE_SPREAD); 
                     result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Ask,spread,Green);
                     while(result!=True)
                     {
                        error=GetLastError();
                        Print("1 LastError closing first try =",error);
                        if(error==138)
                          {
                              Sleep(10000);
                              RefreshRates();
                              spread=MarketInfo(Symbol(),MODE_SPREAD);
                              result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Ask,spread,Green);
                           }
                        if(error==0)
                           {
                              result=true;
                           }
                     }
                     
                  }
                else
                  {
                     spread=MarketInfo(Symbol(),MODE_SPREAD);
                     result = OrderClose(ticket,OrderLots(),Ask,spread,Green);
                     while(result!=True)
                     {
                        error=GetLastError();
                        Print("2 LastError closing first try =",error);
                        if(error==138)
                           {
                              Sleep(10000);
                              RefreshRates();
                              spread=MarketInfo(Symbol(),MODE_SPREAD);
                              result = OrderClose(ticket,OrderLots(),Ask,spread,Green);
                           }
                        if(error==0)
                           {
                              result=true;
                           }
                     }
                  }
            }
         }
       }
     else
       {
        if((OrderOpenPrice()-Ask)>(Point*trldistance))
          {
           if((OrderStopLoss()>(Ask+Point*trldistance)) || (OrderStopLoss()==0))
             {
               result=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*trldistance,OrderTakeProfit(),0,Red);
               while(result!=True)
                  {
                     error=GetLastError();
                     Print("LastError closing first try =",error);
                     if(error==138)
                        {
                           Sleep(10000);
                           RefreshRates();
                           result=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*trldistance,OrderTakeProfit(),0,Red);
                        }
                        if(error==0)
                           {
                              result=true;
                           }
                  }
             if (PolLots)
             if (NormalizeDouble(OrderLots()/2,2)>MarketInfo(Symbol(), MODE_MINLOT))
               {
                  spread=MarketInfo(Symbol(),MODE_SPREAD);
                  result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Bid,spread,Green);
                  while(result!=True)
                  {
                     error=GetLastError();
                     Print("3 LastError closing first try =",error);
                     if(error==138)
                        {
                           Sleep(10000);
                           RefreshRates();
                           spread=MarketInfo(Symbol(),MODE_SPREAD);
                           result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Bid,spread,Green);
                        }
                        if(error==0)
                           {
                              result=true;
                           }
                  }
                  
               }
             else
               {
                  spread=MarketInfo(Symbol(),MODE_SPREAD);
                  result = OrderClose(ticket,OrderLots(),Bid,spread,Green);
                  while(result!=true)
                  {
                     error=GetLastError();
                     Print("4 LastError closing first try =",error);
                     if(error==138)
                        {
                           Sleep(10000);
                           RefreshRates();
                           spread=MarketInfo(Symbol(),MODE_SPREAD);
                           result = OrderClose(ticket,NormalizeDouble(OrderLots()/2,2),Bid,spread,Green);
                        }
                        if(error==0)
                           {
                              result=true;
                           }
                  }

               }
             }
          }
        }
    }





Sample





Analysis



Market Information Used:

Series array that contains open time of each bar


Indicator Curves created:


Indicators Used:

Moving average indicator


Custom Indicators Used:

Order Management characteristics:
Checks for the total of open orders

It automatically opens orders when conditions are reached
It Closes Orders by itself
It can change open orders parameters, due to possible stepping strategy

Other Features:

BackTest : EURUSD on H1

From 2009-08-01 to 2009-10-01 Profit Factor:0.40 Total Net Profit:-1634.52

BackTest : EURUSD on H1

From 2009-11-01 to 2009-11-30 Profit Factor:0.00 Total Net Profit:3025.52

BackTest : EURUSD on H1

From 2009-12-01 to 2010-01-17 Profit Factor:8.93 Total Net Profit:5614.48

BackTest : EURUSD on H1

From 2010-03-01 to 2010-03-27 Profit Factor:0.79 Total Net Profit:-233.28

BackTest : EURUSD on H1

From 2010-04-01 to 2010-04-30 Profit Factor:0.00 Total Net Profit:-1329.00

BackTest : EURUSD on H1

From 2010-05-01 to 2010-05-31 Profit Factor:1.06 Total Net Profit:65.16

BackTest : EURUSD on H1

From 2010-06-01 to 2010-06-30 Profit Factor:0.30 Total Net Profit:-1287.20

BackTest : GBPUSD on H1

From 2010-01-01 to 2010-02-27 Profit Factor:0.40 Total Net Profit:-2016.49

BackTest : GBPUSD on H1

From 2010-01-01 to 2010-04-16 Profit Factor:0.08 Total Net Profit:-6812.82

BackTest : USDCAD on H1

From 2009-01-01 to 2010-01-01 Profit Factor:0.59 Total Net Profit:-5788.24

BackTest : USDCAD on H1

From 2009-12-01 to 2010-01-01 Profit Factor:0.31 Total Net Profit:-1076.77

BackTest : USDJPY on H1

From 2009-11-01 to 2009-11-30 Profit Factor:0.91 Total Net Profit:-46.49

Request Backtest for Simple_ema_cross_Grail


From : (yyyy/mm/dd) To: (yyyy/mm/dd)

Pair: Period: