Place purchase order in another period

 

Hi everyone,

I'm new in MQL5 and the following code is not working for me, what I want is that when it detects the crossing of the two H1 moving averages, I change the period with ChartSetSymbolPeriod to M5 and place the purchase order (orderSend) and close the purchase (orderClose or trade. PositionClose) when I detect the crossing of the two moving averages in M5, I know that the ChartSetSymbolPeriod function performs the period change asynchronously, am I using this correctly? Should I do it with ChartSetSymbolPeriod or another way? It turns out that I don't know why it is not working for me, it never enters the condition of the moving averages in the M5 period:

#property copyright "ATILA"
#property link      ""

#include <Trade/trade.mqh>

int takeProfit = 200;
int stopLoss = 100;
CTrade trade;
datetime openTimeBuy = 0;
datetime verticalLines[];
// H1
int maH1_period10, maH1_period20, maH1_period200;
double maH1_period10_Array[], maH1_period20_Array[], maH1_period200_Array[];
// M5
int maM5_period20, maM5_period50;
double maM5_period20_Array[], maM5_period50_Array[];

// Variables globales
MqlRates velasH1[];
MqlRates velasM5[];

int candleCount = 0;

double takeProfitLevel = 0.0; // Nivel de Take Profit

// Declarar una variable para rastrear el estado de la orden
bool isOrderOpen = false;


int OnInit()
{
   ChartSetInteger(0, CHART_SHOW_GRID, false);
   ChartSetInteger(0, CHART_MODE, CHART_CANDLES);
   ChartSetInteger(0, CHART_COLOR_BACKGROUND, clrBlack);
   ChartSetInteger(0, CHART_COLOR_FOREGROUND, clrWhite);
   ChartSetInteger(0, CHART_COLOR_CANDLE_BULL, clrWhite);
   ChartSetInteger(0, CHART_COLOR_CHART_UP, clrWhite);
   ChartSetInteger(0, CHART_COLOR_CHART_DOWN, clrRed);
   ChartSetInteger(0, CHART_COLOR_CANDLE_BEAR, clrRed);
   ChartSetInteger(0, CHART_COLOR_STOP_LEVEL, clrGold);
   ChartSetInteger(0, CHART_SHOW_VOLUMES, false);
   
   // H1
   maH1_period10 = iMA(_Symbol, PERIOD_H1, 10, 0, MODE_SMA, PRICE_CLOSE);
   maH1_period20 = iMA(_Symbol, PERIOD_H1, 20, 0, MODE_SMA, PRICE_CLOSE);
   maH1_period200 = iMA(_Symbol, PERIOD_H1, 200, 0, MODE_SMA, PRICE_CLOSE);
   
   //M15
   maM5_period20 = iMA(_Symbol, PERIOD_M5, 20, 0, MODE_SMA, PRICE_CLOSE);
   maM5_period50 = iMA(_Symbol, PERIOD_M5, 50, 0, MODE_SMA, PRICE_CLOSE);
   
  
   return(INIT_SUCCEEDED);
}

void OnDeinit()
{
}

void OnTick()
{
   // H1
   ArraySetAsSeries(maH1_period10_Array, true);
   ArraySetAsSeries(maH1_period20_Array, true);
   ArraySetAsSeries(maH1_period200_Array, true);
   
   ArraySetAsSeries(velasH1, true);

   CopyBuffer(maH1_period10, 0, 0, 3, maH1_period10_Array);
   CopyBuffer(maH1_period20, 0, 0, 3, maH1_period20_Array);
   CopyBuffer(maH1_period200, 0, 0, 3, maH1_period200_Array);
   
   // M15 
   ArraySetAsSeries(maM5_period20_Array, true);
   ArraySetAsSeries(maM5_period50_Array, true);
   
   //ArraySetAsSeries(velasM5, true);

   CopyBuffer(maM5_period20, 0, 0, 3, maM5_period20_Array);
   CopyBuffer(maM5_period50, 0, 0, 3, maM5_period50_Array);
   
   MACrossOver(maH1_period10_Array, maH1_period20_Array ,maH1_period200_Array);
}

void MACrossOver(double &maH1_period10_Array[], double &maH1_period20_Array[], double &maH1_period200_Array[])
{
   // Tendencia ALCISTA
   if (isBullishTrendThreeMACrossOver(maH1_period10_Array, maH1_period20_Array ,maH1_period200_Array))
   {
         // Verificar si ya hay una orden abierta
      if (!isOrderOpen)
      {
         createVerticalLine("BuyLine" + IntegerToString(ArraySize(verticalLines)), clrBlue, TimeCurrent());
   
         CopyRates(_Symbol, PERIOD_H1, 0, 1, velasH1);
         CopyRates(_Symbol, PERIOD_M5, 0, 12, velasM5);
         
         ChartSetSymbolPeriod(ChartID(), _Symbol, PERIOD_M5);
         
         // Realizar la operación de compra sin establecer TP y SL
         double entryPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         double lotSize = 0.01; // Tamaño de lote deseado
         string comment = "BUY";
         int slippage = 3; // Deslizamiento permitido en pips
         
         Buy(123456,_Symbol,lotSize,0,0);
         
         isOrderOpen = true;
         
         if ( maM5_period50_Array[0] > maM5_period20_Array[0] && maM5_period50_Array[1] <= maM5_period20_Array[1] ) {
            
            CloseAllPosition();
            isOrderOpen = false;
            printf("******M5*******");
         }
      }
      
      // Tendencia BAJISTA
   } /*else if (isBearishTrendThreeMACrossOver(maH1_period10_Array, maH1_period20_Array ,maH1_period200_Array)) {
      
                 double entryPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
                 ArrayResize(verticalLines, ArraySize(verticalLines) + 1);
                 verticalLines[ArraySize(verticalLines) - 1] = TimeCurrent();
                 createVerticalLine("SellLine" + IntegerToString(ArraySize(verticalLines)), clrRed, TimeCurrent(), entryPrice);
             }*/
 }

bool isBullishTrendThreeMACrossOver(double &myMovingAverageArray1[], double &myMovingAverageArray2[], double &myMovingAverageArray3[]) 
{

     return (myMovingAverageArray1[0] > myMovingAverageArray2[0] && myMovingAverageArray1[1] <= myMovingAverageArray2[1])
            && (myMovingAverageArray1[0] > myMovingAverageArray3[0] && myMovingAverageArray2[0] > myMovingAverageArray3[0])
            && (myMovingAverageArray1[0] > myMovingAverageArray3[0] && myMovingAverageArray2[0] > myMovingAverageArray3[0]);
            
            
}   

bool isBearishTrendThreeMACrossOver(double &fast[], double &middle[], double &slow[]) 
{
      return (fast[0] <= middle[0] && fast[1] > middle[1])
            && ( (fast[1] < slow[0] && middle[1] < slow[0])
            && (fast[0] < slow[0] && middle[0] < slow[0]));
            
}

void CloseAllPosition()
{
   for( int i = PositionsTotal() - 1; i >= 0; i++ )
   {
      int ticket = PositionGetTicket(i);
      trade.PositionClose(ticket);
   }
}

void createVerticalLine(string name, color clr, datetime time)
{
   double entryPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   ArrayResize(verticalLines, ArraySize(verticalLines) + 1);
   verticalLines[ArraySize(verticalLines) - 1] = TimeCurrent();

   int line = ObjectCreate(0, name, OBJ_VLINE, 0, time, entryPrice);
   if (line != -1)
   {
      ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
      ObjectSetInteger(0, name, OBJPROP_WIDTH, 3);
      ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, false);
      ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
   }
}

//+------------------------------------------------------------------+
//| Opening Buy position                                             |
//+------------------------------------------------------------------+
void Buy(int magicnumber,string symbol,double lots,double tp,double sl)
{
//--- declare and initialize the trade request and result of trade request
   MqlTradeRequest request {};
   MqlTradeResult  result {};
//--- parameters of request
   request.action    = TRADE_ACTION_DEAL;                     // type of trade operation
   request.symbol    = symbol;                                // symbol
   request.volume    = lots;                                  // volume
   request.type      = ORDER_TYPE_BUY;                        // order type
   request.price     = SymbolInfoDouble(symbol,SYMBOL_ASK);   // price for opening
   request.deviation = 3;                                     // allowed deviation from the price
   request.sl        = sl;                                    // Stop Loss of the position
   request.tp        = tp;                                    // Take Profit of the position
   request.magic     = magicnumber;                           // MagicNumber of the order
//--- send the request
   if(!OrderSend(request,result))
      PrintFormat("OrderSend error %d",GetLastError());       // if unable to send the request, output the error code
//--- information about the operation
   PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);
            MqlDateTime dt_struct;
         datetime dtSer=TimeCurrent(dt_struct);
         string hora = StringFormat("%02d", dt_struct.hour);
         string min = StringFormat("%02d", dt_struct.min);
         string seg = StringFormat("%02d", dt_struct.sec);
               
         printf(" HORA ACTUAL: " + hora + ":" + min + ":" + seg);
}

Could someone help me? attached (example.png)

Documentation on MQL5: Chart Operations / ChartSetSymbolPeriod
Documentation on MQL5: Chart Operations / ChartSetSymbolPeriod
  • www.mql5.com
ChartSetSymbolPeriod - Chart Operations - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Files:
example.png  179 kb
 
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 

Trades are totally independent of the time-frame. There is no need to change the time-frame of the chart.

Your EA can access data from any time-frame simultaneously, independent of what the chart's current time-frame may be.

Forcing a time-frame change on the chart will cause you EA (and all Indicators) to restart, going through a OnDeInit and OnInit cycle on all of them.

The simple resolution to your issue, is DO NOT force a change of chart time-frame. It is inefficient, counter-productive and a very bad design for your EA.

Reason: