Candle data not aligning

 

Hi all,

Rookie/noob here, thinking he figured out the issue but failed again. I have been working on this for a couple days and thought i fixed it last night by resizing the arrays. As you can see below the close shows 1.10374 for the second last candle. Assuming based on the code is states that it is the current bar but the previous bar or none of the others close by seem to have a closing price of 1.10397.

My question is, is this a code issue or a data issue with my mt5? I had issues with this the last couple days which i thought i resolved by resizing the arrays. This is also making my back test inaccurate/ I'd like to also add when testing on real data it does the same thing where the current bar shows the previous closing price and the previous bar shows the current closing price:


It went from consistently showing the previous bar data in the print statement for current bar (and vice versa) to now showing another close bar price (i have made some updates along the way but still data price issue). 



The area below shows the section of code, any help would be much appreciated:

   MqlRates rates[];
   
   // Get the rates
   int copiedRates = CopyRates(Symbol(), PERIOD_H4, 0, 2, rates);
   if(copiedRates < 2)
   {
      Print("CopyRates failed, error = ", GetLastError());
      return;
   }
   else
   {
      Print("Copied ", copiedRates, " rates.");
   }
   // Resize the arrays
   ArrayResize(rates, 2);

//Then somewhere down the line

// Print an error message
    Print("CopyBuffer failed, error = ", GetLastError());
   }
   //Test - Print the bar time
   Print("Current bar time: ", TimeToString(rates[0].time));
   Print("Previous bar time: ", TimeToString(rates[1].time));
   
   // Print the closing prices for the current and previous bars
   Print("Current bar closing price: ", rates[0].close);
   Print("Previous bar closing price: ", rates[1].close);



///ALL CODE BELOW FOR Context

#include <Trade\Trade.mqh> // Include the file that contains the CTrade class

//+------------------------------------------------------------------+
//|                                                        WazMA.mq5 |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

input double TakeProfit = 100;
input double StopLoss = 50;
input double TrailStop = 100;
input double LotSize = 1;
input bool Long_Positions = true;
input bool Short_Positions = true;
input int SMA_Period = 1;
input int MagicNumber = 12345;

CTrade trade; 


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
 
 //+------------------------------------------------------------------+
//| Trailing Stop function                                           |
//+------------------------------------------------------------------+
void TrailingStop() {
    for (int i = 0; i < PositionsTotal(); i++) {
        ulong ticket = PositionGetTicket(i);
        if (PositionSelectByTicket(ticket)) {
            string symbol = PositionGetString(POSITION_SYMBOL);
            ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
            double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
            double stopLoss = PositionGetDouble(POSITION_SL);
            double currentPrice = (type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK);
            if (symbol == Symbol() && PositionGetInteger(POSITION_MAGIC) == MagicNumber) {
                if (type == POSITION_TYPE_BUY) {
                    if (currentPrice - openPrice > TrailStop * _Point) {
                        if (stopLoss < currentPrice - TrailStop * _Point) {
                            trade.PositionModify(ticket, currentPrice - TrailStop * _Point, PositionGetDouble(POSITION_TP));
                        }
                    }
                } else if (type == POSITION_TYPE_SELL) {
                    if (openPrice - currentPrice > TrailStop * _Point) {
                        if (stopLoss > currentPrice + TrailStop * _Point || stopLoss == 0) {
                            trade.PositionModify(ticket, currentPrice + TrailStop * _Point, PositionGetDouble(POSITION_TP));
                        }
                    }
                }
            }
        }
    }
}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // Initialize the counters
   int totalPositions = PositionsTotal();
   int buyOrders = 0;
   int sellOrders = 0;

   // Count the number of buy and sell orders
   for(int i = 0; i < totalPositions; i++) {
       string symbol = PositionGetSymbol(i);
       if(symbol == _Symbol) {
           ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
           if(type == POSITION_TYPE_BUY) {
               buyOrders++;
           } else if(type == POSITION_TYPE_SELL) {
               sellOrders++;
           }
       }
   }
   // Check if there are any open positions
   if(PositionsTotal() >= 2)
   {
      TrailingStop();
      return;
   }
   MqlRates rates[];
   
   // Get the rates
   int copiedRates = CopyRates(Symbol(), PERIOD_M1, 0, 2, rates);
   if(copiedRates < 2)
   {
      Print("CopyRates failed, error = ", GetLastError());
      return;
   }
   else
   {
      Print("Copied ", copiedRates, " rates.");
   }
   // Resize the arrays
   ArrayResize(rates, 2);

   // Create a handle for the SMA indicator
   int handleHigh = iMA(Symbol(), PERIOD_M1, SMA_Period, 0, MODE_SMA, PRICE_HIGH);
   int handleLow = iMA(Symbol(), PERIOD_M1, SMA_Period, 0, MODE_SMA, PRICE_LOW);
   
   // Create arrays to hold the SMA values
   double currentSMA_High[];
   double previousSMA_High[];
   double currentSMA_Low[];
   double previousSMA_Low[];
   
   // Resize the arrays
   ArrayResize(currentSMA_High, 1);
   ArrayResize(previousSMA_High, 1);
   ArrayResize(currentSMA_Low, 1);
   ArrayResize(previousSMA_Low, 1);
   
   // Copy the SMA values into the arrays
   int copiedCurrentHigh = CopyBuffer(handleHigh, 0, 0, 1, currentSMA_High);
   int copiedPreviousHigh = CopyBuffer(handleHigh, 0, 1, 1, previousSMA_High);
   int copiedCurrentLow = CopyBuffer(handleLow, 0, 0, 1, currentSMA_Low);
   int copiedPreviousLow = CopyBuffer(handleLow, 0, 1, 1, previousSMA_Low);
   
   //Double Check if the copy was successful
   if(copiedCurrentHigh > 0 && copiedPreviousHigh > 0)
   {
    // Print the SMA values
    Print("Current SMA High: ", currentSMA_High[0]);
    Print("Previous SMA High: ", previousSMA_High[0]);
    Print("Current SMA Low: ", currentSMA_Low[0]);
    Print("Previous SMA Low: ", previousSMA_Low[0]);
   }
   else
   {
    // Print an error message
    Print("CopyBuffer failed, error = ", GetLastError());
   }
   //Test - Print the bar time
   Print("Current bar time: ", TimeToString(rates[0].time));
   Print("Previous bar time: ", TimeToString(rates[1].time));
   
   // Print the closing prices for the current and previous bars
   Print("Current bar closing price: ", rates[0].close);
   Print("Previous bar closing price: ", rates[1].close);
   
   
   // Buy conditions
   if(Long_Positions==true)
   {
   if(buyOrders < 2) {
   if(rates[1].close < previousSMA_High[0] && rates[0].close > currentSMA_High[0])
   {
    {
      MqlTradeRequest request;
      MqlTradeResult result;
      
      ZeroMemory(request);
      
      request.action = TRADE_ACTION_DEAL;
      request.symbol = Symbol();
      request.volume = LotSize;
      request.type = ORDER_TYPE_BUY;
      request.price = NormalizeDouble(SymbolInfoDouble(Symbol(), SYMBOL_ASK), _Digits);
      request.sl = NormalizeDouble(request.price - StopLoss * _Point, _Digits);
      request.tp = NormalizeDouble(request.price + TakeProfit * _Point, _Digits);
      
      if(!OrderSend(request,result))
         Print("OrderSend failed with error #",GetLastError());
      else
         Print("OrderSend succeeded. Order #",result.order," placed with ",result.retcode," return code.");
      }
      }
      }
   }
   
   // Sell conditions
   if(Short_Positions==true)
   {
   if(sellOrders < 2) {
   if(rates[1].close > previousSMA_Low[0] && rates[0].close < currentSMA_Low[0])
   {
      MqlTradeRequest request;
      MqlTradeResult result;
      
      ZeroMemory(request);
      
      request.action = TRADE_ACTION_DEAL;
      request.symbol = Symbol();
      request.volume = LotSize;
      request.type = ORDER_TYPE_SELL;
      request.price = NormalizeDouble(SymbolInfoDouble(Symbol(), SYMBOL_BID), _Digits);
      request.sl = NormalizeDouble(request.price + StopLoss * _Point, _Digits);
      request.tp = NormalizeDouble(request.price - TakeProfit * _Point, _Digits);
      
      if(!OrderSend(request,result))
         Print("OrderSend failed with error #",GetLastError());
      else
         Print("OrderSend succeeded. Order #",result.order," placed with ",result.retcode," return code.");
      }
      }
      }
  }
//+------------------------------------------------------------------+
   
 
bump - no one knows? It seems to error as well with normal Mt5 with a demo account, and the H4 real money below as well?

 
ok i created 2 arrays and seems to work, for now.