EA not triggering buy or sell trades

 

Hi all,

I'm relatively new to coding, but can someone take a look at this code and tell my if there's a reason the trades aren't triggering in back testing? I'm getting no errors back from MetaEditor, and the defined variables are how I'd like them. Just not getting any trades lighting up in MT5 when back testing. Any clues would be greatly appreciated. 

Merci!


// Define input parameters

input double lots = 0.1;
input int fastEMA = 5;
input int mediumEMA = 10;
input int slowEMA = 50;
input int RSIperiod = 14;
input int RSIupper = 83;
input int RSIlower = 17;
input int slippage = 3;
input double stopLoss = 50.0;
input double takeProfit = 150.0;
input int barsAndPrice = 50;

// Define global variables
double lastBuyPrice = 0;
double lastSellPrice = 0;

// Define initialization function
void OnInit()
{
   
}



// Define trading function
void OnTick()
{
     // Get the current price
     double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);

     // Calculate EMAs
     double fastMA = iMA(_Symbol, PERIOD_CURRENT, fastEMA, 0, MODE_EMA, PRICE_CLOSE);
     double mediumMA = iMA(_Symbol, PERIOD_CURRENT, mediumEMA, 0, MODE_EMA, PRICE_CLOSE);
     double slowMA = iMA(_Symbol, PERIOD_CURRENT, slowEMA, 0, MODE_EMA, PRICE_CLOSE);

    // Calculate RSI
    double rsi = iRSI(_Symbol, 0, RSIperiod, PRICE_CLOSE);

    // Check if there's an open position
    bool isBuyPosition = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY;
    bool isSellPosition = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL;

    // Check if previous buy/sell signal was within 50 candles and 50 pips
    bool isWithinRange = false;
    if(isBuyPosition)
    {
        if(lastBuyPrice > 0 && (price - lastBuyPrice) <= barsAndPrice)
        {
            isWithinRange = true;
        }
    }
    else if(isSellPosition)
    {
        if(lastSellPrice > 0 && (lastSellPrice - price) <= barsAndPrice)
        {
            isWithinRange = true;
        }
    }

    // Place a buy trade if the EMAs are in the right order and there's no open position and RSI is below the lower level
    if(fastMA > mediumMA && mediumMA > slowMA && !isBuyPosition && !isWithinRange && rsi < RSIupper)
    {
         lastBuyPrice = price;
        MqlTradeRequest request = {};
        MqlTradeResult result;
        request.action = TRADE_ACTION_DEAL;
        request.symbol = _Symbol;
        request.volume = lots;
        request.price = price;
        request.deviation = slippage;
        request.type_filling = ORDER_FILLING_FOK;
        request.type = ORDER_TYPE_BUY;
        request.tp = price + (takeProfit * _Point);
        request.sl = price - (stopLoss * _Point);
        request.comment = "Buy order";
        request.magic = 123456;
        if(OrderSend(request,result))
        {
            Print("Buy order opened with ticket #", result.order);
        }
        else
        {
            Print("Error opening buy order: ", result.retcode);
        }
    }

    // Place a sell trade if the EMAs are in the right order and there's no open position and RSI is above the upper level
      if(fastMA < mediumMA && mediumMA < slowMA && !isSellPosition && !isWithinRange && rsi > RSIlower)
      {
      
       lastSellPrice = price;
       MqlTradeRequest request = {};
       request.action = TRADE_ACTION_DEAL;
       request.symbol = _Symbol;
       request.volume = lots;
       request.price = price;
       request.deviation = slippage;
       request.type_filling = ORDER_FILLING_FOK;
       request.type = ORDER_TYPE_SELL;
       request.tp = price + (takeProfit * _Point);
       request.sl = price - (stopLoss * _Point);
       request.comment = "Sell order";
       request.magic = 1;
       MqlTradeResult result;
         if(OrderSend(request, result))
    {
        Print("Sell order opened with ticket #", result.order);
    }
         else
    {
        Print("Error opening sell order: ", result.retcode);
    }
}
}
 
ChatGPT code ?
 
  1. void OnTick()
    {
         // Get the current price
         double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
         // Calculate EMAs
         double fastMA = iMA(_Symbol, PERIOD_CURRENT, fastEMA, 0, MODE_EMA, PRICE_CLOSE);

    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.

    They all (including iCustom) return a handle (an int). You get that in OnInit. In OnTick/OnCalculate (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)

  2.     bool isBuyPosition = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY;
        bool isSellPosition = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL;

    No positions selected, bogus calls

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

 
Alain Verleyen #:
ChatGPT code ?

Yes sir, but it's got me a basic framework of what I need, however don't understand what's missing. Can you help?

 
catsoda #:

Yes sir, but it's got me a basic framework of what I need, however don't understand what's missing. Can you help?

No, your code doesn't make sense. It mixed mql4 and mql5.
 
catsoda #: Yes sir, but it's got me a basic framework of what I need, however don't understand what's missing. Can you help?
You also have the option to hire a programmer in the Freelance section. Given that you don't know how to code, it may be the better option.
Trading applications for MetaTrader 5 to order
Trading applications for MetaTrader 5 to order
  • 2023.04.26
  • www.mql5.com
The largest freelance service with MQL5 application developers
 
Alain Verleyen #:
No, your code doesn't make sense. It mixed mql4 and mql5.

I had a feeling that might be the case as I've spent all afternoon fixing errors in MetaEditor. Got rid of all the errors, so thought that may be it, but obvs more to it than that.

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

    They all (including iCustom) return a handle (an int). You get that in OnInit. In OnTick/OnCalculate (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)

  2. No positions selected, bogus calls

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

Hello William, I'm a new mql trader and I've built a simple not based on price action. Everything works well, no errors trades are going exactly as I coded. But at the end of one code, it could miss a signal or 2 before opening the next trade. Any help pls?
 
@harry amos #: Hello William, I'm a new mql trader and I've built a simple not based on price action. Everything works well, no errors trades are going exactly as I coded. But at the end of one code, it could miss a signal or 2 before opening the next trade. Any help pls?

Help with your code can only be provided if you show all relevant code and explain the issue in detail. Otherwise, you will have to hire a freelance coder to do it for you.

 
catsoda #:

Yes sir, but it's got me a basic framework of what I need, however don't understand what's missing. Can you help?

And people say AI will take your jobs hahahaha
 
Fernando Carreiro #:

Help with your code can only be provided if you show all relevant code and explain the issue in detail. Otherwise, you will have to hire a freelance coder to do it for you.

 #include <Trade\Trade.mqh>

input double LotSize = 0.1;       // Adjustable lot size
input double Multiplier = 20;      // Input multiplier for positive tick movement
CTrade trade;

int barsCount = 0;
double entryLow = 0.0;             // Stores the low of the entry candle

void OnTick()
{
    // Check if the bar count has increased, indicating a new candle
    int currentBarsCount = Bars(_Symbol, PERIOD_CURRENT);
    if (barsCount != currentBarsCount)
    {
        barsCount = currentBarsCount;
        
        // Print message on every new bar count
        Print("New bar detected. Checking conditions for Buy Bot.");

        // Ensure enough bars exist to reference
        if (barsCount < 2) return;

        // Fetch the high of the previous candle and close of the current candle
        double prevHigh = iHigh(_Symbol, PERIOD_CURRENT, 1);
        double currClose = iClose(_Symbol, PERIOD_CURRENT, 0);

        // Buy condition: bullish candle closes above the previous candle's high
        if (currClose > prevHigh)
        {
            // Check if there are no open positions
            if (PositionsTotal() == 0)
            {
                trade.Buy(LotSize, _Symbol);
                entryLow = iLow(_Symbol, PERIOD_CURRENT, 1);  // Store the low of the entry candle
                Print("Buy trade opened.");
            }
        }
    }

    // Check close condition if a buy trade is open on every new bar
    if (PositionSelect(_Symbol) && PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
    {
        double entryPrice = PositionGetDouble(POSITION_PRICE_OPEN);

        // Condition 1: Close if one candlestick closes below entry candle low
        if (iClose(_Symbol, PERIOD_CURRENT, 1) < entryLow)
        {
            trade.PositionClose(_Symbol);
            Print("Buy trade closed due to close below entry candle low.");
        }

        // Condition 2: Close if price has moved 20 ticks (or Multiplier) above entry price
        else if (iClose(_Symbol, PERIOD_CURRENT, 0) >= entryPrice + Multiplier * Point())
        {
            trade.PositionClose(_Symbol);
            Print("Buy trade closed due to positive price movement.");
        }
    }
} 

So this is my code above Fernando, what I mean is all is working fine, except it could take a trade signal on initialization, close that trade, skip one or 2 signals and then take the next trade on and on. Pls I would greatly appreciate your help