What is wrong?

 

Hello guys, i am not very good with mql5, but with the help of chatgpt i tried to transform a Supertrend Script from pinescript to mql5.

This is my Code:

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

//|                                                      SuperTrend.mq5|

//|                        Copyright 2024, KivancOzbilgic           |

//|                        https://www.mql5.com/en/codebase          |

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

#property strict



input int ATR_Periods = 10;             // ATR Periods

input double ATR_Multiplier = 3.0;      // ATR Multiplier

input bool Change_ATR_Method = true;    // Change ATR Calculation Method

input bool Show_Signals = false;        // Show Buy/Sell Signals

input bool Highlighting = true;         // Highlighter On/Off

input bool Bar_Coloring = true;         // Bar Coloring On/Off

input double Lots = 0.1;                // Lot Size

input int SL_Pips = 100;                // Stop Loss in Pips

input int TP_Pips = 200;                // Take Profit in Pips



double Ask, Bid;

double atr[];

double up[], dn[];

int trend[];

bool buySignal, sellSignal;

double High[];

double Low[];

double Close[];

datetime Time[];  // Deklaration des Time-Arrays



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

//| Expert initialization function                                   |

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

int OnInit()

  {

   Print("SuperTrend EA initialized.");



   ArraySetAsSeries(atr, true);

   ArraySetAsSeries(up, true);

   ArraySetAsSeries(dn, true);

   ArraySetAsSeries(trend, true);

   ArraySetAsSeries(High, true);

   ArraySetAsSeries(Low, true);

   ArraySetAsSeries(Close, true);

   ArraySetAsSeries(Time, true);  // Initialisieren als Serie



   return INIT_SUCCEEDED;

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

   Print("SuperTrend EA deinitialized. Reason: ", reason);

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

   static datetime lastTradeTime = 0;



   // Get the latest market data

   Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

   Bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);



   // Calculate the SuperTrend values

   CalculateSuperTrend();



   // Check for buy signal

   if (buySignal && Time[0] != lastTradeTime)

     {

      double lotSize = Lots;

      double sl = Ask - SL_Pips * _Point;

      double tp = Ask + TP_Pips * _Point;

      MqlTradeRequest request;

      MqlTradeResult result;

      ZeroMemory(request);

      ZeroMemory(result);

      request.action = TRADE_ACTION_DEAL;

      request.symbol = _Symbol;

      request.volume = lotSize;

      request.type = ORDER_TYPE_BUY;

      request.price = Ask;

      request.sl = sl;

      request.tp = tp;

      request.deviation = 3;

      request.magic = 0;

      request.comment = "SuperTrend Buy";

      if (OrderSend(request, result))

        {

         Print("Buy order sent successfully.");

         lastTradeTime = TimeCurrent();  // Verwendung von TimeCurrent() statt Time[0]

        }

      else

        {

         Print("Failed to send buy order. Error: ", GetLastError());

        }

     }



   // Check for sell signal

   if (sellSignal && Time[0] != lastTradeTime)

     {

      double lotSize = Lots;

      double sl = Bid + SL_Pips * _Point;

      double tp = Bid - TP_Pips * _Point;

      MqlTradeRequest request;

      MqlTradeResult result;

      ZeroMemory(request);

      ZeroMemory(result);

      request.action = TRADE_ACTION_DEAL;

      request.symbol = _Symbol;

      request.volume = lotSize;

      request.type = ORDER_TYPE_SELL;

      request.price = Bid;

      request.sl = sl;

      request.tp = tp;

      request.deviation = 3;

      request.magic = 0;

      request.comment = "SuperTrend Sell";

      if (OrderSend(request, result))

        {

         Print("Sell order sent successfully.");

         lastTradeTime = TimeCurrent();  // Verwendung von TimeCurrent() statt Time[0]

        }

      else

        {

         Print("Failed to send sell order. Error: ", GetLastError());

        }

     }

  }

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

//| Calculate SuperTrend function                                    |

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

void CalculateSuperTrend()

  {

   int bars = iBars(_Symbol, _Period);

   if (bars < ATR_Periods) 

     {

      Print("Not enough bars to calculate SuperTrend. Bars: ", bars);

      return;

     }



   ArrayResize(atr, bars);

   ArrayResize(up, bars);

   ArrayResize(dn, bars);

   ArrayResize(trend, bars);



   for (int i = bars - 1; i >= 0; i--)

     {

      double src = (High[i] + Low[i]) / 2.0;

      double atrValue;

      if (Change_ATR_Method)

        {

         atrValue = iATR(_Symbol, _Period, ATR_Periods);  // Korrigierte iATR-Funktion

        }

      else

        {

         int atr2Handle = iMA(_Symbol, _Period, ATR_Periods, 0, MODE_SMA, PRICE_MEDIAN);

         double atr2Buffer[];

         ArraySetAsSeries(atr2Buffer, true);

         CopyBuffer(atr2Handle, 0, 0, bars, atr2Buffer);

         atrValue = atr2Buffer[i];

        }

      

      atr[i] = atrValue;

      up[i] = src - (ATR_Multiplier * atr[i]);

      if (i < bars - 1) {

          up[i] = (Close[i + 1] > up[i + 1]) ? MathMax(up[i], up[i + 1]) : up[i];

      }

      dn[i] = src + (ATR_Multiplier * atr[i]);

      if (i < bars - 1) {

          dn[i] = (Close[i + 1] < dn[i + 1]) ? MathMin(dn[i], dn[i + 1]) : dn[i];

      }

      if (i < bars - 1) {

          trend[i] = trend[i + 1];

      }

      trend[i] = (trend[i] == -1 && Close[i] > dn[i + 1]) ? 1 : (trend[i] == 1 && Close[i] < up[i + 1]) ? -1 : trend[i];

     }



   if (bars > 1) {

       buySignal = (trend[0] == 1 && trend[1] == -1);

       sellSignal = (trend[0] == -1 && trend[1] == 1);

   } else {

       buySignal = false;

       sellSignal = false;

   }

   

   Print("SuperTrend calculated: buySignal=", buySignal, ", sellSignal=", sellSignal);

  }

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

The Expert Advisor should place orders for me but when used on a chart it keeps disappearing and sometimes i get an error : Array out of range. Could someone help me with this?
Files:
 

Well the error points to line:

 double src = (High[i] + Low[i]) / 2.0;

Note that the High and Low buffers are completely empty. They were not assigned to iHigh and iLow, so the compiler has no idea what to do with these. It just sees empty arrays. Use CopyHigh/CopyLow instead of iHigh or iLow

 
Laborpraktikum: but with the help of chatgpt

Stop using ChatGPT/Copilot.
          Help needed to debug and fix an AI EA - Trading Systems - MQL5 programming forum #2 (2023)

ChatGPT (the worst), “Bots Builder”, “EA builder”, “EA Builder Pro”, EATree, “Etasoft forex generator”, “Forex Strategy Builder”, ForexEAdvisor (aka. ForexEAdvisor STRATEGY BUILDER, and Online Forex Expert Advisor Generator), ForexRobotAcademy.com, forexsb, “FX EA Builder”, fxDreema, Forex Generator, FxPro, “LP-MOBI”, Molanis, “Octa-FX Meta Editor”, Strategy Builder FX, “Strategy Quant”, “Visual Trader Studio”, “MQL5 Wizard”, etc., are all the same. You will get something quick, but then you will spend a much longer time trying to get it right, than if you learned the language up front, and then just wrote it.

Since you haven't learned MQL4/5, therefor there is no common language for us to communicate. If we tell you what you need, you can't code it. If we give you the code, you don't know how to integrate it into yours.

We are willing to HELP you when you post your attempt (using Code button) and state the nature of your problem, but we are not going to debug your hundreds of lines of code. You are essentially going to be on your own.

ChatGPT
  1. Even it says do not use it for coding. * 
  2. Mixing MT4 and MT5 code together.
  3. Creating multiple OnCalculate/OnTick functions.
  4. OnCalculate returning a double.
  5. Filling buffers with zero in OnInit (they have no size yet). Setting buffer elements to zero but not setting Empty Value to correspond.
  6. Calling undefined functions.
  7. Calling MT4 functions in MT5 code.
  8. Sometimes, not using strict (MT4 code).
  9. Code that will not compile.
  10. Creating code outside of functions. * 
  11. Creating incomplete code. * 
  12. Initialization of Global variables with non-constants. * 
  13. Assigning a MT5 handle to a double or missing the buffer and bar indexes in a MT4 call. * 
  14. Useing MT4 Trade Functions without first selecting an order. * 
  15. Uses NULL in OrderSend. * 
bot builder Creating two OnInit() functions. * 
EA builder
  1. Counting up while closing multiple orders.
  2. Not useing time in new bar detection.
  3. Not adjusting for 4/5 digit brokers, TP/SL and slippage. * 
  4. Not checking return codes.
EATree Uses objects on chart to save values — not persistent storage (files or GV+Flush.) No recovery (crash/power failure.)
ForexEAdvisor
  1. Non-updateing global variables.
  2. Compilation errors.
  3. Not checking return codes.
  4. Not reporting errors.
FX EA Builder
  1. Not checking return codes.
  2. Loosing open tickets on terminal restart. No recovery (crash/power failure.)
  3. Not adjusting stops for the spread. * 
  4. Using OrdersTotal directly.
  5. Using the old event handlers.
 

AI won't get you there. It was unholy the amount of changes needed to be made to this script 

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

//|                                                      SuperTrend.mq5|

//|                        Copyright 2024, KivancOzbilgic           |

//|                        https://www.mql5.com/en/codebase&amp;amp;nbsp;         |

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

#property strict


//input int bars = 1000;

input int ATR_Periods = 10;             // ATR Periods

input double ATR_Multiplier = 3.0;      // ATR Multiplier

input bool Change_ATR_Method = true;    // Change ATR Calculation Method

input bool Show_Signals = false;        // Show Buy/Sell Signals

input bool Highlighting = true;         // Highlighter On/Off

input bool Bar_Coloring = true;         // Bar Coloring On/Off

input double Lots = 0.1;                // Lot Size

input int SL_Pips = 100;                // Stop Loss in Pips

input int TP_Pips = 200;                // Take Profit in Pips


/**

...right click a symbol on Market Watch window...click Specification...see what the broker is using for Filling


**/
input ENUM_ORDER_TYPE_FILLING BROKER_FILLING_TYPE = ORDER_FILLING_IOC; // Broker Filling Type

int bars;

double Ask, Bid;

double atr[];  double atr2Buffer[];

double up[], dn[];

int trend[];

bool buySignal, sellSignal;

double High[];

double Low[];

double Close[];

datetime Time[];  // Deklaration des Time-Arrays

double atrValue;

int atrHandle = INVALID_HANDLE;
int atr2Handle = INVALID_HANDLE;
//+------------------------------------------------------------------+

//| Expert initialization function                                   |

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

int OnInit()

  {

   Print("SuperTrend EA initialized.");

   // put the handle shit here
   
   atrHandle = iATR(_Symbol, _Period, ATR_Periods);  // Korrigierte iATR-Funktion
   
   atr2Handle = iMA(_Symbol, _Period, ATR_Periods, 0, MODE_SMA, PRICE_MEDIAN);
   
   ArraySetAsSeries(atr, true);
   
   ArraySetAsSeries(atr2Buffer, true);

   ArraySetAsSeries(up, true);

   ArraySetAsSeries(dn, true);

   ArraySetAsSeries(trend, true);

   ArraySetAsSeries(High, true);

   ArraySetAsSeries(Low, true);

   ArraySetAsSeries(Close, true);

   ArraySetAsSeries(Time, true);  // Initialisieren als Series
   
   //bars = iBars(_Symbol, _Period); // you don't need to use all available bars...this is too much and not necessary to use all the historic bars. It will slow down the EA in backtesting.
   
    bars = 1000; 
   // resize the shit here in OnInit
   
   ArrayResize(atr, bars);
   
   ArrayResize(atr2Buffer, bars);

   ArrayResize(up, bars);

   ArrayResize(dn, bars);

   ArrayResize(trend, bars);

   ArrayResize(High, bars);
   
   ArrayResize(Low, bars);
   
   ArrayResize(Close, bars);
   
   ArrayResize(Time, bars);

   ArrayResize(trend, bars);

   return INIT_SUCCEEDED;

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

   Print("SuperTrend EA deinitialized. Reason: ", reason);

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

   static datetime lastTradeTime = 0;
   
   
   Time[0] = iTime(_Symbol, _Period, 0);


   // Get the latest market data

   Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

   Bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);



   // Calculate the SuperTrend values

   CalculateSuperTrend();



   // Check for buy signal

   if (buySignal && PositionsTotal()==0)

     {

      double lotSize = Lots;

      double sl = Ask - SL_Pips * _Point;

      double tp = Ask + TP_Pips * _Point;

      MqlTradeRequest request;

      MqlTradeResult result;

      ZeroMemory(request);

      ZeroMemory(result);

      request.action = TRADE_ACTION_DEAL;

      request.symbol = _Symbol;

      request.volume = lotSize;

      request.type = ORDER_TYPE_BUY;
      
      request.type_filling = BROKER_FILLING_TYPE;

      request.price = Ask;

      if (sl >= 0) {
      
         request.sl = NormalizeDouble(sl, _Digits);
     
      }
      
      if (tp >= 0) {
      
         request.tp = NormalizeDouble(tp, _Digits);

      }

      request.deviation = 3;

      request.magic = 0;

      request.comment = "SuperTrend Buy";

      if (OrderSend(request, result))

        {

         Print("Sell order sent successfully.");

         lastTradeTime = TimeCurrent();  // Verwendung von TimeCurrent() statt Time[0]

        }

      else

        {

         Print("Failed to send sell order. Error: ", GetLastError());

        }

     }



   // Check for sell signal

   if (sellSignal && PositionsTotal()==0)

     {

      double lotSize = Lots;

      double sl = Bid + SL_Pips * _Point;

      double tp = Bid - TP_Pips * _Point;

      MqlTradeRequest request;

      MqlTradeResult result;

      ZeroMemory(request);

      ZeroMemory(result);

      request.action = TRADE_ACTION_DEAL;

      request.symbol = _Symbol;

      request.volume = lotSize;

      request.type = ORDER_TYPE_SELL;
      
      request.type_filling = BROKER_FILLING_TYPE;

      request.price = Bid;

      if (sl >= 0) {

        request.sl = NormalizeDouble(sl, _Digits);      
      }
      
      if (tp >= 0) {

        request.tp =  NormalizeDouble(tp, _Digits);
      }

      request.deviation = 3;

      request.magic = 0;

      request.comment = "SuperTrend Sell";

      if (OrderSend(request, result))

        {

         Print("Sell order sent successfully.");

         lastTradeTime = TimeCurrent();  // Verwendung von TimeCurrent() statt Time[0]

        }

      else

        {

         Print("Failed to send sell order. Error: ", GetLastError());

        }

     }
     
  }

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

//| Calculate SuperTrend function                                    |

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

void CalculateSuperTrend()

  {

   if (bars < ATR_Periods) 

     {

      Print("Not enough bars to calculate SuperTrend. Bars: ", bars);

      return;
     }

   CopyHigh(_Symbol, _Period, 0, bars, High);
   CopyLow(_Symbol, _Period, 0, bars, Low);
   CopyClose(_Symbol, _Period, 0, bars, Close);


   if (CopyBuffer(atrHandle, 0, 0, bars, atr) == -1) {
     Print("Problem encountered loading ATR values");
   }   
   
   if (CopyBuffer(atr2Handle, 0, 0, bars, atr2Buffer) == -1) {
     Print("Problem encountered loading MA values");
   } 
      
   for (int i = bars-1; i >= 0; i--)
     {
     
     // Print("debug high[i]", High[i]);
     // Print("debug low[i]", Low[i]);       

      double src = (High[i] + Low[i]) / 2.0;

      if (Change_ATR_Method)
        {   
             atrValue = atr[i];
        }

      else
        {
             atrValue = atr2Buffer[i];
        }


      up[i] = src - (ATR_Multiplier * atr[i]);

      if (i < bars - 1) {

          up[i] = (Close[i + 1] > up[i + 1]) ? MathMax(up[i], up[i + 1]) : up[i];

      }

      dn[i] = src + (ATR_Multiplier * atr[i]);

      if (i < bars - 1) {

          dn[i] = (Close[i + 1] < dn[i + 1]) ? MathMin(dn[i], dn[i + 1]) : dn[i];

      }

      if (i < bars - 1) {

          trend[i] = trend[i+1];

      }

     if(i+1 < bars) trend[i] = (Close[i] > dn[i + 1]) ? 1 : (Close[i] < up[i + 1]) ? -1 : trend[i];
      
         
         if (bars > 1) {
         
          buySignal = (trend[i] == 1);
         
          sellSignal = (trend[i] == -1);
         
         } else {
         
          buySignal = false;
         
          sellSignal = false;
         }  

        //Print("debug i=", i, " High=", High[i], " Low=", Low[i], " Close=", Close[i]);
        //Print("debug atr[", i, "]=", atr[i], " atr2Buffer[", i, "]=", atr2Buffer[i]);
        //Print("debug up[", i, "]=", up[i], " dn[", i, "]=", dn[i]);
        //Print("debug trend[", i, "]=", trend[i]);
     }


  // Print("SuperTrend calculated: buySignal=", buySignal, ", sellSignal=", sellSignal);
  }
 
      double sl = Ask - SL_Pips * _Point;

      double tp = Ask + TP_Pips * _Point;

You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

  1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

  2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
              MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

  3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

    Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
    My GBPJPY shows average spread = 26 points, average maximum spread = 134.
    My EURCHF shows average spread = 18 points, average maximum spread = 106.
    (your broker will be similar).
              Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

 
William Roeder #:

You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

  1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

  2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
              MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

  3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

    Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
    My GBPJPY shows average spread = 26 points, average maximum spread = 134.
    My EURCHF shows average spread = 18 points, average maximum spread = 106.
    (your broker will be similar).
              Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

In MT5, the instantly executed orders are actually named 

ORDER_TYPE_BUY

and

ORDER_TYPE_SELL


They are not pending orders even though they seem like they are.

The pending orders are:

ORDER_TYPE_BUY_STOP 
ORDER_TYPE_SELL_STOP
ORDER_TYPE_BUY_LIMIT
ORDER_TYPE_SELL_LIMIT


This naming convention was confusing, and nowadays most people rather use the cTrade library.


William Roeder #:

My GBPJPY shows average spread = 26 points, average maximum spread = 134.

My EURCHF shows average spread = 18 points, average maximum spread = 106.

Holy crap boss, that is a big spread. I would be suspicious of this broker

 
  1. Conor Mcnamara #:

    In MT5, the instantly executed orders are actually named 

    and

    They are not pending orders even though they seem like they are.

    The pending orders are:

    This naming convention was confusing, and nowadays most people rather use the cTrade library.


    So what? Nothing in my previous post has to do with market orders vs. pending orders. What part of “SL shorter and your TP longer” was unclear?

  2. Conor Mcnamara #: Holy crap boss, that is a big spread. I would be suspicious of this broker

    One of the largest brokers in the world. It is you that doesn't understand.

 

William Roeder #

So what? Nothing in my previous post has to do with market orders vs. pending orders. What part of “SL shorter and your TP longer” was unclear?

You were talking about pending orders, and his EA does not do them. No need to add confusion, pending orders is offtopic.

 
 It is you that doesn't understand.

I'm pretty certain I don't want to either. I would not trade on highly volatile session times.

 
Conor Mcnamara #: You were talking about pending orders, and his EA does not do them. No need to add confusion, pending orders is offtopic.

No, I was not. I was talking about when orders open. You have added the confusion.