Mean Revert EA - bug! Any suggestions much appreciated

 
/*------------------------------------------------------------------+
 |                                             fracmap_home         |
 |                                                 Copyright © 2011 |
 |                                                                  |
 +------------------------------------------------------------------*/
#property copyright "Copyright © 2011, fracmap.com"
//-----  
//-- This EA is meant to go long when the market price touches (or goes below then closes above within the same bar) a Buy indicator line and then reverses when the price touches (trades above but closes below) a sell indicator line. The EA is always either long or short.
// The indicator is displayed as two lines on the chart and is visually analgous to Bollinger bands.
#define MagicNum 10001
//-----
//-----
extern bool       Retrace    = False; // 
extern int       Band_Period   = 1;
extern int       price_type    = 0; // 0 = High/Low | 1 = Open/Close
extern double       phi    = 1.618034; // 
extern int       order    = 6; // 

//+------------------------------------------------------------------+
int start()
 {

double New_Time_M1;
bool New_Bar_M1;

//new bar is born
if(New_Time_M1 != iTime("EURUSD",PERIOD_M1,0)) // Compare time --> new bar is born
{
New_Time_M1=iTime("EURUSD",PERIOD_M1,0); // New time set
New_Bar_M1=true; // A new bar detected

}
else
{
New_Bar_M1=false;
}

         



   string IndicatorStyle;
   bool Golong = false;
   bool Goshort = false;
      

 //There are two different styles of indicator.

   if(Retrace==False)
     {
     IndicatorStyle="fracmap_NoRetrace";
     }
      else
     {
     IndicatorStyle="fracmap_trade";
     }


// 
 
   int cnt, ticket, total;

//New bar code for Min data

if(New_Bar_M1==true)
{  


// delete allpending orders
string Symb=Symbol();

for(int i=1; i<=OrdersTotal(); i++)          // Order searching cycle
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // If the next is available
        {                                       // Order analysis:
         //----------------------------------------------------------------------- 3 --
         if (OrderSymbol()!= Symb) continue;    // Symbol is not ours
         int Tip=OrderType();                   // Order type
         //if (Tip>2) continue;                   // Market or
         OrderDelete(OrderTicket());
         }
       }





   //-----
  
     double frac_sell=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,1,0);
     double frac_buy=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,0,0);

     double frac_sell_prev=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,1,1);
     double frac_buy_prev=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,0,1);

     double frac_sell_next=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,1,-1);
     double frac_buy_next=iCustom(NULL, 0, IndicatorStyle  ,Band_Period,price_type,phi,order,0,-1);

  
      //-------------------------------------------------------  this is where signals are filtered

      if(Close[0]>=frac_buy  && Low[0]<=frac_buy  && frac_buy_prev < frac_buy && frac_buy_next < frac_buy)
       {      
         Golong=true;
       }
       else
       {
       Golong=false;
       }     
       
      if(Close[0]<=frac_sell && High[0]>=frac_sell && frac_sell_prev > frac_sell && frac_sell_next > frac_sell)
       {
         Goshort = true;
       }            
      else
       {
         Goshort = false;
       }            
      //-------------------------------------------------------  



      if(Golong==true)
       {      
        ticket=OrderSend(Symbol(),OP_BUY,OrderLots(),Ask,1,0,0,"Buy Entry",10001,0,Green);
         if(ticket > 0)
          {            
             return(0);
          }
       }
            
      if(Goshort==true)
       {
         ticket=OrderSend(Symbol(),OP_SELL,OrderLots(),Bid,1,0,0,"Sell Entry",10001,0,Red);
         if(ticket > 0)
          {
             return(0); 
          }  
       }            
    }
   //-- here trades are exited and reversed
   total = OrdersTotal();
   for(cnt = 0; cnt < total; cnt++)
    {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType() <= OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNum)
       {
         //-----------------------         
         if(OrderType() == OP_BUY)
          {                
            if(Goshort==true)
             {
               OrderClose(OrderTicket(), OrderLots(), Bid, 3, Violet); 
               return(0); 
             }
          }
         else if(OrderType() == OP_SELL)
          {                
            if(Golong==true)
             {
               OrderClose(OrderTicket(), OrderLots(), Ask, 3, Violet); 
               return(0); 
             }
          }
       }
 }
 }

Please note that much of the code was evolved from BasisForex's excellent EA_Fibo_Avg (as well as others). Thanks, and please note - I am a novice! Thanks in advance for your support. Fracmap.

PROBLEM

Multiple positions are opened up in the same bar.

DESCRIPTION

Always either long or short. Uses a proprietary indicator which is similar to Bollinger bands.

The logic for Buy signals are as follows:

1. The Value of the Buy indicator for the current bar is greater than the value of the Buy indicator for the future bar and the previous bar (this is possible because the Buy indicator is plotted into the future 1 bar.)
2. The Low of the bar is less than or equal to the Buy indicator value.
3. The close of the bar is greater or equal to the Buy indicator.

The logic for Sell signals are as follows:
1. The Value of the sell indicator for the current bar is less than the value of the sell indicator for the future bar and the previous bar (this is possible because the sell indicator is plotted into the future 1 bar.)
2. The High of the bar is greater than or equal to the sell indicator value.
3. The Close of the bar is less than or equal to the sell indicator.

#define MagicNum 10001


//-----


//-----


extern bool Retrace = False; //


extern int Band_Period = 1;


extern int price_type = 0; // 0 = High/Low | 1 = Open/Close


extern double phi = 1.618034; //


extern int order = 6; //



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


int start()


{



double New_Time_M1;


bool New_Bar_M1;



//new bar is born


if(New_Time_M1 != iTime("EURUSD",PERIOD_M1,0)) // Compare time --> new bar is born


{


New_Time_M1=iTime("EURUSD",PERIOD_M1,0); // New time set


New_Bar_M1=true; // A new bar detected



}


else


{


New_Bar_M1=false;


}



string IndicatorStyle;


bool Golong = false;


bool Goshort = false;




//There are two different styles of indicator.



if(Retrace==False)


{


IndicatorStyle="fracmap_NoRetrace";


}


else


{


IndicatorStyle="fracmap_trade";


}




//



int cnt, ticket, total;



//New bar code for Min data



if(New_Bar_M1==true)


{




// delete allpending orders


string Symb=Symbol();



for(int i=1; i<=OrdersTotal(); i++) // Order searching cycle


{


if (OrderSelect(i-1,SELECT_BY_POS)==true) // If the next is available


{ // Order analysis:


//----------------------------------------------------------------------- 3 --


if (OrderSymbol()!= Symb) continue; // Symbol is not ours


int Tip=OrderType(); // Order type


//if (Tip>2) continue; // Market or


OrderDelete(OrderTicket());
}
}





//----- Here the indicators are called.

double frac_sell=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,1,0);
double frac_buy=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,0,0);

double frac_sell_prev=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,1,1);
double frac_buy_prev=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,0,1);

double frac_sell_next=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,1,-1);
double frac_buy_next=iCustom(NULL, 0, IndicatorStyle,Band_Period,price_type,phi,order,0,-1);


//------------------------------------------------------- this is where signals are filtered

if(Close[0]>=frac_buy && Low[0]<=frac_buy && frac_buy_prev < frac_buy && frac_buy_next < frac_buy)
{
Golong=true;
}
else
{
Golong=false;
}

if(Close[0]<=frac_sell && High[0]>=frac_sell && frac_sell_prev > frac_sell && frac_sell_next > frac_sell)
{
Goshort = true;
}
else
{
Goshort = false;
}
//-------------------------------------------------------



if(Golong==true)
{
ticket=OrderSend(Symbol(),OP_BUY,OrderLots(),Ask,1,0,0,"Buy Entry",10001,0,Green);
if(ticket > 0)
{
return(0);
}
}

if(Goshort==true)
{
ticket=OrderSend(Symbol(),OP_SELL,OrderLots(),Bid,1,0,0,"Sell Entry",10001,0,Red);
if(ticket > 0)
{
return(0);
}
}
}


//-- here trades are exited and reversed

total = OrdersTotal();
for(cnt = 0; cnt < total; cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType() <= OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNum)
{
//-----------------------
if(OrderType() == OP_BUY)
{
if(Goshort==true)
{
OrderClose(OrderTicket(), OrderLots(), Bid, 3, Violet);
return(0);
}
}
else if(OrderType() == OP_SELL)
{
if(Golong==true)
{
OrderClose(OrderTicket(), OrderLots(), Ask, 3, Violet);
return(0);
}
}
}
}
}

 

Please use this to post code . . . it makes it easier to read.

 
  1. Use SRC
  2. Count your open orders and don't open more.
    int start(){
        int count=0;
        for(pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
            OrderSelect(pos, SELECT_BY_POS)                 // Only my orders w/
        &&  OrderMagicNumber()  == magic.number             // my magic number
        &&  OrderSymbol()       == Symbol() ){              // and my pair.
            count++;
        }
        if (count != 0) return; // one open order per chart.

  3. if(New_Time_M1 != iTime("EURUSD",PERIOD_M1,0)) // Compare time --> new bar is born
    Tester limitation, you can NOT get bar zero data for other TF/pairs.
 
RaptorUK:

Please use this to post code . . . it makes it easier to read.



tks Raptor :-)
 
WHRoeder:
  1. Use SRC
  2. Count your open orders and don't open more.


Tks WHRoeder :-)
 
WHRoeder:
  1. Use SRC
  2. Count your open orders and don't open more.


Hi WHRoeder - Inserted the code as suggested. This solved the problem of multiple orders being opened (thanks).

However, there is an additional bug. There are many genuine signals created by the EA, but only the first signal that is encountered is executed, and is left open for the entire back test period.


When I change the start point of the back test, sometimes the first signal is a Buy and sometimes it is a Sell (as expected) but a second (opposite to the initital signal) is never executed.

For instance, when the first signal is a Buy, then further Sell signals are ignored.

Any advice appreciated.

Tks

Fracmap

 

fracmap:
When I change the start point of the back test

#3 added
 
WHRoeder:
  1. Use SRC
  2. Count your open orders and don't open more.

  3. Tester limitation, you can NOT get bar zero data for other TF/pairs.


Hi - Yes that is correct. Am just using EURUSD. Tks Fracmap
 
WHRoeder:
  1. Use SRC
  2. Count your open orders and don't open more.

  3. Tester limitation, you can NOT get bar zero data for other TF/pairs.

fracmap:


Hi - Yes that is correct. Am just using EURUSD. Tks Fracmap


Hi WHRoeder - Working through the code, does #2 prevent the reversal trade being executed? Tks