Download MetaTrader 5

Need help for below ea

To add comments, please log in or register
steven37
18
steven37  
//+------------------------------------------------------------------+
//|                                                    hedgetest.mq4 |
//|                        Copyright 2016, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

//------- external parameters ---------------------------------------+
extern string             nameInd1           = "___________RSI__________"; // RSi 
extern int                RSI_period         = 7;                          // RSi period
extern ENUM_APPLIED_PRICE RSI_applied_price  = PRICE_CLOSE;                // RSi applied price
extern int                RSI_up_level       = 80;                         // level up - RSi 
extern int                RSI_dn_level       = 20;                         // level down - RSi 
extern string             nameInd2           = "___________MA___________"; // MA
extern int                MA_period          = 20;                        // MA period
extern double             MA_level_1         = 60;                         // MA Level 1
extern double             MA_level_2         = 120;                        // MA Level 2
extern int                MA_shift           = 0;                          // MA shift
extern ENUM_MA_METHOD     MA_method          = MODE_EMA;                   // MA method
extern ENUM_APPLIED_PRICE MA_applied_price   = PRICE_CLOSE;                // MA applied price
extern string             EA_properties      = "_________Expert_________"; // Expert properties
extern double             Lot                = 0.01;                       // Lot
extern double             Take_Profit        = 300;                        // Take profit
extern double             StopLoss           = 300;                        // StopLoss
extern int                Slippage           = 30;                         // Slippage
extern int                NumberOfTry        = 5;                          // number of trade attempts
extern int                MagicNumber        = 5577555;                    // Magic Number


//------- global variables ------------------------------------------+
string   NameEA="Expert_MA_RSI_Hedge";
double pips;  
string   Symb;
string   txt="";
datetime candleTime=0;

//+------------------------------------------------------------------+
//| double to string                                                 |
//+------------------------------------------------------------------+
string double_to_str(double num,int _dig=2)
  {
   string _num  = (string)num;
   int    _pp   = StringFind(_num, ".", 0);
   if(_pp!=-1) _num=StringSubstr(_num,0,_pp+_dig+1);
   return(_num);
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
  
   double ticksize = MarketInfo(Symbol(),MODE_TICKSIZE);
   if (ticksize == 0.00001 || ticksize == 0.001)
   pips = ticksize*10;
   else pips = ticksize;
   
   Symb=Symbol();
   if(RSI_up_level>=100 || RSI_up_level<=RSI_dn_level) { Print("Wrong level up - RSi !");             return(INIT_FAILED);}
   if(RSI_dn_level<=0   || RSI_dn_level>=RSI_up_level) { Print("Wrong level down - RSi !");           return(INIT_FAILED);}
   if(Lot<MarketInfo(Symb,MODE_MINLOT) || Lot>MarketInfo(Symb,MODE_MAXLOT)) { Print("Wrong LOT!");    return(INIT_FAILED);}
   if(Slippage<0) Slippage=0;
   if(NumberOfTry<1)  NumberOfTry=1;
   if(MagicNumber<0)  MagicNumber=MathAbs(MagicNumber);
   Comment("Waiting a new tick!");
      
   return(INIT_SUCCEEDED);
  }
  
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) { Comment(""); }

//+------------------------------------------------------------------+
//| Looking for a open price                                         |
//+------------------------------------------------------------------+
double OpenPrice(int or_tp)
  {
   double _opPr=0;
   if(or_tp!=0 && or_tp!=1) return (_opPr);
   int i,k = OrdersTotal ();
//---
   for(i=k-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symb && OrderMagicNumber()==MagicNumber)
           {
            if(or_tp==OrderType())
              {
               if(_opPr==0) {_opPr=OrderOpenPrice(); continue;}
               if(or_tp==0 && _opPr<OrderOpenPrice()) _opPr=OrderOpenPrice();
               if(or_tp==1 && _opPr>OrderOpenPrice()) _opPr=OrderOpenPrice();
              }
           }
        }
     }
   return (_opPr);
  }

//+------------------------------------------------------------------+
//| Check open position                                              |
//+------------------------------------------------------------------+
bool HaveOpenPos(int or_tp=-1)
  {
   int i,ot,k=OrdersTotal();
   if(or_tp<0 || or_tp>1) or_tp=-1;
   for(i=k-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symb && OrderMagicNumber()==MagicNumber)
           {
            ot=OrderType();
            if(or_tp==-1)
              {
               if(ot==0 || ot==1) return (true);
                 } else {
               if(or_tp==ot) return (true);
              }
           }
        }
     }
   return (false);
  }


//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+

void OnTick()
  {
   if(!IsTradeAllowed())
     {
      string _txt_new="You must allow trading!";
      if(txt!=_txt_new) { txt=_txt_new; Print(txt); Comment(txt);}
      return;
     }
   
//---
   double _ma      = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0);
   double ma_buy1  = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0)-(MA_level_1);
   double ma_sell1 = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0)+(MA_level_1);
   double ma_buy2  = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0)-(MA_level_2);
   double ma_sell2 = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0)+(MA_level_2);
   double _rsi     = iRSI       (Symb, 0, RSI_period, RSI_applied_price, 0);
   
//---
//--- comment
   string _dn_up="DOWN price"; if(Bid>_ma) _dn_up="UP price";
   txt="\n"+NameEA+"\nMA = "+double_to_str(_ma,Digits)+" ---> "+_dn_up
       +"\nRSI ("+(string)RSI_dn_level+"/"+(string)RSI_up_level+") = "+double_to_str(_rsi);
        Comment(txt);
//---


//--- BUY
   if(Ask<ma_buy2 && _rsi<RSI_dn_level && HaveOpenPos(0)==false)
     {
      BuyPos(Lot);
     }
//--- SELL
   if(Bid>ma_sell2 && _rsi>RSI_up_level && HaveOpenPos(1)==false)
     {
      SellPos(Lot);
     }
//---
}

  //+------------------------------------------------------------------+
//| BUY                                                              |
//+------------------------------------------------------------------+
void BuyPos(double _lot)
  {
   double sl=0,tp=0;
//---
   int err;
   for(int it=1; it<=NumberOfTry; it++)
     {
      ResetLastError();
      RefreshRates();
      if(!OrderSend(Symb,OP_BUY,_lot,NormalizeDouble(Ask,Digits),Slippage,NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),NULL,MagicNumber))
        {
         if(it>=NumberOfTry) { Print("Failed OP_BUY !"); break; }
         err=GetLastError();
         if(err==4 || err==6 || err==8 || err==128 || err==137 || err==141 || err==146) Sleep(1000*100);
         else { Print("Failed OP_BUY !"); break; }
        }
      else break;
     }
  }
//+------------------------------------------------------------------+
//| SELL                                                             |
//+------------------------------------------------------------------+
void SellPos(double _lot)
  {
   double sl=0,tp=0;
//---
   int err;
   for(int it=1; it<=NumberOfTry; it++)
     {
      ResetLastError();
      RefreshRates();
      if(!OrderSend(Symb,OP_SELL,_lot,NormalizeDouble(Bid,Digits),Slippage,NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),NULL,MagicNumber))
        {
         if(it>=NumberOfTry) { Print("Failed OP_SELL !"); break; }
         err=GetLastError();
         if(err==4 || err==6 || err==8 || err==128 || err==137 || err==141 || err==146) Sleep(1000*100);
         else { Print("Failed OP_SELL !"); break; }
        }
      else break;
     }
  }

Hi,

Can any expert help on above ea ? I can compile it with no error , but during backtest , it not sending order. 

Carl Schreiber
7091
Carl Schreiber  
You have forgotten to convert your levels (MA_level_1 ..) into prices like e.g.: what_ever = MA_level_1*Point
steven37
18
steven37  
gooly:
You have forgotten to convert your levels (MA_level_1 ..) into prices like e.g.: what_ever = MA_level_1*Point
//+------------------------------------------------------------------+
//|                                                    hedgetest.mq4 |
//|                        Copyright 2016, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

//------- external parameters ---------------------------------------+
extern string             nameInd1           = "___________RSI__________"; // RSi 
extern int                RSI_period         = 7;                          // RSi period
extern ENUM_APPLIED_PRICE RSI_applied_price  = PRICE_CLOSE;                // RSi applied price
extern int                RSI_up_level       = 80;                         // level up - RSi 
extern int                RSI_dn_level       = 20;                         // level down - RSi 
extern string             nameInd2           = "___________MA___________"; // MA
extern int                MA_period          = 20;                        // MA period
extern double             MA_level_1         = 60;                         // MA Level 1
extern double             MA_level_2         = 120;                        // MA Level 2
extern int                MA_shift           = 0;                          // MA shift
extern ENUM_MA_METHOD     MA_method          = MODE_EMA;                   // MA method
extern ENUM_APPLIED_PRICE MA_applied_price   = PRICE_CLOSE;                // MA applied price
extern string             EA_properties      = "_________Expert_________"; // Expert properties
extern double             Lot                = 0.01;                       // Lot
extern double             Take_Profit        = 300;                        // Take profit
extern double             StopLoss           = 300;                        // StopLoss
extern int                Slippage           = 30;                         // Slippage
extern int                NumberOfTry        = 5;                          // number of trade attempts
extern int                MagicNumber        = 5577555;                    // Magic Number
extern int                params_digits      = 5;                           // Broker digits

//------- global variables ------------------------------------------+
string   NameEA="Expert_MA_RSI_Hedge";
double point;  
string   Symb;
string   txt="";
datetime candleTime=0;


//+------------------------------------------------------------------+
//| double to string                                                 |
//+------------------------------------------------------------------+
string double_to_str(double num,int _dig=2)
  {
   string _num  = (string)num;
   int    _pp   = StringFind(_num, ".", 0);
   if(_pp!=-1) _num=StringSubstr(_num,0,_pp+_dig+1);
   return(_num);
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
  
   point = MathPow (0.1, params_digits) ;  
   
   Symb=Symbol();
   if(RSI_up_level>=100 || RSI_up_level<=RSI_dn_level) { Print("Wrong level up - RSi !");             return(INIT_FAILED);}
   if(RSI_dn_level<=0   || RSI_dn_level>=RSI_up_level) { Print("Wrong level down - RSi !");           return(INIT_FAILED);}
   if(Lot<MarketInfo(Symb,MODE_MINLOT) || Lot>MarketInfo(Symb,MODE_MAXLOT)) { Print("Wrong LOT!");    return(INIT_FAILED);}
   if(Slippage<0) Slippage=0;
   if(NumberOfTry<1)  NumberOfTry=1;
   if(MagicNumber<0)  MagicNumber=MathAbs(MagicNumber);
   Comment("Waiting a new tick!");
      
   return(INIT_SUCCEEDED);
  }
  
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) { Comment(""); }

//+------------------------------------------------------------------+
//| Looking for a open price                                         |
//+------------------------------------------------------------------+
double OpenPrice(int or_tp)
  {
   double _opPr=0;
   if(or_tp!=0 && or_tp!=1) return (_opPr);
   int i,k = OrdersTotal ();
//---
   for(i=k-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symb && OrderMagicNumber()==MagicNumber)
           {
            if(or_tp==OrderType())
              {
               if(_opPr==0) {_opPr=OrderOpenPrice(); continue;}
               if(or_tp==0 && _opPr<OrderOpenPrice()) _opPr=OrderOpenPrice();
               if(or_tp==1 && _opPr>OrderOpenPrice()) _opPr=OrderOpenPrice();
              }
           }
        }
     }
   return (_opPr);
  }

//+------------------------------------------------------------------+
//| Check open position                                              |
//+------------------------------------------------------------------+
bool HaveOpenPos(int or_tp=-1)
  {
   int i,ot,k=OrdersTotal();
   if(or_tp<0 || or_tp>1) or_tp=-1;
   for(i=k-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symb && OrderMagicNumber()==MagicNumber)
           {
            ot=OrderType();
            if(or_tp==-1)
              {
               if(ot==0 || ot==1) return (true);
                 } else {
               if(or_tp==ot) return (true);
              }
           }
        }
     }
   return (false);
  }


//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+

void OnTick()
  {
   if(!IsTradeAllowed())
     {
      string _txt_new="You must allow trading!";
      if(txt!=_txt_new) { txt=_txt_new; Print(txt); Comment(txt);}
      return;
     }
   
//---
   double _ma      = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0);
   double ma_buy1  = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0)-(MA_level_1*point);
   double ma_sell1 = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0)+(MA_level_1*point);
   double ma_buy2  = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0)-(MA_level_2*point);
   double ma_sell2 = iMA        (Symb, 0, MA_period, MA_shift, MA_method, MA_applied_price, 0)+(MA_level_2*point);
   double _rsi     = iRSI       (Symb, 0, RSI_period, RSI_applied_price, 0);
   
//---
//--- comment
   string _dn_up="DOWN price"; if(Bid>_ma) _dn_up="UP price";
   txt="\n"+NameEA+"\nMA = "+double_to_str(_ma,Digits)+" ---> "+_dn_up
       +"\nRSI ("+(string)RSI_dn_level+"/"+(string)RSI_up_level+") = "+double_to_str(_rsi);
        Comment(txt);
//---


//--- BUY
   if(Ask<ma_buy2 && _rsi<RSI_dn_level && HaveOpenPos(0)==false)
     {
      BuyPos(Lot);
     }
//--- SELL
   if(Bid>ma_sell2 && _rsi>RSI_up_level && HaveOpenPos(1)==false)
     {
      SellPos(Lot);
     }
//---
}

  //+------------------------------------------------------------------+
//| BUY                                                              |
//+------------------------------------------------------------------+
void BuyPos(double _lot)
  {
   
//---
   int err;
   for(int it=1; it<=NumberOfTry; it++)
     {
      ResetLastError();
      RefreshRates();
      if(!OrderSend(Symb,OP_BUY,_lot,NormalizeDouble(Ask,Digits),Slippage,Ask-StopLoss*point,Ask+Take_Profit*point,NULL,MagicNumber))
        {
         if(it>=NumberOfTry) { Print("Failed OP_BUY !"); break; }
         err=GetLastError();
         if(err==4 || err==6 || err==8 || err==128 || err==137 || err==141 || err==146) Sleep(1000*100);
         else { Print("Failed OP_BUY !"); break; }
        }
      else break;
     }
  }
//+------------------------------------------------------------------+
//| SELL                                                             |
//+------------------------------------------------------------------+
void SellPos(double _lot)
  {
  
//---
   int err;
   for(int it=1; it<=NumberOfTry; it++)
     {
      ResetLastError();
      RefreshRates();
      if(!OrderSend(Symb,OP_SELL,_lot,NormalizeDouble(Bid,Digits),Slippage,Bid+StopLoss*point,Bid+Take_Profit*point,NULL,MagicNumber))
        {
         if(it>=NumberOfTry) { Print("Failed OP_SELL !"); break; }
         err=GetLastError();
         if(err==4 || err==6 || err==8 || err==128 || err==137 || err==141 || err==146) Sleep(1000*100);
         else { Print("Failed OP_SELL !"); break; }
        }
      else break;
     }
  }
steven37
18
steven37  
Hi , I already change the code , I able to send order but during in backtest ,found alot of Ordersend error 130.
ffoorr
1077
ffoorr  

The error is in the fonction open sell, the takeprofit is wrong,

But something is not working in your code, it did not inform about error


void SellPos(double _lot)
  {
  
//---
   int err;
   for(int it=1; it<=NumberOfTry; it++)
     {
      Print("OPENING SELL");
      ResetLastError();
      RefreshRates();
      if(!OrderSend(Symbol(),OP_SELL,_lot,NormalizeDouble(Bid,Digits),Slippage,
                 Bid+StopLoss*point,Bid+Take_Profit*point,NULL,MagicNumber))
        {
         
         if(it>=NumberOfTry) { Print("Failed OP_SELL !"); break; }
         err=GetLastError();
         if(err==4 || err==6 || err==8 || err==128 || err==137 || err==141 || err==146) Sleep(1000*100);
         else { Print("Failed OP_SELL ! Error : "+ ErrorDescription(err)); break; }
        }
      else break;
     }
  }
  
Keith Watford
Moderator
10569
Keith Watford  
      if(!OrderSend(Symbol(),OP_SELL,_lot,NormalizeDouble(Bid,Digits),Slippage,
                 Bid+StopLoss*point,Bid+Take_Profit*point,NULL,MagicNumber))

Unless Take_Profit is a negative number, it should be 

Bid-Take_Profit*point

 .

ffoorr
1077
ffoorr  

Yes gumrai, i showed the error and let him correct it.

OrderSend is not a boolean fonction, the returned code will alway be different of 0=false

 if(!OrderSend(Symbol()

 so it should alway enter in the parenthesis : it don't (?)


 Better use the return (int) code of ticket, rather than a boolean

Keith Watford
Moderator
10569
Keith Watford  
ffoorr:

Yes gumrai, i showed the error and let him correct it.

OrderSend is not a boolean fonction, the returned code will alway be different of 0=false

 so it should alway enter in the parenthesis : it don't (?)


 Better use the return (int) code of ticket, rather than a boolean

Sorry, I wasn't paying attention, I didn't even notice that the return from OrderSend() was being treated as a Boolean.
To add comments, please log in or register