I need help strategy tester tralingstop

 
Hi guys

In the demo accounts and real accounts it works well but at the moment of placing in the strategy tester the program gets these errors I have no idea which part of my code may be causing this I ask for your help to review the code in an extensive and precise manner because I am really very desperate since it is not the data nor the meta trader that is causing the error I am sure what the error is in the code

Tralingstop works fine but in the strategy tester cause of your errors any help is welcome thank you I will read all the comments
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (volume limit 4 at 2023.09.15 00:00 exceeded)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (volume limit 4 at 2023.09.15 00:00 exceeded)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (low value 28.33460 at 2023.09.14 23:00 is not reached from the least timeframe, low price 28.33790 mismatches)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (high value 28.41030 at 2023.09.14 23:00 is not reached from the least timeframe, high price 28.33790 mismatches)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (low value 28.35020 at 2023.09.14 22:00 is not reached from the least timeframe, low price 28.35560 mismatches)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (high value 28.39380 at 2023.09.14 22:00 is not reached from the least timeframe, high price 28.36140 mismatches)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (low value 28.34640 at 2023.09.14 21:00 is not reached from the least timeframe, low price 28.36110 mismatches)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (high value 28.36970 at 2023.09.14 21:00 is not reached from the least timeframe, high price 28.36280 mismatches)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (low value 28.40420 at 2023.09.14 18:00 is not reached from the least timeframe, low price 28.41930 mismatches)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (low value 28.41160 at 2023.09.14 17:00 is not reached from the least timeframe, low price 28.41510 mismatches)
2023.12.01 14:44:04.000 TestGenerator: unmatched data error (high value 28.47550 at 2023.09.14 17:00 is not reached from the least timeframe, high price 28.46280 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (low value 28.60780 at 2023.09.14 13:00 is not reached from the least timeframe, low price 28.63340 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.64320 at 2023.09.14 13:00 is not reached from the least timeframe, high price 28.63560 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (low value 28.60040 at 2023.09.14 12:00 is not reached from the least timeframe, low price 28.61090 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.63630 at 2023.09.14 12:00 is not reached from the least timeframe, high price 28.61750 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (low value 28.62150 at 2023.09.14 11:00 is not reached from the least timeframe, low price 28.62760 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.64830 at 2023.09.14 11:00 is not reached from the least timeframe, high price 28.63450 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (low value 28.62170 at 2023.09.14 10:00 is not reached from the least timeframe, low price 28.63280 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.65300 at 2023.09.14 10:00 is not reached from the least timeframe, high price 28.63280 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (low value 28.59740 at 2023.09.14 09:00 is not reached from the least timeframe, low price 28.61820 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.67120 at 2023.09.14 09:00 is not reached from the least timeframe, high price 28.65690 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.66480 at 2023.09.14 08:00 is not reached from the least timeframe, high price 28.65930 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (low value 28.42710 at 2023.09.14 06:00 is not reached from the least timeframe, low price 28.59160 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.64390 at 2023.09.14 06:00 is not reached from the least timeframe, high price 28.63000 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.61700 at 2023.09.14 05:00 is not reached from the least timeframe, high price 28.61270 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.62760 at 2023.09.14 04:00 is not reached from the least timeframe, high price 28.61690 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.62270 at 2023.09.14 03:00 is not reached from the least timeframe, high price 28.60990 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (low value 28.46660 at 2023.09.14 01:00 is not reached from the least timeframe, low price 28.46850 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (high value 28.59550 at 2023.09.14 01:00 is not reached from the least timeframe, high price 28.59170 mismatches)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (volume limit 193 at 2023.09.13 23:00 exceeded)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (volume limit 193 at 2023.09.13 23:00 exceeded)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (volume limit 193 at 2023.09.13 23:00 exceeded)
2023.12.01 14:44:03.999 TestGenerator: unmatched data error (volume limit 193 at 2023.09.13 23:00 exceeded)


@William Roeder
//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 20023, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#property strict

input bool trailingStopBuyEnabled = true;  // Habilitar/deshabilitar Trailing Stop para órdenes de compra
input int magicNumberBuy = 456;  // Número mágico para las órdenes de compra
input int trailingStopDistancebuy = 10;  // Distancia en ticks para el Trailing Stop de compra

input bool trailingStopSellEnabled = true;  // Habilitar/deshabilitar Trailing Stop para órdenes de venta
input int magicNumberSell = 123;  // Número mágico para las órdenes de venta
input int trailingStopDistancesell = 10;  // Distancia en ticks para el Trailing Stop de venta




//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
// Imprime la cabecera en la consola de MetaTrader
   Print("Número de Ticket\t\tNúmero Mágico\t\tTipo de Orden\t\tPrecio de Ejecución\t\tStop Loss");

// Inicia la función OnTick
   EventSetMillisecondTimer(1000);

   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Función de manejo de órdenes                                      |
//+------------------------------------------------------------------+
void OnTimer()
{
   string symbolActual = Symbol(); // Obtener el símbolo del gráfico actual

   // Itera a través de las órdenes activas
   for (int i = OrdersHistoryTotal() - 1; i >= 0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         Print("Error al seleccionar la orden en posición ", i);
         continue;
      }

      // Verifica si la orden está cerrada o cancelada
      if (OrderCloseTime() > 0)
         continue;

      // Verifica si el símbolo de la orden coincide con el símbolo del gráfico actual
      if (OrderSymbol() != symbolActual)
         continue;

      // Verifica si la orden es de tipo sell y tiene el número mágico correcto
      if (OrderType() == OP_SELL && OrderMagicNumber() == magicNumberSell && trailingStopSellEnabled)
      {
         AdjustTrailingStopSell(i, trailingStopDistancesell); // Ajusta el trailing stop de venta
         PrintSellOrderInfo(i); // Pasa el índice de la orden a la función
      }

      // Verifica si la orden es de tipo buy y tiene el número mágico correcto
      if (OrderType() == OP_BUY && OrderMagicNumber() == magicNumberBuy && trailingStopBuyEnabled)
      {
         AdjustTrailingStopBuy(i, trailingStopDistancebuy); // Ajusta el trailing stop de compra
         PrintBuyOrderInfo(i); // Pasa el índice de la orden a la función
      }
   }
}


//+------------------------------------------------------------------+
//| Función para ajustar el Trailing Stop de la orden de venta       |
//+------------------------------------------------------------------+
void AdjustTrailingStopSell(int orderIndex, int trailingDistance)
{
   // Asegurarse de que la orden existe
   int ticket = OrderTicket();
   if (ticket == 0)
   {
      Print("La orden no tiene un número de ticket válido.");
      return;
   }

   // Asegurarse de que la distancia del trailing stop sea válida
   if (trailingDistance <= 0)
   {
      Print("La distancia del trailing stop no es válida.");
      return;
   }

   // Obtener el precio de ejecución de la orden
   double executionPrice = OrderOpenPrice();

   // Obtener el precio ask actual
   double currentAskPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   if (currentAskPrice == 0.0)
   {
      Print("Error al obtener el precio ask. Código de error: ", GetLastError());
      return;
   }

   // Calcular el nuevo nivel de trailing stop
   double newStopLevel = NormalizeDouble(currentAskPrice + trailingDistance * Point, Digits());

   // Obtener el nivel actual del trailing stop
   double currentStopLevel = OrderStopLoss();

   // Comprobar si la orden aún es válida para ajustar el trailing stop
   if (OrderSymbol() != _Symbol || OrderType() != OP_SELL)
   {
      Print("La orden no es válida para ajustar el trailing stop.");
      return;
   }

   // Comparar el nuevo nivel con el nivel actual
   if (newStopLevel < currentStopLevel || currentStopLevel == 0.0)
   {
      // Actualizar el trailing stop solo si el nuevo nivel es menor que el nivel actual
      if (!OrderModify(ticket, 0, newStopLevel, OrderTakeProfit(), 0, 0))
      {
         Print("Error al modificar la orden. Código de error: ", GetLastError());
      }
   }
}

//+------------------------------------------------------------------+
//| Función para ajustar el Trailing Stop de la orden de compra       |
//+------------------------------------------------------------------+
void AdjustTrailingStopBuy(int orderIndex, int trailingDistance)
{
   // Asegurarse de que la orden existe
   int ticket = OrderTicket();
   if (ticket == 0)
   {
      Print("La orden no tiene un número de ticket válido.");
      return;
   }

   // Asegurarse de que la distancia del trailing stop sea válida
   if (trailingDistance <= 0)
   {
      Print("La distancia del trailing stop no es válida.");
      return;
   }

   // Obtener el precio de ejecución de la orden
   double executionPrice = OrderOpenPrice();

   // Obtener el precio bid actual
   double currentBidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   if (currentBidPrice == 0.0)
   {
      Print("Error al obtener el precio bid. Código de error: ", GetLastError());
      return;
   }

   // Calcular el nuevo nivel de trailing stop
   double newStopLevel = NormalizeDouble(currentBidPrice - trailingDistance * Point, Digits());

   // Obtener el nivel actual del trailing stop
   double currentStopLevel = OrderStopLoss();

   // Comprobar si la orden aún es válida para ajustar el trailing stop
   if (OrderSymbol() != _Symbol || OrderType() != OP_BUY)
   {
      Print("La orden no es válida para ajustar el trailing stop.");
      return;
   }

   // Comparar el nuevo nivel con el nivel actual
   if (newStopLevel > currentStopLevel || currentStopLevel == 0.0)
   {
      // Actualizar el trailing stop solo si el nuevo nivel es mayor que el nivel actual
      if (!OrderModify(ticket, 0, newStopLevel, OrderTakeProfit(), 0, 0))
      {
         Print("Error al modificar la orden. Código de error: ", GetLastError());
      }
   }
}


//+------------------------------------------------------------------+
//| Función para imprimir información de la orden de venta activa    |
//+------------------------------------------------------------------+
void PrintSellOrderInfo(int orderIndex)
  {
// Obtiene el ticket, el número mágico y el precio de ejecución de la orden
   int ticket = OrderTicket();
   int magicNumber = OrderMagicNumber();
   double executionPrice = OrderOpenPrice();
   double stopLoss = OrderStopLoss();

// Formatea el tipo de orden como "Sell"
   string orderTypeString = "Sell";

// Imprime la información de la orden en la consola de MetaTrader
   Print("Número de Ticket ", ticket, "\t\tNúmero Mágico ", magicNumber, "\t\t", orderTypeString, "\t\t\t", executionPrice, "\t\t\t", stopLoss);
  }

//+------------------------------------------------------------------+
//| Función para imprimir información de la orden de compra activa    |
//+------------------------------------------------------------------+
void PrintBuyOrderInfo(int orderIndex)
  {
// Obtiene el ticket, el número mágico y el precio de ejecución de la orden
   int ticket = OrderTicket();
   int magicNumber = OrderMagicNumber();
   double executionPrice = OrderOpenPrice();
   double stopLoss = OrderStopLoss();

// Formatea el tipo de orden como "Buy"
   string orderTypeString = "Buy";

// Imprime la información de la orden en la consola de MetaTrader
   Print("Número de Ticket ", ticket, "\t\tNúmero Mágico ", magicNumber, "\t\t", orderTypeString, "\t\t\t", executionPrice, "\t\t\t", stopLoss);
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {

  }
//+------------------------------------------------------------------+
 
Your topic has been moved to the section: MQL4 and MetaTrader 4
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
MQL5 forum: Expert Advisors and Automated Trading
MQL5 forum: Expert Advisors and Automated Trading
  • www.mql5.com
How to create an Expert Advisor (a trading robot) for Forex trading
 
Please do not write in ALLCAPS. It is considered "shouting" and rude. I have edited your post accordingly.
 
Reivaxceniceros: In the demo accounts and real accounts it works well but at the moment of placing in the strategy tester the program gets these errors I have no idea which part of my code may be causing this I ask for your help to review the code in an extensive and precise manner because I am really very desperate since it is not the data nor the meta trader that is causing the error I am sure what the error is in the code. Tralingstop works fine but in the strategy tester cause of your errors any help is welcome thank you I will read all the comments

The error message "unmatched data error" is not related to your code. It is related to the mismatch of historical data being provided to the MT4 Strategy Tester.

In other words, there is a mismatch of the data between the different time-frames.

The possible reason is that you are mixing broker provided data and data downloaded via the History Center (which downloads from MetaQuotes and not the broker).

To fix the issue, you will need to rebuild the data with the PeriodConverter program so that all the time-frames are consistent.

Please run a search in the forum to find more information about the issue and the steps to accomplish this.

 
Fernando Carreiro #:

The error message "unmatched data error" is not related to your code. It is related to the mismatch of historical data being provided to the MT4 Strategy Tester.

In other words, there is a mismatch of the data between the different time-frames.

The possible reason is that you are mixing Broker provided data and data downloaded via the History Center (which downloads from MetaQuotes and not the broker).

To fix the issue, you will need to rebuild the data with the PeriodConverter program so that all the time-frames are consistent.

Please run a search in the forum to find more information about the issue and the steps to accomplish this.

Thanks What is the periodconvert program and where can I find it?
 
Reivaxceniceros #: Thanks What is the periodconvert program and where can I find it?

"PeriodConverter.mq4" is in your "Scripts" folder, and as I stated, run a search in the forum for more information.