Fixing AI-generated code

 

This is an experimental topic where you can legally ask for help with AI-generated code. If you create a separate topic asking for help with AI-generated code, such a topic may be deleted.

The purpose of creating this topic is to maintain order on the forum.

 
Use the CODE button (Alt-S) when inserting code.

A moderator corrected the formatting this time. Please format code properly in future; posts with improperly formatted code may be removed.

EA compile error: undeclared identifier idx and some operator expected at line 16

Message: Hello everyone, I’m building a modular EA with multiple safeguard stages (Stage 2: Spread filter, Stage 3: Volatility check, Stage 5: Multi‑trade management).

When I compile, I keep getting these errors:

  • undeclared identifier idx (line 16)

  • 'idx' - some operator expected (line 16)

I’ve tried both loop forms:

for(int idx = 0; idx < totalTrades; idx++)

and

int idx;
for(idx = 0; idx < totalTrades; idx++)

but the errors persist.

Here’s the relevant Stage 5 code block:

bool Stage5_MultiTradeOK()
  {
   int totalTrades = PositionsTotal();
   double totalLots = 0.0;
   int symbolTrades = 0;
   int idx;
   for(idx = 0; idx < totalTrades; idx++)
     {
      if(PositionSelectByIndex(idx))
        {
         string sym = PositionGetString(POSITION_SYMBOL);
         if(sym == _Symbol)
            symbolTrades++;
         totalLots += PositionGetDouble(POSITION_VOLUME);
        }
     }
   AuditLog("Stage5", "Multi-trade check passed");
   return(true);
  }

I suspect the issue is upstream (Stage 2 or Stage 3 not closing properly, or a malformed AuditLog line), but I can’t spot it.

👉 Could someone please review and point out why the compiler still throws these errors, even though idx is declared?

Thanks in advance!

 
221062 #:
Those errors are caused by the fact that the PositionSelectByIndex() function does not exist - it is an AI hallucination.
 

Forum on trading, automated trading systems and testing trading strategies

Checking errors

Owethu luyanda Mchunu, 2026.02.12 15:44

//+------------------------------------------------------------------+
//| Three Candle Pattern EA - M5                                    |
//+------------------------------------------------------------------+
#property strict

input double   Lots                = 0.1;
input int      StopLossTicks       = 10;      // Adjustable SL in ticks
input double   RiskRewardRatio     = 2.0;     // TP = SL × RR
input int      StartHour           = 8;       // Trading start hour (server time)
input int      EndHour             = 13;      // Trading end hour (server time)
input int      EMAPeriod           = 10;

datetime lastBarTime = 0;

//+------------------------------------------------------------------+
int OnInit()
{
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
void OnTick()
{
   if(_Period != PERIOD_M5)
      return;

   datetime currentBarTime = iTime(_Symbol, PERIOD_M5, 0);
   if(currentBarTime == lastBarTime)
      return;

   lastBarTime = currentBarTime;

   // Check trading hours
   MqlDateTime timeStruct;
   TimeToStruct(TimeCurrent(), timeStruct);
   if(timeStruct.hour < StartHour || timeStruct.hour >= EndHour)
      return;

   if(PositionSelect(_Symbol))
      return;

   CheckBuy();
   CheckSell();
}
//+------------------------------------------------------------------+
void CheckBuy()
{
   double open1 = iOpen(_Symbol, PERIOD_M5, 3);
   double close1 = iClose(_Symbol, PERIOD_M5, 3);

   double open2 = iOpen(_Symbol, PERIOD_M5, 2);
   double close2 = iClose(_Symbol, PERIOD_M5, 2);

   double open3 = iOpen(_Symbol, PERIOD_M5, 1);
   double close3 = iClose(_Symbol, PERIOD_M5, 1);

   double high1 = iHigh(_Symbol, PERIOD_M5, 3);
   double high2 = iHigh(_Symbol, PERIOD_M5, 2);
   double low3  = iLow(_Symbol, PERIOD_M5, 1);

   double ema = iMA(_Symbol, PERIOD_M5, EMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);

   // Two bearish candles
   bool bearish1 = close1 < open1;
   bool bearish2 = close2 < open2;

   // Third bullish candle closing above both highs
   bool bullish3 = close3 > open3 && close3 > high1 && close3 > high2;

   bool aboveEMA = close3 > ema;

   if(bearish1 && bearish2 && bullish3 && aboveEMA)
   {
      double tickSize = _Point;
      double slDistance = StopLossTicks * tickSize;
      double sl = low3 - tickSize;
      double tp = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + (slDistance * RiskRewardRatio);

      trade(ORDER_TYPE_BUY, sl, tp);
   }
}
//+------------------------------------------------------------------+
void CheckSell()
{
   double open1 = iOpen(_Symbol, PERIOD_M5, 3);
   double close1 = iClose(_Symbol, PERIOD_M5, 3);

   double open2 = iOpen(_Symbol, PERIOD_M5, 2);
   double close2 = iClose(_Symbol, PERIOD_M5, 2);

   double open3 = iOpen(_Symbol, PERIOD_M5, 1);
   double close3 = iClose(_Symbol, PERIOD_M5, 1);

   double low1 = iLow(_Symbol, PERIOD_M5, 3);
   double low2 = iLow(_Symbol, PERIOD_M5, 2);
   double high3 = iHigh(_Symbol, PERIOD_M5, 1);

   double ema = iMA(_Symbol, PERIOD_M5, EMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);

   // Two bullish candles
   bool bullish1 = close1 > open1;
   bool bullish2 = close2 > open2;

   // Third bearish candle closing below both lows
   bool bearish3 = close3 < open3 && close3 < low1 && close3 < low2;

   bool belowEMA = close3 < ema;

   if(bullish1 && bullish2 && bearish3 && belowEMA)
   {
      double tickSize = _Point;
      double slDistance = StopLossTicks * tickSize;
      double sl = high3 + tickSize;
      double tp = SymbolInfoDouble(_Symbol, SYMBOL_BID) - (slDistance * RiskRewardRatio);

      trade(ORDER_TYPE_SELL, sl, tp);
   }
}
//+------------------------------------------------------------------+
void trade(ENUM_ORDER_TYPE type, double sl, double tp)
{
   MqlTradeRequest request;
   MqlTradeResult result;

   ZeroMemory(request);
   ZeroMemory(result);

   request.action   = TRADE_ACTION_DEAL;
   request.symbol   = _Symbol;
   request.volume   = Lots;
   request.type     = type;
   request.price    = (type == ORDER_TYPE_BUY) ? 
                       SymbolInfoDouble(_Symbol, SYMBOL_ASK) :
                       SymbolInfoDouble(_Symbol, SYMBOL_BID);
   request.sl       = sl;
   request.tp       = tp;
   request.deviation= 10;
   request.magic    = 123456;
   request.type_filling = ORDER_FILLING_FOK;

   OrderSend(request, result);
}
 

Owethu luyanda Mchunu #:

Forum on trading, automated trading systems and testing trading strategies

Checking errors

William Roeder, 2026.02.12 16:39

   double ema = iMA(_Symbol, PERIOD_M5, EMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
MT4 code. 

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/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)

 

Moderator warning: Incorrect AI-generated answer

The error happens because you're using an older C standard (C89) that requires all variable declarations to be at the very top of a block, before any executable code. So even though your int idx; syntax is correct, if any statement appears before it in the same block, the compiler rejects it. The fix is either to move all your variable declarations to the very top of the function, or compile with -std=c99 to use a newer standard that doesn't have this restriction.

 
Victor Paul Hamilton #:
The error happens because you're using an older C standard (C89) that requires all variable declarations to be at the very top of a block, before any executable code. So even though your int idx; syntax is correct, if any statement appears before it in the same block, the compiler rejects it.

There are no problems with variables or blocks. The only problem is that PositionSelectByIndex() doesn't exist. If you define it, the code will compile.

int OnInit() { return INIT_SUCCEEDED; }

void OnTick()
  {
   Stage5_MultiTradeOK();
  }

bool PositionSelectByIndex(int) { return true; }

void AuditLog(string, string) {}

bool Stage5_MultiTradeOK()
  {
   int totalTrades = PositionsTotal();
   double totalLots = 0.0;
   int symbolTrades = 0;
   int idx;
   for(idx = 0; idx < totalTrades; idx++)
     {
      if(PositionSelectByIndex(idx))
        {
         string sym = PositionGetString(POSITION_SYMBOL);
         if(sym == _Symbol)
            symbolTrades++;
         totalLots += PositionGetDouble(POSITION_VOLUME);
        }
     }
   AuditLog("Stage5", "Multi-trade check passed");
   return(true);
  }

 
Victor Paul Hamilton #:
compile with -std=c99 to use a newer standard that doesn't have this restriction.
Please demonstrate how to do this, since you recommend it.
 
Moderator warning: Incorrect AI-generated answer
Vladislav Boyko #:
Please demonstrate how to do this, since you recommend it.
The only change is moving int idx; to the very top of the function before anything else runs
 
Victor Paul Hamilton #:
The only change is moving int idx; to the very top of the function before anything else runs
I've already provided you with proof that your AI-generated answer is incorrect, but you continue to repeat it. Please refrain from making AI-generated comments when you don't understand either the question or the generated answer.