Simple Indicator

 
Hello I am trying to build a simple Indicator. It should display arrows when the price crosses the previous day's high, low or closing price levels, and a check symbol (position entry signal) when the next candle closes above the previous candle.

P. S. I m a beginner.

I get 27 errors. Can someone help me please?



 //+------------------------------------------------------------------+
//|                         MyStrategy.mq5                                |
//|                                                                                 |
//|                        Date: 2024-08-07                               |
//+------------------------------------------------------------------+
#property copyright "Ayva"
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1 Blue   // For Previous High
#property indicator_color2 Red    // For Previous Low
#property indicator_color3 Green  // For Previous Close

//--- indicator buffers
double PrevHighBuffer[];
double PrevLowBuffer[];
double PrevCloseBuffer[];

//--- input parameters
input int periodHighLowClose = 20; // Period for calculating high, low, close
input int alertDistance = 10; // Distance in points for alert

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Indicator buffers
   SetIndexBuffer(0, PrevHighBuffer);
   SetIndexBuffer(1, PrevLowBuffer);
   SetIndexBuffer(2, PrevCloseBuffer);
   
   // Set indicator name
   IndicatorShortName("Previous High/Low/Close Levels");

   // Set index styles
   SetIndexStyle(0, DRAW_LINE);
   SetIndexStyle(1, DRAW_LINE);
   SetIndexStyle(2, DRAW_LINE);
   
   // Set index widths
   SetIndexWidth(0, 1);
   SetIndexWidth(1, 1);
   SetIndexWidth(2, 1);

   // Initialization done
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const long &spread[])
  {
   // Ensure enough bars to calculate
   if (rates_total < periodHighLowClose)
      return 0;

   // Calculate Previous High, Low, and Close
   int start = periodHighLowClose;
   if (prev_calculated == 0)
     {
      start = periodHighLowClose; // Initialize start index on first run
     }
   else
     {
      start = prev_calculated - 1; // Continue from last calculation
     }

   for (int i = start; i < rates_total; i++)
     {
      int highestBar = iHighest(NULL, 0, MODE_HIGH, periodHighLowClose, i);
      int lowestBar = iLowest(NULL, 0, MODE_LOW, periodHighLowClose, i);

      PrevHighBuffer[i] = iHigh(NULL, 0, highestBar);
      PrevLowBuffer[i] = iLow(NULL, 0, lowestBar);
      PrevCloseBuffer[i] = iClose(NULL, 0, i - periodHighLowClose + 1);
     }
   
   // Alert conditions
   for (int i = rates_total - 1; i >= 0; i--)
     {
      if (MathAbs(close[i] - PrevHighBuffer[i]) < alertDistance * _Point ||
          MathAbs(close[i] - PrevLowBuffer[i]) < alertDistance * _Point ||
          MathAbs(close[i] - PrevCloseBuffer[i]) < alertDistance * _Point)
        {
         Alert("Price is close to a significant level.");
         break;
        }
     }
   
   return(rates_total);
  }
//+------------------------------------------------------------------+
 

please edit your post - 

When you post code please use the CODE button (Alt-S)!

Use the CODE button

 
  1. Please edit your (original) post and use the CODE button (or Alt+S)! (For large amounts of code, attach it.)
          General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
              Messages Editor
          Forum rules and recommendations - General - MQL5 programming forum (2023)

  2. ayvaniniyisi: I get 27 errors. Can someone help me please?d

    Help you with what? You haven't stated a single problem. Fix one, recompile, repeat.

 
I have now a better version. But still have 6 errors. I dont know how to solve this.


#include <Trade\Trade.mqh>

input int stopLoss = 100; // Stop Loss in points
input int takeProfit = 200; // Take Profit in points

CTrade trade; // Create an instance of the CTrade class

#define POSITION_PRICE 1 // Define POSITION_PRICE constant

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    static double prevHigh = 0;
    static double prevLow = 0;
    static double prevClose = 0;

    double currentHigh = iHigh(Symbol(), 0, 1);
    double currentLow = iLow(Symbol(), 0, 1);
    double currentClose = iClose(Symbol(), 0, 1);

    double point = SymbolInfoDouble(Symbol(), SYMBOL_POINT);

    double positionPrice = trade.PositionGetDouble(POSITION_PRICE);

    if (currentHigh > prevHigh)
    {
        // Buy signal
        if (trade.Buy(0.1))
        {
            trade.PositionModify(positionPrice - stopLoss *point, positionPrice + takeProfit* point);
        }
    }
    else if (currentLow < prevLow)
    {
        // Sell signal
        if (trade.Sell(0.1))
        {
            trade.PositionModify(positionPrice + stopLoss *point, positionPrice - takeProfit* point);
        }
    }
    else if (currentClose > prevClose)
    {
        // Buy signal
        if (trade.Buy(0.1))
        {
            trade.PositionModify(positionPrice - stopLoss *point, positionPrice + takeProfit* point);
        }
    }
    else if (currentClose < prevClose)
    {
        // Sell signal
        if (trade.Sell(0.1))
        {
            trade.PositionModify(positionPrice + stopLoss *point, positionPrice - takeProfit* point);
        }
    }

    prevHigh = currentHigh;
    prevLow = currentLow;
    prevClose = currentClose;
}

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

Errors:

'PositionGetDouble' - undeclared identifier My Strategy.mq5 33 34

'1' - some operator expected My Strategy.mq5 33 52

'PositionModify' - no one of the overloads can be applied to the function call My Strategy.mq5 40 19
could be one of 2 function(s) My Strategy.mq5 40 19
   bool CTrade::PositionModify(const string,const double,const double) Trade.mqh 99 22
   bool CTrade::PositionModify(const ulong,const double,const double) Trade.mqh 100 22


'PositionModify' - no one of the overloads can be applied to the function call My Strategy.mq5 48 19
could be one of 2 function(s) My Strategy.mq5 48 19

   bool CTrade::PositionModify(const string,const double,const double) Trade.mqh 99 22

   bool CTrade::PositionModify(const ulong,const double,const double) Trade.mqh 100 22


'PositionModify' - no one of the overloads can be applied to the function call My Strategy.mq5 56 19
could be one of 2 function(s) My Strategy.mq5 56 19
   bool CTrade::PositionModify(const string,const double,const double) Trade.mqh 99 22
   bool CTrade::PositionModify(const ulong,const double,const double) Trade.mqh 100 22

'PositionModify' - no one of the overloads can be applied to the function call My Strategy.mq5 64 19
could be one of 2 function(s) My Strategy.mq5 64 19
   bool CTrade::PositionModify(const string,const double,const double) Trade.mqh 99 22
   bool CTrade::PositionModify(const ulong,const double,const double) Trade.mqh 100 22




 

Ok- I have only 2 errors left.

(Note: I have created this with two different AI's.)

Errors:

'ORDER_BUY' - undeclared identifier My Strategy.mq5 43 28

possible loss of data due to type conversion from 'double' to 'ulong' My Strategy.mq5 47 31

'ORDER_SELL' - undeclared identifier My Strategy.mq5 69 28

possible loss of data due to type conversion from 'double' to 'ulong' My Strategy.mq5 73 31


#include <Trade\Trade.mqh>

input int stopLoss = 100; // Stop Loss in points
input int takeProfit = 200; // Take Profit in points

CTrade trade; // Create an instance of the CTrade class

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    static double prevHigh = 0;
    static double prevLow = 0;
    static double prevClose = 0;

    double currentHigh = iHigh(Symbol(), 0, 1);
    double currentLow = iLow(Symbol(), 0, 1);
    double currentClose = iClose(Symbol(), 0, 1);

    double point = SymbolInfoDouble(Symbol(), SYMBOL_POINT);
    double slippage = 3;

    MqlTradeRequest request = {};
    MqlTradeResult result = {};

    // Buy Order Request
    if (currentHigh > prevHigh)
    {
        if (PositionSelect(Symbol()) == false) // Check if there's no open position
        {
            request.action = TRADE_ACTION_DEAL;
            request.symbol = Symbol();
            request.volume = 0.1;
            request.type = ORDER_BUY;
            request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID);
            request.sl = request.price - stopLoss * point;
            request.tp = request.price + takeProfit * point;
            request.deviation = slippage;
            request.type_filling = ORDER_FILLING_FOK;
            request.type_time = ORDER_TIME_GTC;

            if (OrderSend(request, result))
            {
                Print("Buy order placed successfully.");
            }
            else
            {
                Print("Buy order failed. Error: ", GetLastError());
            }
        }
    }
    // Sell Order Request
    else if (currentLow < prevLow)
    {
        if (PositionSelect(Symbol()) == false) // Check if there's no open position
        {
            request.action = TRADE_ACTION_DEAL;
            request.symbol = Symbol();
            request.volume = 0.1;
            request.type = ORDER_SELL;
            request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
            request.sl = request.price + stopLoss * point;
            request.tp = request.price - takeProfit * point;
            request.deviation = slippage;
            request.type_filling = ORDER_FILLING_FOK;
            request.type_time = ORDER_TIME_GTC;

            if (OrderSend(request, result))
            {
                Print("Sell order placed successfully.");
            }
            else
            {
                Print("Sell order failed. Error: ", GetLastError());
            }
        }
    }

    prevHigh = currentHigh;
    prevLow = currentLow;
    prevClose = currentClose;
}
 
ayvaniniyisi #: (Note: I have created this with two different AI's.)


'ORDER_BUY' - undeclared identifier My Strategy.mq5 43 28

'ORDER_SELL' - undeclared identifier My Strategy.mq5 69 28

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.
 
William Roeder #:

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.

You are absolutely right. After I made my post, that is exactly what was going through my head.

But I don't know exactly where to start learning MQL5. And just thinking about it is overwhelming. That doesn't mean that I am not willing to learn. I am certainly open to learning new things. As I said, I don't really know where to start.

Should I learn small blocks of code first? I don't know what all the OnInit etc. mean. ://

Also, if you gave me the corrected parts of the code, it would always hurt me because I don't know what it means and how to really deal with it. (The hurt comes from the fact that I am inquisitive and curious, and in this case I don't know what I'm dealing with.)


Thank you for your detailed answer earlier.

 
ayvaniniyisi #: But I don't know exactly where to start learning MQL5.
MT5: Begin learning to code it.

If you don't learn MQL4/5, 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 your code.
          I need HEEEELP, please, it's URGENT...really ! - General - MQL5 programming forum (2017)

 
ayvaniniyisi #:

You are absolutely right. After I made my post, that is exactly what was going through my head.

But I don't know exactly where to start learning MQL5. And just thinking about it is overwhelming. That doesn't mean that I am not willing to learn. I am certainly open to learning new things. As I said, I don't really know where to start.

Should I learn small blocks of code first? I don't know what all the OnInit etc. mean. ://

Also, if you gave me the corrected parts of the code, it would always hurt me because I don't know what it means and how to really deal with it. (The hurt comes from the fact that I am inquisitive and curious, and in this case I don't know what I'm dealing with.)


Thank you for your detailed answer earlier.


There are good articles here. I learned things by going through the codebase, but going through an article sounds like the most reasonable approach to learning.

https://www.mql5.com/en/articles/15299


What AI is giving you is the non streamlined headache way of creating what you want to create. The article I just linked discusses the streamlined way of making buy and sell positions without the need to use the Request structure.

Introduction to MQL5 (Part 8): Beginner's Guide to Building Expert Advisors (II)
Introduction to MQL5 (Part 8): Beginner's Guide to Building Expert Advisors (II)
  • www.mql5.com
This article addresses common beginner questions from MQL5 forums and demonstrates practical solutions. Learn to perform essential tasks like buying and selling, obtaining candlestick prices, and managing automated trading aspects such as trade limits, trading periods, and profit/loss thresholds. Get step-by-step guidance to enhance your understanding and implementation of these concepts in MQL5.
 
Conor Mcnamara #:


There are good articles here. I learned things by going through the codebase, but going through an article sounds like the most reasonable approach to learning.

https://www.mql5.com/en/articles/15299


What AI is giving you is the non streamlined headache way of creating what you want to create. The article I just linked discusses the streamlined way of making buy and sell positions without the need to use the Request structure.

thank you.