EXPERT ADVISOR - Order not being opened on bar closed

 

Hello,

 How are you doing? Hope you are doing well.

 I have coded an EA to trade in H4 periods. I'm having an issue and I can't solve it, even if I've been trying it since a lot of time.

 This is the issue:

The EA is NOT opening or closing the orders when the H4 bar is closed. I need the EA to open or close the orders when the opening or closing conditions are true, and the H4 bar is closed. 

I have been truying by using the "iClose" function, but is not functioning.

 Your help will be appreciated.

Regards.  

 

There are many reasons of this issue !.

You need to show your code to understand what is going on, otherwise, no one can help you. 

 
Osama Shaban:

There are many reasons of this issue !.

You need to show your code to understand what is going on, otherwise, no one can help you. 

Hi Osama, 

   Thanks for advising me this.

   I'll erase all the commented code so it can be more understandable, and I'll be showing it. 

   Regards. 

 
AjsTrader86:

Hello,

 How are you doing? Hope you are doing well.

 I have coded an EA to trade in H4 periods. I'm having an issue and I can't solve it, even if I've been trying it since a lot of time.

 This is the issue:

The EA is NOT opening or closing the orders when the H4 bar is closed. I need the EA to open or close the orders when the opening or closing conditions are true, and the H4 bar is closed. 

I have been truying by using the "iClose" function, but is not functioning.

 Your help will be appreciated.

Regards.  

iClose() is returning the close price, not closing an order


iClose

Returns Close price value for the bar of specified symbol with timeframe and shift.

double  iClose(
   string           symbol,          // symbol
   int              timeframe,       // timeframe
   int              shift            // shift
   );

Parameters

symbol

[in]  Symbol name. NULL means the current symbol.

timeframe

[in]  Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the current chart timeframe.

shift

[in]  Index of the value taken from the indicator buffer (shift relative to the current bar the given amount of periods ago).

Returned value

Close price value for the bar of specified symbol with timeframe and shift. If local history is empty (not loaded), function returns 0. To check errors, one has to call the GetLastError() function.

Note

For the current chart, the information about close prices is in the Close[] predefined array.

Example:

  Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,0),", ",  iOpen("USDCHF",PERIOD_H1,0),", ",
                                      iHigh("USDCHF",PERIOD_H1,0),", ",  iLow("USDCHF",PERIOD_H1,0),", ",
                                      iClose("USDCHF",PERIOD_H1,0),", "iVolume("USDCHF",PERIOD_H1,0));

 

1) create global variable 

int prev_bars;

2) in init write

prev_bars=iBars(Symbol(),PERIOD_H4);

3) in OnTick() where you need code once a bar write 

int bars=iBars(Symbol(),PERIOD_H4);

if(prev_bars==bars) return;

 prev_bars=bars;

 
Fstrifoerr8: if(prev_bars==bars) return;
Bars is unreliable (a refresh/reconnect can change number of bars on chart) volume is unreliable (miss ticks) Always use time. New candle - MQL4 forum
 
whroeder1:

Bars is unreliable (a refresh/reconnect can change number of bars on chart) volume is unreliable (miss ticks) Always use time. New candle - MQL4 forum
<Post removed>
 
Fstrifoerr8:
<Post removed>
If you continue to post with the intention to disrupt the forum, you will be banned
 
Mladen Rakic:

iClose() is returning the close price, not closing an order


Hi Mladen, 

 Thanks for your response.

 I know that iClose returns the close price. I use it to verify if the long entry conditions are true.

 Regards. 

 

Hi, 

 As I said before, below you can see the EA's code and how the iClose is being used to set the conditions when an order is opened.

 I hope that this can clarify the issue.

 Thanks in advance for your opinions!

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

//|                                   Ichimoku_Setup_H4_AJS_v1.8.mq4 |

//|                                                    Jona Siracusa |

//|                                                                  |

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


#property copyright "Jona Siracusa"

#property version   "1.80"

#property strict


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

//| 1. Inicio de variables externas                                  |

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


// Iniciamos las variables externas


extern double TakeProfit=1000;

extern double StopLoss=400;

extern double TrailingStop=350;

extern double Lots=0.05;


extern int Tenkan_sen_per = 7;

extern int Kijun_sen_per = 22;

extern int Senkou_Span_B_per = 44;


extern double Dif_precio_Kumo = 10;


extern string Activo = "USOIL";

extern int Per_grafico = 240;


extern int MinDuration_MIN = 240;

extern int MinDuration_Salida_Kumo = 20;


extern bool Sunday = true;

extern bool Monday = true;

extern bool Tuesday = true;

extern bool Wednesday = true;

extern bool Thursday = true;

extern bool Friday = true;



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

//| 2. Declaro las variables internas globales                       |

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


double Tenkan_sen, Kijun_sen, Chikou_span;

double Senkou_span_A, Senkou_span_B;

double Tenkan_sen_1, Kijun_sen_1;

double Senkou_span_A_1, Senkou_span_B_1;


double Aper, Cierre;

double Aper_ant, Cierre_ant;


int cnt, ticket, total;

int duration, Min_duration, Duration_Kumo, Min_Duration_Kumo;



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

//| 3. Comienzo del programa                                         |

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


int start()

  {

  

   cnt = 0;

   Min_duration = MinDuration_MIN * 60;  // Se multiplica por 60, para convertirlo en minutos.

   Min_Duration_Kumo = MinDuration_Salida_Kumo * 60;  // Se multiplica por 60, para convertirlo en minutos.


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

//| 4. Comprobacion inicial de los datos y referencio variables internas |

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


// Comprobacion de Take Profit

   if(Bars<100)

     {

      Print("Menos de 100 barras");

      return(0);

     }


   Tenkan_sen = iIchimoku(Activo, Per_grafico, Tenkan_sen_per, Kijun_sen_per, Senkou_Span_B_per, MODE_TENKANSEN, 0);

   Kijun_sen = iIchimoku(Activo, Per_grafico, Tenkan_sen_per, Kijun_sen_per, Senkou_Span_B_per, MODE_KIJUNSEN, 0);

   Chikou_span = iIchimoku(Activo, Per_grafico, Tenkan_sen_per, Kijun_sen_per, Senkou_Span_B_per, MODE_CHIKOUSPAN, 0);

   Senkou_span_A = iIchimoku(Activo, Per_grafico, Tenkan_sen_per, Kijun_sen_per, Senkou_Span_B_per, MODE_SENKOUSPANA, 0);

   Senkou_span_B = iIchimoku(Activo, Per_grafico, Tenkan_sen_per, Kijun_sen_per, Senkou_Span_B_per, MODE_SENKOUSPANB, 0);

  

   Tenkan_sen_1 = iIchimoku(Activo, Per_grafico, Tenkan_sen_per, Kijun_sen_per, Senkou_Span_B_per, MODE_TENKANSEN, 1);

   Kijun_sen_1 = iIchimoku(Activo, Per_grafico, Tenkan_sen_per, Kijun_sen_per, Senkou_Span_B_per, MODE_KIJUNSEN, 1);

   Senkou_span_A_1 = iIchimoku(Activo, Per_grafico, Tenkan_sen_per, Kijun_sen_per, Senkou_Span_B_per, MODE_SENKOUSPANA, 1);

   Senkou_span_B_1 = iIchimoku(Activo, Per_grafico, Tenkan_sen_per, Kijun_sen_per, Senkou_Span_B_per, MODE_SENKOUSPANB, 1);

  

   Cierre = iClose(Activo, Per_grafico, 0);

   Aper = iOpen(Activo, Per_grafico,0);

   Cierre_ant = iClose(Activo, Per_grafico, 1);



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

//| 5. DESARROLLO DEL SETUP                                          |

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



//| 5.1 Condiciones de Filtro                                        |

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



//| 5.2 Apertura de posiciones                                       |

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


// Chequeamos que no hay ordenes abiertas, entonces seguimos adelante.

   total = OrdersTotal();

  

   if((total < 1) && DaytoTrade())

      {

      if(AccountFreeMargin()<(1000*Lots))

        {

         Print("No hay fondos suficientes en la cuenta. Margen libre = ",AccountFreeMargin());

//         return(0);

        }



// Vemos la posibilidad de abrir una POSICION LARGA, si se cumple el Setup


         if((LONG_entry() == true))

            {

            

         // Colocamos una Orden (OrderSend) y asignamos a Ticket todos los parametros de la Orden

            ticket = OrderSend(Activo, OP_BUY, Lots, Ask, 3, Bid - (StopLoss * Point),

                              Ask + (TakeProfit * Point), " Ichimoku_Setup_H4_AJS_v1.8", 1986, 0, Blue);

                    

         // Chequeamos que la Orden se haya abierto correctamente  

            if(ticket > 0)

               {

               if(OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))  // "True" si la orden succeded.

                  Print("Orden BUY abierta: ", OrderOpenPrice());

               }

            else Print("Error de apertura de posición BUY: ", GetLastError());

            return(0);              

            }




// Vemos la posibilidad de abrir una POSICION CORTA, si se cumple el Setup

      

//   if(MACD_LP_Tend == "Bear")

//      {      

      

         if(SHORT_entry() == true)

            {

                    

         // Colocamos una Orden (OrderSend) y asignamos a Ticket todos los parametros de la Orden

            ticket = OrderSend(Activo, OP_SELL, Lots, Bid, 3, Ask + (StopLoss * Point),

                              Bid - (TakeProfit * Point), "Ichimoku_Setup_H4_AJS_v1.4", 1986, 0, Red);

                    

         // Chequeamos que la Orden se haya abierto correctamente  

            if(ticket > 0)

               {

               if(OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))  // "True" si la orden succeded.

                  Print("Orden SELL abierta: ", OrderOpenPrice());

               }

            else Print("Error de apertura de posición SELL: ", GetLastError());

            return(0);              

            }

//      }

              

   return(0);

   }

  


//| 5.3 Cierre de posiciones o modificacion de Trailing Stop         |

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


   for(cnt=0; cnt < total; cnt++)  // Si cnt = 0 y es < que Total, es porque Total > 0. Quiere decir que hay orders abiertas.

      {

      

      duration = TimeCurrent() - OrderOpenTime();    // Se compara con: Min_duration

      Duration_Kumo = TimeCurrent() - OrderOpenTime();    // Se compara con: Min_duration

      

      

      if((OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) == true) && (duration >= Min_duration))  // "True" si la orden succeded.

         {



// Comprobamos si hay posiciones abiertas  

            

         if(OrderType() <= OP_SELL &&  // Comprueba que hay una posicion abierta. OP_SELL = 1, OP_BUY = 0, por lo que esta preguntando si la orden es BUY o SELL.

            OrderSymbol() == Activo)   // Comprueba el activo de la orden.

            {

            

   // Si es una POSICION LARGA        

            if(OrderType() == OP_BUY)

               {

                          

            // Verificamos si debe cerrarse la Orden  

               if(LONG_exit() == true)

                  {

                  // NO DEBERIA IR UN ORDERCLOSE ACA?  

                  Print("SE CUMPLIO EL SETUP DE CIERRE BUY");            

                  OrderClose(OrderTicket(), OrderLots(), Cierre, 3, Violet);

  

                  if(!OrderClose(OrderTicket(), OrderLots(), Bid, 3, Violet))  // Se cierra la posicion

                     Print("OrderClose error ",GetLastError());

                  return(0);  // Salimos del If.

//                  return(0);

                  }          

               }


            

   // Si es una posicion CORTA

            else

               {

                    

            // Verificamos si debe cerrarse la Orden  

               if(SHORT_exit() == true)

                  {

                  // NO DEBERIA IR UN ORDERCLOSE ACA?

                  Print("SE CUMPLIO EL SETUP DE CIERRE SELL");            

                  OrderClose(OrderTicket(), OrderLots(), Ask, 3, Violet);


                  if(!OrderClose(OrderTicket(), OrderLots(), Ask, 3, Violet))  // Se cierra la posicion

                     Print("OrderClose error ",GetLastError());

//                  return(0);  // Salimos del If.

                    return(0);  

                    }          

               }                      

         }              

      }

   }

      return(0);      

      }




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

//| Funciones varias                                                 |

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


//Función para determinar los días en los que el EA duerme.


bool DaytoTrade(){

bool daytotrade = false;


if(DayOfWeek() == 0 && Sunday) daytotrade = true;

if(DayOfWeek() == 1 && Monday) daytotrade = true;

if(DayOfWeek() == 2 && Tuesday) daytotrade = true;

if(DayOfWeek() == 3 && Wednesday) daytotrade = true;

if(DayOfWeek() == 4 && Thursday) daytotrade = true;

if(DayOfWeek() == 5 && Friday) daytotrade = true;


return(daytotrade);}



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

//| Funciones del SETUP                                              |

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


//| Apertura de posiciones                                           |

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


// Posicion LARGA


bool LONG_entry(){

bool long_entry = false;


if(

   ((Cierre_ant <= Senkou_span_A) && (Cierre > (Senkou_span_A + (Dif_precio_Kumo * Point))) &&    

   ((Cierre > Senkou_span_A) && (Cierre > Senkou_span_B)) &&

   (Cierre > Kijun_sen))

   ||

   ((Cierre_ant <= Senkou_span_B) && (Cierre > (Senkou_span_B + (Dif_precio_Kumo * Point))) &&    

   ((Cierre > Senkou_span_A) && (Cierre > Senkou_span_B)) &&

   (Cierre > Kijun_sen))              

   )

   {long_entry = true;}


return(long_entry);}



// Posicion CORTA


bool SHORT_entry(){

bool short_entry = false;


if(

   ((Cierre_ant >= Senkou_span_A) && (Cierre < (Senkou_span_A - (Dif_precio_Kumo * Point))) &&    

   ((Cierre < Senkou_span_A) && (Cierre < Senkou_span_B)) &&

   (Cierre < Kijun_sen))

   ||

   ((Cierre_ant >= Senkou_span_B) && (Cierre < (Senkou_span_B - (Dif_precio_Kumo * Point))) &&    

   ((Cierre < Senkou_span_A) && (Cierre < Senkou_span_B)) &&

   (Cierre < Kijun_sen))

   )

   {short_entry = true;}


return(short_entry );}



//| Cierre de posiciones                                             |

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


// Posicion LARGA


bool LONG_exit(){

bool long_exit = false;


if(

   (

   ((Cierre_ant >= Senkou_span_A) && (Cierre < Senkou_span_A)) ||

   ((Cierre_ant >= Senkou_span_B) && (Cierre < Senkou_span_B))

   )

   ||

   (

   (Cierre < Kijun_sen)

   )

   )

   {long_exit = true;}


return(long_exit);}



// Posicion CORTA


bool SHORT_exit(){

bool short_exit = false;


if(

   (

   ((Cierre_ant <= Senkou_span_A) && (Cierre > Senkou_span_A)) ||

   ((Cierre_ant <= Senkou_span_B) && (Cierre > Senkou_span_B))

   )

   ||

   (

   (Cierre > Kijun_sen)

   )

   )

   {short_exit = true;}


return(short_exit);}
 

Forum on trading, automated trading systems and testing trading strategies

Hello,

Please use the SRC button when you post code. Thank you.


This time, I edited it for you.


Reason: