need help

 

Hello all,


I need help for my code

The code doesn't execute as the following condition:

BUY CONDITION: 

-Breakout of the upper bands on M15, and when the candle on M15 closed above the upper band,confirm the condition on M5 chart(wait the next candle on M5 breaks out the upper band too)

SELL CONDITION:

-Breakout of the lower bands on M15, and when the candle on M15 closed below the lower band,confirm the condition on M5 chart(wait the next candle on M5 breaks out the lower band too)

#property copyright   ""
#property link        ""
#property description "BBands EA"

#define MAGICMA  20131111
//--- Inputs
input double Lots          =0.1;
input double MaximumRisk   =0.04;
input double DecreaseFactor=3;
input int    MovingPeriod  =1;
input int    MovingShift   =0;
extern double   MADistance          = 700;

//+------------------------------------------------------------------+
//| 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()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//--- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//--- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//--- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
           {
            Print("Error in history!");
            break;
           }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
            continue;
         //---
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1)
         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//--- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
  string TradeStartTime = "10:30";
  string TradeStopTime = "23:00";

  
   int    res;
   
   double BandsTopCurr=iBands(Symbol(),PERIOD_M5,20,2,0,PRICE_CLOSE,MODE_UPPER,0);
   double BandsLowCurr=iBands(Symbol(),PERIOD_M5,20,2,0,PRICE_CLOSE,MODE_LOWER,0);
   double BandsTopCurrM=iBands(Symbol(),PERIOD_M15,20,2,0,PRICE_CLOSE,MODE_UPPER,1);
   double BandsLowCurrM=iBands(Symbol(),PERIOD_M15,20,2,0,PRICE_CLOSE,MODE_LOWER,1);
   double ma;
//--- go trading only for first tiks of new bar
   
//--- get Moving Average 
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_EMA,PRICE_WEIGHTED,1);
   
        MADistance=ND(MADistance*Point,Digits);
//--- go trading only for first tiks of new bar
   if(Volume[0]>700) return;
//--- sell conditions
   if(Open[1]>BandsLowCurrM && Close[1]<BandsLowCurrM && Close[0]<BandsLowCurr && TimeCurrent()>StrToTime(TradeStartTime) && TimeCurrent()<StrToTime(TradeStopTime))
     {
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      return;
     }
//--- buy conditions
   if(Open[1]<BandsTopCurrM && Close[1]>BandsTopCurrM && Close[0]>BandsTopCurr && TimeCurrent()>StrToTime(TradeStartTime) && TimeCurrent()<StrToTime(TradeStopTime))
     {
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      return;
     }
//---
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double ma;
//--- go trading only for first tiks of new bar
   
//--- get Moving Average 
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_EMA,PRICE_WEIGHTED,1);
   
        MADistance=ND(MADistance*Point,Digits);
//---
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //--- check order type 
      if(OrderType()==OP_BUY)
        {
         if(Ask>ma+MADistance)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(Bid<ma-MADistance)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
     }
//---
  }
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {if(Volume[0]>1) return;
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
   double maxDuration = 5 * 60; 
for(int pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
    OrderSelect(pos, SELECT_BY_POS)            // Only my orders w/
&&  OrderSymbol()== Symbol()){               // and period and symbol
    int duration = TimeCurrent() - OrderOpenTime();
    if (duration >= maxDuration)
         OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(),
                     3*Point);
}     
  return;
//---
  }
//+------------------------------------------------------------------+

double ND(double Value,int Precision){return(NormalizeDouble(Value,Precision));}

Files:
M15.PNG  42 kb
M5.PNG  49 kb
 
  {if(Volume[0]>1) return;

For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
          New candle - MQL4 programming forum #3 2014.04.04

I disagree with making a new bar function, because it can only be called once per tick. A variable can be tested multiple times.
          Running EA once at the start of each bar - MQL4 programming forum 2011.05.06

 
Comments that do not relate to this topic, have been moved to "Off Topic Posts".
 
William Roeder:

For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
          New candle - MQL4 programming forum #3 2014.04.04

I disagree with making a new bar function, because it can only be called once per tick. A variable can be tested multiple times.
          Running EA once at the start of each bar - MQL4 programming forum 2011.05.06

Thanks William, 

I have tried this but nothing happen

The ea doesn't execute as the condition I need

 

Do not double post!

I have deleted your other topic.

 
Keith Watford:

Do not double post!

I have deleted your other topic.

olease help me
 
Dany William:
olease help me

I see this a lot from new coders and I have never understood why.

   for(int i=0;i<OrdersTotal();i++)
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;

Why the break? That means that none of the following orders will be checked if one select fails.

   for(int i=0;i<OrdersTotal();i++)
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) continue;

makes much more sense.

If you want help, show your updated code that you have done and of course you have implemented William's advice from the first reply.

 
Keith Watford:

I see this a lot from new coders and I have never understood why.

Why the break? That means that none of the following orders will be checked if one select fails.

makes much more sense.

If you want help, show your updated code that you have done and of course you have implemented William's advice from the first reply.


Thanks so much sir


it doesn't work again :-(

The condition before placing an order should be:

BUY CONDITION: 

-Breakout of the upper bands on M15, and when the candle on M15 closed above the upper band,confirm the condition on M5 chart(after M15 candle closed,wait a new candle M5 to confirm the trade,the new candle must be an UP CANDLE)

SELL CONDITION:

-Breakout of the lower bands on M15, and when the candle on M15 closed below the lower band,confirm the condition on M5 chart( after M15 candle closed,wait a new candle M5 to confirm the trade,the new candle must be a DOWN CANDLE )


this is the updated code that I tried and the bad signal(photo)

#property version   "1.00"
#property strict
input string comEAsettings="[EA settings]";//~
input int MagicNumber=55545;
input string EA_Comment="";
input double DecreaseFactor=3;
input int    MovingPeriod  =1;
input int    MovingShift   =0;
double _point=1;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create timer
   EventSetTimer(60);
//Get Symbol digit
   string _sym=Symbol();
   double _digits=MarketInfo(_sym,MODE_DIGITS);
   if(_digits==5||_digits==3) _point=1/MathPow(10,(_digits-1));
   if(_digits==4||_digits==2) _point=1/MathPow(10,(_digits));
   if(_digits==1) _point=0.1;
//
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
if(Volume[0]>1) return;
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   int maxDuration = 5 * 60; 
   for(int pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
    OrderSelect(pos, SELECT_BY_POS)            // Only my orders w/
&&  OrderSymbol()== Symbol()){               // and period and symbol
    int duration = TimeCurrent() - OrderOpenTime();
    if (duration >= maxDuration)
         OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(),
                     3*Point);
}  

  
    
  }
  
void CheckForOpen()
  {
  string TradeStartTime = "10:30";
  string TradeStopTime = "23:00";

//--- get Moving Average  
   //BB
   double BandsTopCurrM5=iBands(Symbol(),PERIOD_M5,20,2,0,PRICE_CLOSE,MODE_UPPER,1);
   double BandsLowCurrM5=iBands(Symbol(),PERIOD_M5,20,2,0,PRICE_CLOSE,MODE_LOWER,1);
   double BandsTopCurrM15=iBands(Symbol(),PERIOD_M15,20,2,0,PRICE_CLOSE,MODE_UPPER,1);
   double BandsLowCurrM15=iBands(Symbol(),PERIOD_M15,20,2,0,PRICE_CLOSE,MODE_LOWER,1);
   
   //OPEN CLOSE
   double openM5=iOpen(Symbol(), PERIOD_M5, 1);
   double closeM5=iClose(Symbol(), PERIOD_M5, 1);
   double openM15=iOpen(Symbol(), PERIOD_M15, 1);
   double closeM15=iClose(Symbol(), PERIOD_M15, 1);
   
   //HIGH LOW
   double highM5=iHigh(Symbol(), PERIOD_M5, 1);
   double lowM5=iLow(Symbol(), PERIOD_M5, 1);
   double highM15=iHigh(Symbol(), PERIOD_M15, 1);
   double lowM15=iLow(Symbol(), PERIOD_M15, 1);
   double ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_EMA,PRICE_WEIGHTED,1);
   
   if(OrdersTotalT(OP_SELL)==0 && TimeCurrent()>StrToTime(TradeStartTime) && TimeCurrent()<StrToTime(TradeStopTime)) { 
    if(openM15>BandsLowCurrM15 && closeM15<BandsLowCurrM15 && closeM15-lowM15!=150*Point && highM15-openM15>=closeM15-lowM15){ 
      if(openM5>BandsLowCurrM5 && closeM5<BandsLowCurrM5 && closeM5-lowM5!=0){
     
         double _sl= MathRound(ma-closeM5)/_point;
         SendOrder(OP_SELL,_sl);
          }
     }
   }
   if(OrdersTotalT(OP_BUY)==0 && TimeCurrent()>StrToTime(TradeStartTime) && TimeCurrent()<StrToTime(TradeStopTime))
     {
     if(openM15<BandsTopCurrM15 && closeM15>BandsTopCurrM15 && highM15-closeM15!=150*Point && highM15-closeM15<=openM15-lowM15){
       if(openM5<BandsTopCurrM5 && closeM5>BandsTopCurrM5 && highM5-closeM5!=0){
            double _sl = MathRound(closeM5-ma)/_point;//
            SendOrder(OP_BUY,_sl);
        }
      }
     }
//---
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//---

  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//---

  }
//+------------------------------------------------------------------+
// function to send order
bool SendOrder(int type,double _sl)
  {
   while(IsTradeContextBusy());
   int ticket=-1;
   double SL,TP;
   double lots=0;
   double Lots;
   if(type==OP_BUY)
     {
      if(_sl==0){SL=0;}else{SL=Ask-3*_sl*_point;}
      if(_sl==0){TP=0;}else{TP=Ask+2*_sl*_point;}
      Lots=(AccountBalance() * 2.6 / 100) / (SL * Point);
      lots=Lots;
      ticket=OrderSend(Symbol(),OP_BUY,NormalizeLots(lots,Symbol()),Ask,3,SL,TP,EA_Comment,MagicNumber,0);
     }
   if(type==OP_SELL)
     {
      if(_sl==0){SL=0;}else{SL=Bid+3*_sl*_point;}
      if(_sl==0){TP=0;}else{TP=Bid-2*_sl*_point;}
      Lots=(AccountBalance() * 2.6 / 100) / (SL * Point);
      lots=Lots;
      ticket=OrderSend(Symbol(),OP_SELL,NormalizeLots(lots,Symbol()),Bid,3,SL,TP,EA_Comment,MagicNumber,0);
     }
   if(ticket<0)
     {
      Print("OrderSend  failed with error #",GetLastError());
      return(false);
     }
   return(true);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//make lots to right format
double NormalizeLots(double _lots,string pair="")
  {
   if(pair=="") pair=Symbol();
   double  lotStep=MarketInfo(pair,MODE_LOTSTEP),
   minLot=MarketInfo(pair,MODE_MINLOT);
   _lots=MathRound(_lots/lotStep)*lotStep;
   if(_lots<MarketInfo(pair,MODE_MINLOT)) _lots=MarketInfo(pair,MODE_MINLOT);
   if(_lots>MarketInfo(pair,MODE_MAXLOT)) _lots=MarketInfo(pair,MODE_MAXLOT);
   return(_lots);
  }

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

int OrdersTotalT(int _type)
  {
   int _total=0;
   for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {

      bool select=OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
      if(OrderMagicNumber()==MagicNumber && OrderSymbol()==Symbol() && OrderType()==_type)
        {
         _total++;
        }
     }
   return(_total);
  }
  
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) continue;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//--- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

Files:
M15.PNG  53 kb
M5.PNG  70 kb
 
Dany William:

Thanks so much sir


it doesn't work again :-(

The condition before placing an order should be:

BUY CONDITION: 

-Breakout of the upper bands on M15, and when the candle on M15 closed above the upper band,confirm the condition on M5 chart(after M15 candle closed,wait a new candle M5 to confirm the trade,the new candle must be an UP CANDLE)

SELL CONDITION:

-Breakout of the lower bands on M15, and when the candle on M15 closed below the lower band,confirm the condition on M5 chart( after M15 candle closed,wait a new candle M5 to confirm the trade,the new candle must be a DOWN CANDLE )


this is the updated code that I tried and the bad signal(photo)

please help me, I did it for my project(study at school)

 

I have tried sthg like this too but it does not work

void CheckForOpen()
  {
  string TradeStartTime = "10:30";
  string TradeStopTime = "23:00";

//--- get Moving Average  
   //BB
   double BandsTopCurrM51=iBands(Symbol(),PERIOD_M5,20,2,0,PRICE_CLOSE,MODE_UPPER,1);
   double BandsLowCurrM51=iBands(Symbol(),PERIOD_M5,20,2,0,PRICE_CLOSE,MODE_LOWER,1);
   double BandsTopCurrM15=iBands(Symbol(),PERIOD_M15,20,2,0,PRICE_CLOSE,MODE_UPPER,1);
   double BandsLowCurrM15=iBands(Symbol(),PERIOD_M15,20,2,0,PRICE_CLOSE,MODE_LOWER,1);
   
   //OPEN CLOSE
   double openM51=iOpen(Symbol(), PERIOD_M5, 1);
   double closeM51=iClose(Symbol(), PERIOD_M5, 1);
   double openM15=iOpen(Symbol(), PERIOD_M15, 1);
   double closeM15=iClose(Symbol(), PERIOD_M15, 1);
   
   //HIGH LOW
   double highM51=iHigh(Symbol(), PERIOD_M5, 1);
   double lowM51=iLow(Symbol(), PERIOD_M5, 1);
   double highM15=iHigh(Symbol(), PERIOD_M15, 1);
   double lowM15=iLow(Symbol(), PERIOD_M15, 1);
   double ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_EMA,PRICE_WEIGHTED,1);
   static int _time_waiting=0;
// ...SELL
   if ( openM15>BandsLowCurrM15 && closeM15<BandsLowCurrM15 && closeM15-lowM15!=0 && highM15-openM15>=closeM15-lowM15 ){ // condition that requires to hold a pause
   _time_waiting = TimeLocal() + 300; // the pause ends in 10 seconds after the current local time
   if ( TimeLocal() >= _time_waiting )
   { 
      if(OrdersTotalT(OP_SELL)==0 && TimeCurrent()>StrToTime(TradeStartTime) && TimeCurrent()<StrToTime(TradeStopTime) && closeM51-lowM51!=0 && openM51>BandsLowCurrM51 && closeM51<BandsLowCurrM51){
     
         double _sl= MathRound(ma-closeM51)/_point;
         SendOrder(OP_SELL,_sl);
          }
   }}
// program block to be executed at every tick, not related to waiting for the end of the pause
// ...

// ...BUY
if ( openM15<BandsTopCurrM15 && closeM15>BandsTopCurrM15 && highM15-closeM15!=0 && highM15-closeM15<=openM15-lowM15 ){ // condition that requires to hold a pause
   _time_waiting = TimeLocal() + 300; // the pause ends in 10 seconds after the current local time
if ( TimeLocal() >= _time_waiting )
{ 
   if(highM51-closeM51!=0 && openM51<BandsTopCurrM51 && closeM51>BandsTopCurrM51 && OrdersTotalT(OP_BUY)==0 && TimeCurrent()>StrToTime(TradeStartTime) && TimeCurrent()<StrToTime(TradeStopTime)){
            double _sl = MathRound(closeM51-ma)/_point;//
            SendOrder(OP_BUY,_sl);
        }
}}
// program block to be executed at every tick, not related to waiting for the end of the pause

//---
  }
 
Dany William:

I have tried sthg like this too but it does not work

Your issue lies in the following line:

   _time_waiting = TimeLocal() + 300; // the pause ends in 10 seconds after the current local time
   if ( TimeLocal() >= _time_waiting )

You call CheckForOpen every tick, your time_waiting resets upon each call. Maybe you should add a while-loop to wait for the time to pass.

_time_waiting = TimeLocal() + 300; // the pause ends in 10 seconds after the current local time

While (TimeLocal() < _time_waiting) { } //Create a while loop to wait before execute next line
if ( TimeLocal() >= _time_waiting ){ 

Since you are using TimeLocal in your code, which uses the current computer time, I think you will not be able to backtest the code correctly. 

Reason: