Meta Trader 4 & 5 Code not working properly and not opening Buy Sel Trade

 

I have this MQL4 code: Which I generated using ChatGPT and then read resources and help groups online and fixed the errors

Now It's giving 0 errors and 0 warnings, but still not working as expected


Here is MQL4 code:

//+------------------------------------------------------------------+
//|                                          BollingerBandsBot.mq4    |
//|                        Copyright 2024, YourName                  |
//+------------------------------------------------------------------+
input double LotSize = 0.1; // Trade Size
input int BBPeriod = 20; // Bollinger Band Period
input double BBDeviation = 2.0; // Bollinger Band Deviation
input int StopLoss = 100; // Stop Loss (in pips)
input int TakeProfit = 200; // Take Profit (in pips)

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

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    double upperBand = iBands(NULL, 0, BBPeriod, BBDeviation, 0, PRICE_CLOSE, 0);
    double lowerBand = iBands(NULL, 0, BBPeriod, BBDeviation, 0, PRICE_CLOSE, 1);
    double currentPrice = Close[0];

// Open a buy trade when the lower limit is broken
    if (currentPrice < lowerBand)
    {
        double stopLoss = currentPrice - StopLoss * Point;
        double takeProfit = currentPrice + TakeProfit * Point;

        OrderSend(Symbol(), OP_BUY, LotSize, currentPrice, 3, stopLoss, takeProfit, "Buy Order", 0, 0, clrGreen);
    }

    // Open a sell trade when the upper limit is broken
    if (currentPrice > upperBand)
    {
        double stopLoss = currentPrice + StopLoss * Point;
        double takeProfit = currentPrice - TakeProfit * Point;

        OrderSend(Symbol(), OP_SELL, LotSize, currentPrice, 3, stopLoss, takeProfit, "Sell Order", 0, 0, clrRed);
    }
}

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

And here is MQL5 Code for same Robot

//+------------------------------------------------------------------+
//|                                          BollingerBandsBot.mq5    |
//|                        Copyright 2024, YourName                  |
//+------------------------------------------------------------------+
input double LotSize = 0.1; // Trade Size
input int BBPeriod = 20; // Bollinger Band Period
input double BBDeviation = 2.0; // Bollinger Band Deviation
input int StopLoss = 100; // Stop Loss (in pips)
input int TakeProfit = 200; // Take Profit (in pips)

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

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    double upperBand =iBands(_Symbol, PERIOD_CURRENT, 20, 2, 0.0, PRICE_HIGH);

    double lowerBand = iBands(_Symbol, PERIOD_CURRENT, 20, 2, 0.0, PRICE_LOW);
    double currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Get current bid price

// Open a buy trade when the lower limit is broken
    if (currentPrice < lowerBand)
    {
        double stopLoss = currentPrice - StopLoss * _Point;
        double takeProfit = currentPrice + TakeProfit * _Point;

        // Create a buy order
        MqlTradeRequest request;
        MqlTradeResult result;
        
        request.action = TRADE_ACTION_DEAL; // Change this line
        request.symbol = Symbol();
        request.volume = LotSize;
        request.type     =ORDER_TYPE_BUY; // Use ORDER_BUY
        request.price = currentPrice;
        request.sl = stopLoss;
        request.tp = takeProfit;
        request.magic = 0;
        request.deviation = 0;

        if (!OrderSend(request, result))
        {
            Print("Error opening buy order: ", GetLastError());
        }
    }

    // Open a sell trade when the upper limit is broken
    if (currentPrice > upperBand)
    {
        double stopLoss = currentPrice + StopLoss * _Point;
        double takeProfit = currentPrice - TakeProfit * _Point;

        // Create a sell order
        MqlTradeRequest request;
        MqlTradeResult result;
        
        request.action = TRADE_ACTION_DEAL; // Change this line
        request.symbol = Symbol();
        request.volume = LotSize;
        request.type     =ORDER_TYPE_SELL; // Use ORDER_SELL
        request.price = currentPrice;
        request.sl = stopLoss;
        request.tp = takeProfit;
        request.magic = 0;
        request.deviation = 0;

        if (!OrderSend(request, result))
        {
            Print("Error opening sell order: ", GetLastError());
        }
    }
}

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

Please help

Thank you

 
  1. PFX Trader: I have this MQL4 code: Which I generated using 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 (MT4). * 
    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. input int StopLoss = 100; // Stop Loss (in pips)
    ⋮
            double stopLoss = currentPrice - StopLoss * _Point;

    PIP, Point, or Tick size are all different in general.
              Ticks, PIPs or points in the GUI. Make up your mind. - MQL4 programming forum #1 (2014)
              Percentage in point - Wikipedia

    Unless you manually adjust your SL/TP for each separate symbol, using Point means code breaks on 4 digit brokers (if any still exists), exotics (e.g. USDZAR where spread is over 500 points), and metals. Compute what a logical PIP is and use that, not points.
              How to manage JPY pairs with parameters? - MQL4 programming forum (2017)
              Slippage defined in index points - Expert Advisors and Automated Trading - MQL5 programming forum (2018)

  3.         double stopLoss   = currentPrice - StopLoss * Point;
            double takeProfit = currentPrice + TakeProfit * 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. Prices (open, SL, and TP) must be a multiple of ticksize. Using Point means code breaks on 4 digit brokers (if any still exists), exotics (e.g. USDZAR where spread is over 500 points), and metals. Compute what a logical PIP is and use that, not points.
                How to manage JPY pairs with parameters? - MQL4 programming forum (2017)
                Slippage defined in index points - Expert Advisors and Automated Trading - MQL5 programming forum (2018)

    4. 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)

  4.     double currentPrice = Close[0];
    ⋮
            OrderSend(Symbol(), OP_BUY, LotSize, currentPrice, 3, stopLoss, takeProfit, "Buy Order", 0, 0, clrGreen);

    You buy at the Ask. See № 3.

  5. Check your return codes, and report your errors (including market prices and your variables). Don't look at GLE/LE unless you have an error. Don't just silence the compiler (MT5 / MT4+strict), it is trying to help you.
              What are Function return values ? How do I use them ? - MQL4 programming forum (2012)
              Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles (2014)

  6.     double upperBand =iBands(_Symbol, PERIOD_CURRENT, 20, 2, 0.0, PRICE_HIGH);
    
        double lowerBand = iBands(_Symbol, PERIOD_CURRENT, 20, 2, 0.0, PRICE_LOW);

    Perhaps you should read the manual, especially the examples.
       How To Ask Questions The Smart Way. (2004)
          How To Interpret Answers.
             RTFM and STFW: How To Tell You've Seriously Screwed Up.

    On MT5, they all (including iCustom) return a handle (an int). You get that in OnInit. In OnTick/OnCalculate/OnStart (after the indicator has updated its buffers), you use the handle, shift and count to get the data.
              Technical Indicators - Reference on algorithmic/automated trading language for MetaTrader 5
              Timeseries and Indicators Access / CopyBuffer - Reference on algorithmic/automated trading language for MetaTrader 5
              How to start with MQL5 - General - MQL5 programming forum - Page 3 #22 (2020)
              How to start with MQL5 - MetaTrader 5 - General - MQL5 programming forum - Page 7 #61 (2020)
              MQL5 for Newbies: Guide to Using Technical Indicators in Expert Advisors - MQL5 Articles (2010)
              How to call indicators in MQL5 - MQL5 Articles (2010)

  7. PFX Trader: but still not working as expected Please help

    Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
              Code debugging - Developing programs - MetaEditor Help
              Error Handling and Logging in MQL5 - MQL5 Articles (2015)
              Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
              Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)

Global Variables of the Terminal - MQL4 Reference
Global Variables of the Terminal - MQL4 Reference
  • docs.mql4.com
Global Variables of the Terminal - MQL4 Reference
 

Thank you so much dear for your advice

You spent too much time in it

I apprecaite

You are the best