Can someone help me check this EA code to see if there are any errors and also I need help to optimize it. Just a newcomer here

 
// Define input parameters
input int fastEMA = 20;                 // Fast Exponential Moving Average period
input int slowSMA = 55;                 // Slow Simple Moving Average period
input int macdFast = 10;                // MACD Fast EMA period
input int macdSlow = 50;                // MACD Slow EMA period
input int macdSignal = 5;               // MACD Signal SMA period
input double lotSize = 0.1;             // Trading lot size
input double maxStopLossPips = 100;     // Maximum allowed stop loss in pips
 
// Define global variables
double emaFastCurrent, emaFastPrevious, emaSlowCurrent, emaSlowPrevious;
double previousLow, previousHigh;
 
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    emaFastPrevious = iMA(Symbol(), Period(), fastEMA, 0, MODE_EMA, PRICE_CLOSE, 1);
    emaSlowPrevious = iMA(Symbol(), Period(), slowSMA, 0, MODE_SMA, PRICE_CLOSE, 1);
    return(INIT_SUCCEEDED);
}
 
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // You can perform cleanup tasks here if needed
}
 
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    // Calculate EMA values
    emaFastCurrent = iMA(Symbol(), Period(), fastEMA, 0, MODE_EMA, PRICE_CLOSE, 0);
    emaSlowCurrent = iMA(Symbol(), Period(), slowSMA, 0, MODE_SMA, PRICE_CLOSE, 0);
 
    // Calculate the previous low and high
    previousLow = iLow(Symbol(), Period(), 1); // Get the previous low
    previousHigh = iHigh(Symbol(), Period(), 1); // Get the previous high
 
    ulong ticket; // Declare the 'ticket' variable here
 
    // Check for open positions
    if (PositionsTotal() > 0)
    {
        for (int i = 0; i < PositionsTotal(); i++)
        {
            ticket = PositionGetTicket(i); // Assign the 'ticket' variable here
            if (ticket > 0)
            {
                // Check for open buy trade and fast EMA crossing below slow SMA
                if (PositionGetInteger(POSITION_TYPE, ticket) == POSITION_BUY && emaFastPrevious < emaSlowPrevious && emaFastCurrent > emaSlowCurrent)
                {
                    PositionClose(ticket);
                }
                // Check for open sell trade and fast EMA crossing above slow SMA
                else if (PositionGetInteger(POSITION_TYPE, ticket) == POSITION_SELL && emaFastPrevious > emaSlowPrevious && emaFastCurrent < emaSlowCurrent)
                {
                    PositionClose(ticket);
                }
            }
        }
    }
 
    // Check for selling condition
    if (emaFastPrevious > emaSlowPrevious && emaFastCurrent < emaSlowCurrent)
    {
        // MACD condition - MACD is below the signal line
        int macdResult = iMACD(Symbol(), Period(), macdFast, macdSlow, macdSignal, PRICE_CLOSE);
        if (macdResult == 1)
        {
            SellSignal();
        }
    }
    // Check for buying condition
    else if (emaFastPrevious < emaSlowPrevious && emaFastCurrent > emaSlowCurrent)
    {
        // MACD condition - MACD is above the signal line
        int macdResult = iMACD(Symbol(), Period(), macdFast, macdSlow, macdSignal, PRICE_CLOSE);
        if (macdResult == -1)
        {
            BuySignal();
        }
    }
 
    // Update previous values for the next tick
    emaFastPrevious = emaFastCurrent;
    emaSlowPrevious = emaSlowCurrent;
}
 
// Function to handle sell signal
void SellSignal()
{
    double openPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double stopLoss = MathMin(previousHigh, openPrice + maxStopLossPips * SymbolInfoDouble(_Symbol, SYMBOL_POINT)); // Limit stop loss to maximum
    double takeProfit = previousLow;

    ulong ticket = OrderSend(Symbol(), OP_SELL, lotSize, openPrice, 2, 0, stopLoss, takeProfit, 0, clrNONE);
    if (ticket > 0)
    {
        Print("Sell order placed successfully. Ticket: ", ticket);
    }
    else
    {
        Print("Error placing sell order. Error code: ", GetLastError());
    }
}
 
// Function to handle buy signal
void BuySignal()
{
    double openPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double stopLoss = MathMax(previousLow, openPrice - maxStopLossPips * SymbolInfoDouble(_Symbol, SYMBOL_POINT)); // Limit stop loss to minimum
    double takeProfit = previousHigh;
 
    ulong ticket = OrderSend(Symbol(), OP_BUY, lotSize, openPrice, 2, 0, stopLoss, takeProfit, 0, clrNONE);
    if (ticket > 0)
    {
        Print("Buy order placed successfully. Ticket: ", ticket);
    }
    else
    {
        Print("Error placing buy order. Error code: ", GetLastError());
    }
}
 
REIM48: "
Can someone help me check this EA code to see if there are any errors and also I need help to optimize it. Just a newcomer here

Why?

You want to trade two ema, if you would have googled for "site:mql5.com EA two ema" yopu would have found e.g. this: https://www.mql5.com/en/forum/20297#comment_763463

Or searching here: https://www.mql5.com/en/search#!keyword=two%20ema you can find lots of working examples.

Bear in mind there's virtually nothing that hasn't already been programmed for MT4/MT5 and is ready for you!

    If you place the cursor on an MQL function and press F1, you will see the reference directly, many with examples to copy and paste - the fastest form to code.
    https://www.mql5.com/en/articles/496
    https://www.mql5.com/en/articles/100
    https://www.mql5.com/en/articles/599
    and for debugging: https://www.metatrader5.com/en/metaeditor/help/development/debug
    https://www.mql5.com/en/search#!keyword=cookbook
    => Search in the articles: https://www.mql5.com/en/articles
    => Search in the codebase: https://www.mql5.com/en/code
    => Search in general: https://www.mql5.com/en/search or via Google with: "site:mql5.com .." (forgives misspelling)
    indicators: see this series of articles:
    https://www.mql5.com/en/users/m.aboud/publications
    Each article explains an indicator (built into MT5) and what it tells you, and how you might use it in an EA.

Two EMA's crossing
Two EMA's crossing
  • 2014.02.12
  • www.mql5.com
Hey guys, okay? I'm developing an EA, and as I'm noob, I don't know much about programming, I'm missing a lot...
 
Didn't expect a helpful advice, but here it is. Thanks man
 
  1. Stop using ChatGPT.
              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, 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.

  2.     ulong ticket = OrderSend(Symbol(), OP_BUY, lotSize, openPrice, 2, 0, stopLoss, takeProfit, 0, clrNONE);
    

    This is MT4 code.


  3.     if (PositionsTotal() > 0)
        {
            for (int i = 0; i < PositionsTotal(); i++)
            {
    
    MT4 does not have positions.
 

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/443428#comment_49114884

 
REIM48:

Everyone else is going to tell you not to use ChatGPT. I'll offer some suggestions about how to use ChatGPT.

  1. It constantly makes the mistake of using the built-in functions (iMA, etc.) to directly produce the values, when what they actually return is a handle to retrieve the values. Tell ChatGPT this and it'll fix it:

    iMA returns handles. You'll need to use those handles to copy the buffers every new candle.

  2. It will then try to use something like emaFast[0], but note that that is being calculated on the currently forming candle. You need to use emaFast[1] to get the calculation on the last close candle. Again, tell this to ChatGPT and it'll fix it.
  3. ChatGPT does an absolutely terrible job if you copy/paste all the errors to it at once — it doesn't know how to sort them all out. Go line by line, and it does a pretty good job. A lot of the errors will be that it used MT4 syntax instead of MT5. This can be very frustrating to keep having the same errors over and over.

ChatGPT does make a lot of mistakes and does write some pretty bad code. But as you learn to work with it, you can get functional code. It's also pretty decent at making small modifications to existing working code. Even though I've gotten to where I can do things myself, I still use ChatGPT a fair amount because it's simply faster than I am... but not when you have to spend an hour getting it to correct itself.

 
Scott Allen #:
Everyone else is going to tell you not to use ChatGPT. I'll offer some suggestions about how to use ChatGPT.

Everything is very simple. In order to fix the code generated by chatgpt, you must be able to program. If you know how to program, then you simply do not need chatgpt.

Reason: