preview
MQL5 Developer Gotchas (Part 1): A Parameter Mapper for Calling Indicators with Input Groups

MQL5 Developer Gotchas (Part 1): A Parameter Mapper for Calling Indicators with Input Groups

MetaTrader 5 — Examples |
98 0
Ali Akbar
Ali Akbar

Contents


    Introduction

    When an EA calls a custom indicator through iCustom() or IndicatorCreate(), it must pass the inputs in the order the terminal expects. If the indicator uses input groups, that order differs from the one in the inputs dialog. Each group line takes a slot of its own. In my tests on builds 6204 and 6230, the terminal accepted a shifted list of numeric values without any error. The CIndicatorInputs class reads the slot order from a running indicator instance. You set each value by its input number. The class fills the group slots and, on a chart, reads the created handle back to check every value. In the Strategy Tester the terminal does not report the order. There the class builds the handle from a layout file saved on a chart, and that handle stays unverified.

    BandsLite, the small bands indicator attached to this article, has four inputs in two groups. I called it with iCustom(..., 50, 2.5, 3, 80.0), the way the parameter list of iCustom() suggests. The handle was valid and nothing appeared in the journal. The indicator received a period of 2, a deviation of 3.0, and the defaults for the other two inputs. Over 4,577 bars of EURUSD H1 in 2026, the intended settings gave 32 signals and the call I actually wrote gave 0. An EA built on that call would compile, load, and run without ever opening a trade.

    The article measures the problem first and then builds the class. It covers which values each slot accepts through both functions, including negative, out-of-range, and non-finite values. It also covers a Strategy Tester restriction and how the class works around it. There are 61 unit tests, a tester EA, and a Python script that repeats the main calculations as a consistency check.

    This is Part 1 of a series on MQL5 code that compiles and runs but quietly does something other than what it says.


    What the documentation and the forum say

    The Input Variables page describes input groups as a way to visually separate parameters in the inputs dialog. The same page says that iCustom() parameters "should go in a strict accordance with the declaration of input variables" of the indicator. The iCustom() page says the type and order of the parameters must match. Neither page says that a group line takes a place in that order.

    The forum found it anyway. In January 2024 a user reported the behavior as a bug with input group and iCustom(), with sample code, on build 4150. A few days later Dominik Egert wrote in the documentation errors thread that the terminal handles group lines as regular inputs, and that each one has to be passed as an empty string. In May 2025 Robert Northen asked whether input group affects the parameter array of IndicatorCreate() and confirmed that three inputs under two group lines need five MqlParam entries. He asked MetaQuotes to put the rule in the documentation, and the pages above still don't mention it.

    So the rule itself is known to people who read the forum, and anyone can count the group lines by hand. Counting by hand needs the source code, however, and the count breaks quietly the day the author adds a group. I could not find a class that reads the layout from a running indicator. I also found no measurement of when the shift fails with an error and when it stays silent, and nothing that covered the Strategy Tester. Those three points are what this article adds.


    Section 1: The slots the terminal sees

    IndicatorParameters() returns the parameters of an indicator handle as an array of MqlParam. For a custom indicator the first entry is the file name, and one entry follows for every slot. I created a BandsLite handle with no parameters, so it ran with its defaults, and printed what came back. The group lines are there as strings of the form "@group 'Name'", in the same places as in the source. In the output, IcustomGroups\BandsLite is a path. IcustomGroups is the project folder under MQL5\Indicators, not a misspelling of iCustom().

    //+------------------------------------------------------------------+
    //| Inputs: 4 numbers in 2 groups                                    |
    //+------------------------------------------------------------------+
    input group  "Bands"
    input int    InpPeriod      =20;                  // Moving average period
    input double InpDeviation   =2.0;                 // Width in standard deviations
    input group  "Signal"
    input int    InpConfirmBars =2;                   // Closes outside the band before a signal
    input double InpMinWidthPts =50.0;                // Skip bands narrower than this, points
    IcustomGroups\BandsLite: 6 slots, 4 inputs, 2 groups
      slot  0  group     STRING        "@group 'Bands'"
      slot  1  input 0   INT           20
      slot  2  input 1   DOUBLE        2.0000
      slot  3  group     STRING        "@group 'Signal'"
      slot  4  input 2   INT           2
      slot  5  input 3   DOUBLE        50.0000

    This is the layout the class works from. The slot numbers are what IndicatorCreate() and iCustom() count. The input numbers are what a person counts when reading the inputs dialog. Each group line above an input adds 1 to the gap between the two numbers.

    Group lines are not the only extra slots. An indicator written with the short form of OnCalculate(), the one that receives a single price array, has an extra slot at the end for the applied price. InputEcho, the second test indicator, has five inputs in three groups and reports nine slots for that reason. SlotProbe, a third attached indicator, starts with an sinput variable and then has an empty group line. Both took a slot of their own, and the unit tests below set the sinput through the class like any other input.

    The types in the reply are not always the declared ones. TypeSlots, the indicator used for the type tests in Section 2, has one group line and one input of each common type, followed by four narrower types. On build 6230 the reply described it like this:

    IcustomGroups\TypeSlots: 13 slots, 11 inputs, 1 group
      slot  0  group     STRING        "@group 'Slots'"
      slot  1  input 0   INT           1
      slot  2  input 1   DOUBLE        1.0000
      slot  3  input 2   BOOL          0
      slot  4  input 3   STRING        "s"
      slot  5  input 4   INT           0
      slot  6  input 5   LONG          1577836800
      slot  7  input 6   UINT          0
      slot  8  input 7   UCHAR         1
      slot  9  input 8   SHORT         1
      slot 10  input 9   UINT          1
      slot 11  input 10  DOUBLE        1.0000
      slot 12  price     INT           1

    The enum input comes back as INT, the datetime as LONG, the color as UINT, and the float as DOUBLE. On build 6230, the reply alone cannot distinguish an enum from an int, a datetime from a long, a color from a uint, or a float from a double. Section 4 shows how the class detects the float case and what it does about the others.


    Section 2: What each slot accepts

    TypeMatrix.mq5 creates TypeSlots 72 times per function. Each time it puts one of nine test values into one of the first eight slots, with valid values in the slots before it. It then reads the handle back to see what the terminal stored. On build 6204 I ran the matrix through IndicatorCreate() only. On build 6230 IndicatorCreate() and iCustom() gave the same result in all 72 cells, and both matched the build 6204 table below. A failed creation returned error 4002 in every case. The datetime test value is 1 January 2026, which is 1767225600 as a number.

    Slot int 7 long 9 double 2.5 double 3.0 bool true datetime color red string "abc" string "12"
    group line kept kept kept kept kept kept kept kept kept
    int 7 9 2 3 1 1767225600 255 4002 4002
    double 7.00 9.00 2.50 3.00 1.00 1767225600.00 255.00 4002 4002
    bool 1 1 1 1 1 1 1 4002 4002
    string 4002 4002 4002 4002 4002 4002 4002 "abc" "12"
    enum 7 9 2 3 1 1767225600 255 4002 4002
    datetime 7 9 2 3 1 1767225600 255 4002 4002
    color 7 9 2 3 1 1767225600 255 4002 4002

    Within these 72 cells, three rules describe every result. A group slot accepts any value and keeps its own text. A string slot accepts only a string. Every other slot accepts any number and never a string. Along the way the fraction of a double is dropped in an integer slot, so 2.5 becomes 2 without a word. Any number other than 0 becomes true in a bool slot.

    The 72 cells use small positive values only, so the same script also sends 24 edge values through both functions. Both functions gave the same result in all 24 cases, shown in the next table.

    Slot Value sent Stored by the terminal
    int int -5 -5
    int long 3000000000 -1294967296
    int double -2.5 -2
    int double 1e20 -2147483648
    int double NaN -2147483648
    double double NaN NaN
    double double inf inf
    double int -5 -5
    bool int -1 1
    bool double 0.4 1
    string empty string empty, the indicator got 0 characters
    string 245 characters 245 characters, the indicator got 245
    string 246 characters 245 characters, the indicator got 245
    enum int 99 99
    enum int -1 -1
    datetime long -1 -1
    color int -1 4294967295
    uchar int 300 44
    uchar int -1 255
    short int 40000 -25536
    uint int -1 4294967295
    uint long 5000000000 705032704
    float double 1e40 inf
    float double 0.1 0.1000000015

    No edge value was refused, so the three rules about what loads still held. The stored values follow the usual C conversions. Integers wrap around, a double loses its fraction toward zero, and a double outside the int range becomes -2147483648. The bool 0.4 case was unexpected, since the value became true instead of losing its fraction and becoming 0. The terminal does not check an enum against its list, so 99 reached the indicator as a value the enum does not declare. Two results change values without any error: a float slot rounds to float precision, and a string slot keeps only the first 245 characters. TypeSlots writes the length of the string it received into a buffer, so the 245 is what the indicator itself saw, not only what IndicatorParameters() reported.

    These rules cover the values in the two tables and nothing more. I did not test char, ushort, long, or ulong slots, and I did not try strings with characters outside the Latin range in a matrix cell.

    What do the tables say about errors? Within this test set the terminal refused a handle only when a string met a numeric slot or a number met a string slot, with error 4002. So a shifted call to an indicator whose inputs are all numbers never produced 4002 here. A handle can still fail for reasons outside the matrix, such as a missing symbol, missing history, or a missing indicator file. A check inside the indicator's own OnInit() does not even make the handle invalid. NeedsInputs, attached for that case, refuses to start with its default period of 0. Its handle was valid, and BarsCalculated() stayed at -1.

    The unit tests also checked a value placed past the last slot. A 7th value of 1 for BandsLite, which has six slots, was dropped and the handle loaded. A 7th value of 99 failed in both functions with error 4804, ERR_INDICATOR_CANNOT_APPLY. The terminal seems to read that position as the data source of the indicator, a price type or the handle of another indicator. I did not test that reading further.


    Section 3: What the shift does to a real indicator

    BandsLite is a plain Bollinger-style indicator. It draws a simple moving average with bands a number of standard deviations away. It marks a signal when price closes back inside after a number of closes outside. Figure 1 shows where the four values of the plain call end up, and where the same values end up with a placeholder in each group slot.

    Where the values of iCustom(..., 50, 2.5, 3, 80.0) land

    BandsLite: four inputs under two input group lines, six slots

    Fig. 1. The values of the plain call move one slot to the left at each group line, while the call with placeholders puts every value on its input

    ShiftCost.mq5 creates both handles on EURUSD H1, copies their buffers over 2026 and counts the signals. The first two lines come from BandsLite itself, which prints its inputs in OnInit().

    BandsLite received: period=2 deviation=3.00 confirm=2 min_width=50.0
    BandsLite received: period=50 deviation=2.50 confirm=3 min_width=80.0
    ShiftCost EURUSD PERIOD_H1, 4577 bars from 2026.01.02 to 2026.09.25
    intended inputs: 18 buy and 14 sell signals, mean band width 1057 points
    raw call:        0 buy and 0 sell signals, mean band width 171 points
    signals on the same bar with the same side: 0

    The 0 comes from the period of 2. With two closes, each close sits exactly 1 standard deviation from their mean. A band 3 deviations from the mean can never be crossed, so BandsLite with these inputs can never give a signal on any symbol. The bands are also far narrower and follow every bar. Figure 2 shows 150 bars in July.

    EURUSD H1, 16 to 27 July 2026

    The same indicator with the intended inputs and with the inputs the plain call delivered

    Fig. 2. The intended bands stay wide and give 3 signals in these 150 bars, while the bands from the plain call hug the close and give none

    Band width on every bar of 2026

    EURUSD H1, 4,525 bars from 6 January, 100-point bins, 41 intended bars wider than 3,000 points not shown

    Fig. 3. Most bands from the plain call are under 300 points wide, while the intended bands spread from about 300 to over 2,000 points

    BandsLite is one example. When numeric inputs sit under group lines and the call passes no placeholders, the indicator runs with values nobody chose. A call with "" in each group slot does not have the problem. How visible the damage is depends on how far the shifted values are from the intended ones.


    Section 4: IndicatorInputs.mqh, the mapper class

    CIndicatorInputs takes the counting away from the caller. It reads the layout from the terminal and lets the caller set values by input number. It fills the group slots itself and checks the handle when it is created. Figure 4 shows the whole path, including the tester branch from Section 5.

    How CIndicatorInputs builds a handle

    On a chart or in a script the layout comes from the terminal. In the Strategy Tester it comes from a file.

    Fig. 4. Load reads the slots, Probe sorts out groups and float inputs, Set checks each value, and Create builds the handle. On a chart Verify reads it back, while the tester reads a saved layout and skips the read-back

    //+------------------------------------------------------------------+
    //| Builds the parameter list of a custom indicator by input number  |
    //| and inserts a placeholder for every input group line             |
    //+------------------------------------------------------------------+
    class CIndicatorInputs
      {
    private:
       string            m_path;                      // indicator path as given to iCustom()
       MqlParam          m_slots[];                   // every slot after the name, with its default
       bool              m_group[];                   // true when the slot is an input group line
       bool              m_float[];                   // a DOUBLE slot that rounds to float precision
       int               m_input_slot[];              // input number -> slot number
       bool              m_price_slot;                // the last slot is the applied price
       bool              m_verified;                  // the last handle was read back and matched
       int               m_mismatch;                  // slots where the group text and the probe disagreed
       string            m_error;                     // reason for the last failure
    
       static bool       IsGroup(const MqlParam &p);
       static bool       IsInteger(const ENUM_DATATYPE type);
       static bool       Range(const ENUM_DATATYPE type,long &lo,long &hi);
       static string     Number(const double value);
       static string     Quoted(const string value);
       void              Index(void);
       bool              Probe(void);
       bool              CheckInput(const int input_no,const bool is_string);
       bool              CheckType(const int input_no,const ENUM_DATATYPE type,const ENUM_DATATYPE reported);
       bool              Store(const int input_no,const long value);
       bool              Same(const MqlParam &a,const MqlParam &b) const;
    
    public:
       //--- constructor: no layout yet
                         CIndicatorInputs(void) : m_price_slot(false), m_verified(false), m_mismatch(0) {}
       //--- the layout: from a live handle, or from a file for the tester
       bool              Load(const string path,const bool price_slot=false,const bool probe=true);
       bool              SaveLayout(const string file_name) const;
       bool              LoadLayout(const string file_name);
       //--- true when both layouts have the same slots, types, groups and defaults
       bool              SameLayout(const CIndicatorInputs &other);
       //--- slots where the "@group '" text and the probe in Load() disagreed
       int               PrefixMismatches(void) const { return(m_mismatch); }
       //--- number of inputs, not counting group lines or the price slot
       int               Inputs(void) const { return(ArraySize(m_input_slot)); }
       //--- number of slots after the indicator name
       int               Slots(void)  const { return(ArraySize(m_slots)); }
       int               Groups(void) const;
       int               InputOf(const string group,const int position) const;
       string            Describe(void) const;
       //--- the iCustom() call for the current values, with "" in every group slot
       string            CallText(void) const;
       //--- reason for the last failure, empty after a success
       string            LastError(void) const { return(m_error); }
       //--- true when Create() read the handle back and every input matched
       bool              Verified(void)  const { return(m_verified); }
       //--- values by input number
       bool              Set(const int input_no,const long value);
       bool              Set(const int input_no,const double value);
       bool              Set(const int input_no,const string value);
       bool              SetBool(const int input_no,const bool value);
       bool              SetTime(const int input_no,const datetime value);
       bool              SetColor(const int input_no,const color value);
       bool              SetEnum(const int input_no,const int value);
       bool              SetPrice(const ENUM_APPLIED_PRICE price);
       //--- the parameter array and the handle
       int               Build(MqlParam &params[]) const;
       int               Create(const string symbol,const ENUM_TIMEFRAMES period);
       bool              Verify(const int handle);
      };

    Load() creates the indicator with nothing but its name, so every slot holds its default. It keeps whatever IndicatorParameters() returns. The caller has to say whether the last slot is an applied price, because nothing in the reply marks it. For a short-form indicator the price looks like any other int.

    //+------------------------------------------------------------------+
    //| Read the slot layout from a handle created with the defaults     |
    //+------------------------------------------------------------------+
    bool CIndicatorInputs::Load(const string path,const bool price_slot=false,const bool probe=true)
      {
       m_path      =path;
       m_price_slot=price_slot;
       m_mismatch  =0;
       m_error     ="";
       ArrayFree(m_slots);
       ArrayFree(m_group);
       ArrayFree(m_float);
       ArrayFree(m_input_slot);
    //--- a handle with no inputs uses the defaults and reports every slot
       MqlParam name[1];
       name[0].type        =TYPE_STRING;
       name[0].string_value=path;
       ResetLastError();
       int handle=IndicatorCreate(_Symbol,PERIOD_CURRENT,IND_CUSTOM,1,name);
       if(handle==INVALID_HANDLE)
         {
          m_error=StringFormat("cannot load %s, error %d",path,GetLastError());
          return(false);
         }
       MqlParam got[];
       ENUM_INDICATOR type;
       ResetLastError();
       int n=IndicatorParameters(handle,type,got);
       int err=GetLastError();
       IndicatorRelease(handle);
    //--- the Strategy Tester answers 4014 here, a saved layout is needed there
       if(n<1)
         {
          m_error=StringFormat("IndicatorParameters() returned %d for %s, error %d",n,path,err);
          return(false);
         }
    //--- slot 0 of the reply is the indicator name, the inputs follow
       ArrayResize(m_slots,n-1);
       ArrayResize(m_group,n-1);
       ArrayResize(m_float,n-1);
       for(int s=0; s<n-1; s++)
         {
          m_slots[s]=got[s+1];
          m_group[s]=IsGroup(m_slots[s]);
          m_float[s]=false;
         }
    //--- the text is a first guess, the probe decides
       if(probe && !Probe())
         {
          ArrayFree(m_slots);
          ArrayFree(m_group);
          ArrayFree(m_float);
          return(false);
         }
       Index();
       return(true);
      }

    My first version decided which slots are groups by the text alone, a string value that starts with "@group '". That text format is not documented anywhere I could find. A regular string input whose default happens to start with the same text would also pass for a group. SlotProbe has such an input, and the text test counted three groups where there are two. So the text is now only a first guess. Probe() creates one more handle with a marker string in every string slot and 0.1 in every double slot. A group slot keeps its own text whatever it is given, which the matrix showed, while a string input takes the marker. A float input rounds 0.1 to 0.1000000015, which is how the class finds a float behind a DOUBLE type.

    //+------------------------------------------------------------------+
    //| One handle with a probe value in every string and double slot.   |
    //| A group slot keeps its own text, a string input takes the probe. |
    //| A float input is reported as DOUBLE and rounds 0.1 to float.     |
    //+------------------------------------------------------------------+
    bool CIndicatorInputs::Probe(void)
      {
       MqlParam params[];
       int n=Build(params);
       int last_input=(m_price_slot ? Slots()-1 : Slots());
       for(int s=0; s<last_input; s++)
         {
          if(m_slots[s].type==TYPE_STRING)
             params[s+1].string_value=II_PROBE_TEXT;
          if(m_slots[s].type==TYPE_DOUBLE)
             params[s+1].double_value=II_PROBE_REAL;
         }
       ResetLastError();
       int handle=IndicatorCreate(_Symbol,PERIOD_CURRENT,IND_CUSTOM,n,params);
       if(handle==INVALID_HANDLE)
         {
          m_error=StringFormat("the probe handle failed, error %d",GetLastError());
          return(false);
         }
       MqlParam got[];
       ENUM_INDICATOR type;
       int count=IndicatorParameters(handle,type,got);
       IndicatorRelease(handle);
       if(count!=n)
         {
          m_error=StringFormat("the probe handle reports %d slots, expected %d",count-1,n-1);
          return(false);
         }
       for(int s=0; s<last_input; s++)
         {
          if(m_slots[s].type==TYPE_STRING)
            {
             bool group=(got[s+1].string_value!=II_PROBE_TEXT);
             if(group!=m_group[s])
                m_mismatch++;
             m_group[s]=group;
            }
          if(m_slots[s].type==TYPE_DOUBLE)
             m_float[s]=(got[s+1].double_value!=II_PROBE_REAL);
         }
       return(true);
      }
    IcustomGroups\SlotProbe: 5 slots, 3 inputs, 2 groups
      slot  0  input 0   INT           1
      slot  1  group     STRING        "@group 'Empty'"
      slot  2  group     STRING        "@group 'Real'"
      slot  3  input 1   INT           2
      slot  4  input 2   STRING        "@group 'Fake'"
      1 slot(s) where the group text and the probe disagreed, the probe was used

    The probe rests on two observed behaviors, the group slot that keeps its text and the float rounding. A future build could change either one, and then the probe would sort the slots wrongly. PrefixMismatches() reports how many slots the text and the probe disagreed on, so a change in the group format at least shows up as a number.

    Load() needs the indicator to be created with its defaults. NeedsInputs fails its own OnInit() with those defaults, and Load() still read all its slots, because the terminal creates the handle and reports the parameters even when the indicator refuses to calculate. However, NeedsInputs is a single case. An indicator whose handle can't be created at all, for example because the file is missing, can't be loaded.

    The setters check the value against the slot before anything reaches the terminal. A number for a string input and a string for a numeric input are refused, since the terminal would answer with 4002 anyway. The other refusals cover the silent changes from the edge table. They refuse a fraction or an out-of-range number for an integer input, NaN and inf, a number beyond the float range for a float input, and a string over 245 characters.

    //+------------------------------------------------------------------+
    //| Set a double input, or a whole number into an integer input      |
    //+------------------------------------------------------------------+
    bool CIndicatorInputs::Set(const int input_no,const double value)
      {
       if(!CheckInput(input_no,false))
          return(false);
       int s=m_input_slot[input_no];
    //--- NaN and inf are stored, but no read-back can confirm them
       if(!MathIsValidNumber(value))
         {
          m_error=StringFormat("input %d: %.8g is not a finite number",input_no,value);
          return(false);
         }
    //--- the terminal would drop the fraction without a word
       if(IsInteger(m_slots[s].type))
         {
          if(value!=MathFloor(value) || MathAbs(value)>9.0e18)
            {
             m_error=StringFormat("input %d is %s, %.8g is not a whole number it can hold",input_no,
                                  StringSubstr(EnumToString(m_slots[s].type),5),value);
             return(false);
            }
          return(Store(input_no,(long)value));
         }
    //--- a float input keeps float precision, and 1e40 would become inf
       if(m_float[s] || m_slots[s].type==TYPE_FLOAT)
         {
          if(MathAbs(value)>FLT_MAX)
            {
             m_error=StringFormat("input %d is float, %.8g is outside its range",input_no,value);
             return(false);
            }
          m_slots[s].double_value=(double)(float)value;
         }
       else
          m_slots[s].double_value=value;
       m_slots[s].integer_value=(long)value;
       return(true);
      }
    //+------------------------------------------------------------------+
    //| Store a whole number if the slot keeps it without wrapping       |
    //+------------------------------------------------------------------+
    bool CIndicatorInputs::Store(const int input_no,const long value)
      {
       int  s=m_input_slot[input_no];
       long lo=0,hi=0;
       if(Range(m_slots[s].type,lo,hi) && (value<lo || value>hi))
         {
          m_error=StringFormat("input %d is %s, %I64d is outside %I64d..%I64d",input_no,
                               StringSubstr(EnumToString(m_slots[s].type),5),value,lo,hi);
          return(false);
         }
       m_slots[s].integer_value=value;
       m_slots[s].double_value =(double)value;
       return(true);
      }

    SetBool(), SetTime(), SetColor(), and SetEnum() add a type check where the reply allows one. SetBool() needs a BOOL slot. SetTime() accepts a DATETIME or LONG slot, and SetColor() a COLOR or UINT slot, because build 6230 reported those types that way. SetEnum() needs an INT slot and can't check the enum range. So the type model stays partial. SetColor() on a uint input passes, and SetEnum(4, 99) passes as well.

    Build() writes the array for IndicatorCreate(): the name first, then every slot, with an empty string in each group slot. The slots the caller never set keep the defaults read by Load(). Create() makes the handle and, outside the tester, calls Verify(). Verify() reads the new handle back and compares every input slot with what was set. A layout that no longer matches the indicator shows up there, not 3 weeks later in a backtest report.

    //+------------------------------------------------------------------+
    //| Fill the IndicatorCreate() array: the name, then every slot      |
    //+------------------------------------------------------------------+
    int CIndicatorInputs::Build(MqlParam &params[]) const
      {
       int n=Slots()+1;
       ArrayResize(params,n);
       params[0].type        =TYPE_STRING;
       params[0].string_value=m_path;
       for(int s=0; s<Slots(); s++)
         {
          params[s+1]=m_slots[s];
          //--- a group slot takes any value, an empty string is the usual one
          if(m_group[s])
             params[s+1].string_value="";
         }
       return(n);
      }
    //+------------------------------------------------------------------+
    //| Create the handle and check that every input landed in place     |
    //+------------------------------------------------------------------+
    int CIndicatorInputs::Create(const string symbol,const ENUM_TIMEFRAMES period)
      {
       m_error   ="";
       m_verified=false;
       if(Slots()==0)
         {
          m_error="no layout, Load() has not succeeded";
          return(INVALID_HANDLE);
         }
       MqlParam params[];
       int n=Build(params);
       ResetLastError();
       int handle=IndicatorCreate(symbol,period,IND_CUSTOM,n,params);
       if(handle==INVALID_HANDLE)
         {
          m_error=StringFormat("IndicatorCreate() failed, error %d",GetLastError());
          return(INVALID_HANDLE);
         }
    //--- IndicatorParameters() is not allowed in the Strategy Tester, the handle stays unverified
       if(MQLInfoInteger(MQL_TESTER) || MQLInfoInteger(MQL_OPTIMIZATION))
          return(handle);
       if(!Verify(handle))
         {
          IndicatorRelease(handle);
          return(INVALID_HANDLE);
         }
       m_verified=true;
       return(handle);
      }

    My first version cleared m_verified only after IndicatorCreate() had succeeded. A failed Create() that followed a good one left Verified() returning true. Now the flag is cleared on the first line, and one of the unit tests covers the case.

    The class has no idea what an input is called. MqlParam carries a type and a value, not a name. Describe() prints the layout with input numbers so you can match them to the inputs dialog once. InputOf() finds an input by its group name and position when the groups are named well.

    CallText() turns the same layout into source text. It returns an iCustom() call with the current values and "" in every group slot. SaveLayout.mq5 prints that line. An EA that doesn't use the class can paste the line and still pass the values in the right order.


    Section 5: The Strategy Tester

    My first tester run of the EA below failed in OnInit(). Load() reported that IndicatorParameters() returned -1. TesterProbeEA.mq5 isolates the failure. It creates BandsLite and a built-in iMA. Then it calls IndicatorParameters() on both, once in OnInit() and once on the 100th tick.

    2026.09.01 00:00:00   OnInit, BandsLite: IndicatorParameters()=-1, error 4014, BarsCalculated()=-1
    2026.09.01 00:00:00   OnInit, iMA: IndicatorParameters()=-1, error 4014, BarsCalculated()=-1
    2026.09.01 00:46:30   tick 100, BandsLite: IndicatorParameters()=-1, error 4014, BarsCalculated()=10317
    2026.09.01 00:46:30   tick 100, iMA: IndicatorParameters()=-1, error 4014, BarsCalculated()=10317

    Error 4014 is "function is not allowed for call". The result was the same for the custom indicator and for iMA, before and after they had calculated. The same restriction came up on the forum back in 2013, and build 6230 still has the restriction. So inside the tester the layout can't be read, and a created handle can't be verified either.

    The class works around the first part with a file and can do nothing about the second. Tester support is therefore partial. SaveLayout.mq5 runs on a chart, loads the layout, prints the CallText() line, and writes the layout to MQL5\Files with SaveLayout(). The EA names that file in a tester_file property, so the tester copies the file to the agent. The EA then reads the file with LoadLayout().

    IcustomGroups\BandsLite: 6 slots, 4 inputs, 2 groups
      slot  0  group     STRING        "@group 'Bands'"
      slot  1  input 0   INT           20
      slot  2  input 1   DOUBLE        2.0000
      slot  3  group     STRING        "@group 'Signal'"
      slot  4  input 2   INT           2
      slot  5  input 3   DOUBLE        50.0000
    
    SaveLayout: iCustom(_Symbol,_Period,"IcustomGroups\\BandsLite","",20,2.0,"",2,50.0)
    SaveLayout: the existing file matches the indicator
    SaveLayout: written to MQL5\Files\IcustomGroups\BandsLite.layout.txt
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
      {
       const string path="IcustomGroups\\BandsLite";
       if(InpUseMapper)
         {
          CIndicatorInputs in;
          //--- the tester can't read a layout from a handle, so it reads the saved file
          bool tester=(bool)MQLInfoInteger(MQL_TESTER);
          bool ok=(tester ? in.LoadLayout(path+".layout.txt") : in.Load(path));
          ok=ok && in.Set(0,(long)InpPeriod) && in.Set(1,InpDeviation) &&
             in.Set(2,(long)InpConfirm) && in.Set(3,InpMinWidth);
          if(ok)
             g_handle=in.Create(_Symbol,_Period);
          if(g_handle==INVALID_HANDLE)
            {
             Print("GroupCallerEA: ",in.LastError());
             return(INIT_FAILED);
            }
          PrintFormat("GroupCallerEA: handle from CIndicatorInputs, %s",
                      (in.Verified() ? "verified" : "layout from the saved file, not verifiable in the tester"));
         }
       else
         {
          g_handle=iCustom(_Symbol,_Period,path,InpPeriod,InpDeviation,InpConfirm,InpMinWidth);
          if(g_handle==INVALID_HANDLE)
             return(INIT_FAILED);
          Print("GroupCallerEA: handle from a plain iCustom() call");
         }
       g_trade.SetExpertMagicNumber(InpMagic);
       return(INIT_SUCCEEDED);
      }

    Inside the tester Create() skips the read-back, so Verified() returns false, and the EA prints that the handle is not verifiable. A layout file written before the indicator changed would build a wrong array without any warning in the tester. SaveLayout.mq5 guards against that outside the tester. Before it writes, it loads the existing file and compares it with the running indicator through SameLayout(). To test the guard, I changed the default period of BandsLite from 20 to 25 in the terminal copy only, compiled it, and ran SaveLayout.mq5 against a copy of the good file.

    SaveLayout: iCustom(_Symbol,_Period,"IcustomGroups\\BandsLite","",25,2.0,"",2,50.0)
    SaveLayout: the existing file is OUT OF DATE (slot 1: the default changed)

    The guard works only if you run SaveLayout.mq5 after each indicator change and before testing. The tester itself has no way to notice a stale file.

    GroupCallerEA.mq5 trades BandsLite signals with a fixed stop and target of 250 points. I ran it twice on EURUSD H1 from 1 January to 26 September 2026, 1-minute OHLC, 10,000 USD, with no execution delay. The two runs differ only in InpUseMapper. Build 6204 and build 6230 gave the same numbers.

    Run Handle BandsLite received Signals Trades Net profit, USD Profit factor
    InpUseMapper=true CIndicatorInputs, layout from the file 50, 2.50, 3, 80.0 32 31 -226.66 0.55
    InpUseMapper=false plain iCustom() 2, 3.00, 2, 50.0 0 0 0.00 no trades

    The 32 signals match ShiftCost. One of them, a sell on 23 July, came while the buy from 20 July was still open, so it gave no trade. The strategy itself lost money: 11 of the 31 trades reached the target. That is not what the run was for, and I didn't tune the strategy. The second row is the one that matters here. Its tester journal has no error and no warning, yet the EA placed no trade in 9 months.


    Section 6: The verification script

    TestIndicatorInputs.mq5 runs 61 checks on a chart. It uses BandsLite for the numeric case and InputEcho for a string input, an enum, a bool, and the price slot. SlotProbe covers the sinput and the look-alike string, NeedsInputs covers defaults that fail, and TypeSlots covers every setter and range. The main checks compare buffers as well as parameters. The handle from the class draws exactly the same upper band as a hand-written call with placeholders over 200 bars. The plain call loads without an error and draws a different one. The last part of the output covers the setters:

    PASS  SetBool refused for an int input  (input 0 is INT, not BOOL)
    PASS  SetColor refused for a datetime input  (input 5 is LONG, not COLOR)
    PASS  3000000000 refused for an int input  (input 0 is INT, 3000000000 is outside -2147483648..2147483647)
    PASS  5 refused for a bool input  (input 2 is BOOL, 5 is outside 0..1)
    PASS  NaN refused for a double input  (input 1: -nan(ind) is not a finite number)
    PASS  300 refused for a uchar input  (input 7 is UCHAR, 300 is outside 0..255)
    PASS  40000 refused for a short input  (input 8 is SHORT, 40000 is outside -32768..32767)
    PASS  -1 refused for a uint input  (input 9 is UINT, -1 is outside 0..4294967295)
    PASS  1e40 refused for a float input  (input 10 is float, 1e+40 is outside its range)
    PASS  246 chars refused for a string input  (input 3: 246 chars, the terminal keeps 245)
    PASS  bool, enum, datetime, color, uchar, short, uint, float and 245 chars set
    PASS  TypeSlots handle verified, float compared at float precision
    PASS  SetEnum accepts 99, the enum range can't be checked
    PASS  SetColor accepts a uint input, both are reported as UINT
    custom indicator 'IcustomGroups\NoSuchIndicator' cannot load [4802]
    PASS  a missing indicator fails with a reason  (cannot load IcustomGroups\NoSuchIndicator, error 4802)
    PASS  Create after a failed Load fails  (no layout, Load() has not succeeded)
    TestIndicatorInputs: 61 passed, 0 failed

    These checks prove that the class does what it claims on build 6230. They don't prove anything about the terminal beyond the cases they run.

    The first version of the script taught me something unrelated to input groups. I wrote each check as Check(name,in.Set(...),in.LastError()), and every reason printed one line late. The reason argument was evaluated before the call next to it, so it showed the error of the previous check. Now every call runs on its own line before Check(). The script has a comment about the trap for the next person who tidies it up.


    Section 7: A consistency check in Python

    crosscheck.py is a Python 3 script that uses only the standard library. It reads the files the MQL5 programs write and repeats the main calculations. It is not an independent reference. It applies the same rules this article states, so it catches slips in the MQL5 code and in my logs, not a wrong rule. It predicts all 72 main cells from the three rules in Section 2, and the 24 edge cells from the C conversions and the 245-character limit.

    def predict(slot, value, precise):
        """(loads, stored) under the 3 rules plus the conversions."""
        kind, v = parse(value)
        is_string = kind == "string"
        if slot == "group":                      # rule 1: a group slot takes anything and keeps its own text
            return True, "kept"
        if slot == "string":                     # rule 2: a string slot takes only strings
            if not is_string:
                return False, ""
            if precise:
                n = min(len(v), MAX_STRING)
                return True, "%d chars, indicator got %d" % (n, n)
            return True, v
        if is_string:                            # rule 3: a numeric slot takes any number, never a string
            return False, ""
        if slot == "double":
            return True, show_real(float(v), precise)
        if slot == "float":
            x = float(v)
            if not math.isinf(x) and not math.isnan(x):
                x = float("inf") if abs(x) > 3.4028234663852886e38 else struct.unpack("f", struct.pack("f", x))[0]
            return True, show_real(x, precise)
        if slot == "bool":
            return True, "1" if v != 0 else "0"
        bits, signed = BITS[slot]
        return True, str(to_integer(v, bits, signed))

    It then replays the plain call on the saved layout file slot by slot. Finally it recomputes both sets of bands from the closes in shift_cost.csv and counts the signals again with the BandsLite rule. Run on the files from this article, it printed:

    main IndicatorCreate 72 of 72 cells match the rules
    main iCustom         72 of 72 cells match the rules
    main: the 2 APIs agree in 72 of 72 cells
    edge IndicatorCreate 24 of 24 cells match the rules
    edge iCustom         24 of 24 cells match the rules
    edge: the 2 APIs agree in 24 of 24 cells
    plain call on the saved layout: period=2 deviation=3.00 confirm=2 min_width=50.0
    ok  period 50 dev 2.5: upper band max diff 0.000005, closes outside the bands 218, signals Python 17/14, MQL5 17/14
    raw period 2 dev 3.0: upper band max diff 0.000000, closes outside the bands 0, signals Python 0/0, MQL5 0/0

    The 0.000005 difference in the intended bands is the rounding of the CSV file, which stores prices with five digits. The recount skips the first 52 bars of 2026, because their bands need closes from December 2025 that the file doesn't hold. One of the 18 buy signals falls in those bars, which is why Python and MQL5 both show 17 there. The 0 closes outside the bands of the plain call is the period-of-2 argument from Section 3, checked on every bar.


    Using it in your own EA

    The change is small, and OnInit() of GroupCallerEA.mq5 in Section 5 shows the whole change. Replace the iCustom() call with a CIndicatorInputs object. Then set the values by input number, create the handle, and print LastError() if the handle comes back invalid.

    Run Describe() once and compare it with the inputs dialog, so you know which input number is which. If the EA will be tested, run SaveLayout.mq5 for each indicator it calls, after every change to that indicator. Add a tester_file property for each layout file and load it with LoadLayout() when MQL_TESTER is set.

    If you would rather not include the class, run SaveLayout.mq5 on the indicator and copy the line it prints. That line already has "" in every group slot. You then change the values in it by hand.

    The class never opens the source file. IndicatorCreate() loads the compiled indicator, and IndicatorParameters() reads the slots from the running copy. I checked the .ex5 case on my own BandsLite only. I moved BandsLite.mq5 out of the terminal's Indicators folder and ran SaveLayout.mq5 on the .ex5 alone. It printed the same six slots and this call:

    SaveLayout: iCustom(_Symbol,_Period,"IcustomGroups\\BandsLite","",20,2.0,"",2,50.0)

    I have not tried an indicator bought on the Market or protected in another way. Such a file may behave differently, so the .ex5 result applies to an indicator compiled locally.

    Indicators you write yourself allow a second option: leave out the input groups. The only cost is that the inputs dialog loses its headings.


    Limitations

    Everything here was measured on one terminal with MetaQuotes-Demo, first on build 6204 and again on build 6230. The main matrix and the tester runs gave the same results on both builds. The edge values, the reported types, the 245-character limit, and the 7th-value results come from build 6230 only.

    Several results rest on behavior the documentation does not describe. They include the "@group '" text, the group slot that keeps its own text, the reported types, the float rounding, and the 245-character limit. A future build could change any of these. On a chart Verify() would then report a mismatch for a value that moved. However, a wrong group or float decision in Probe() can also shift the input numbers themselves, and only Describe() would show that.

    The class knows slots, types, and defaults, but not the names of the inputs. The caller can still swap two inputs of the same type that sit next to each other, and Verify() would accept the result. The class can't tell an enum from an int, a datetime from a long, or a color from a uint, and it doesn't check an enum range.

    Whether the last slot is an applied price has to be passed to Load(). I found no way to tell from the reply. A wrong flag shows up as one input too many or one too few in Describe().

    Load() needs a handle created with the defaults. NeedsInputs showed that a refusal in OnInit() doesn't stop the layout from loading, but that is one indicator. An indicator whose handle can't be created with its defaults can't be loaded.

    Tester support is partial. In the Strategy Tester the handle is not verified, because IndicatorParameters() is not allowed there. The tester relies on a layout file written earlier on a chart, and only SaveLayout.mq5, run outside the tester, can tell that the file is stale.

    I tested custom indicators that take their inputs from iCustom() and IndicatorCreate() by value. I did not test indicators that receive another indicator's handle as their price source, indicators called on a custom symbol, or Market indicators. The two tables cover the listed values only.

    crosscheck.py applies the rules from this article a second time. It checks the MQL5 results against a second implementation of the same rules, not against an outside reference.


    Conclusion

    On builds 6204 and 6230, every input group line in the five indicators I tested took a parameter slot in iCustom() and IndicatorCreate(). The documentation doesn't say so, and for numeric values the terminal didn't say so either. Within the tested values, a value that lands in the wrong numeric slot is accepted, and only a mix of strings and numbers gave error 4002. Some values change even in the right slot: integers wrap, floats round, and strings longer than 245 characters are cut. BandsLite called the obvious way ran for 9 months of EURUSD H1 with a period of 2 and produced no signal at all.

    CIndicatorInputs reads the layout from a running indicator and probes which slots are groups or floats. It fills the group slots, refuses values the terminal would silently change, and checks the handle after it is made on a chart. For an EA that doesn't use the class, CallText() gives the same order as one ready iCustom() line. In the Strategy Tester, where IndicatorParameters() fails with error 4014, the class builds the handle from a layout file but can't verify it. SaveLayout.mq5 reports a stale file before the test.

    The next part of the series looks at chart labels that stop at 63 characters without a warning.

    To try it, unpack MQL5.zip into the terminal's data folder and compile the indicators first. Run TestIndicatorInputs.mq5, TypeMatrix.mq5, and ShiftCost.mq5 on a EURUSD H1 chart, and run SaveLayout.mq5 before testing GroupCallerEA.mq5. crosscheck.py reads the files they write to MQL5\Files\IcustomGroups.

    Attached files

    # Name Folder Description
    1 IndicatorInputs.mqh MQL5\Include\IcustomGroups\ CIndicatorInputs: reads and probes the slot layout, fills the group slots, checks values and the handle, prints a ready iCustom() call, saves, loads, and compares layout files
    2 BandsLite.mq5 MQL5\Indicators\IcustomGroups\ Bands indicator with four inputs in two groups, used in every example
    3 InputEcho.mq5 MQL5\Indicators\IcustomGroups\ Test indicator that writes the values it received into its buffers
    4 TypeSlots.mq5 MQL5\Indicators\IcustomGroups\ Test indicator with one group line, one input of each common type, and four narrower types
    5 SlotProbe.mq5 MQL5\Indicators\IcustomGroups\ Test indicator with an sinput, an empty group, and a string input whose default looks like a group line
    6 NeedsInputs.mq5 MQL5\Indicators\IcustomGroups\ Test indicator that refuses to start with its default input
    7 TestIndicatorInputs.mq5 MQL5\Scripts\IcustomGroups\ Verification script, 61 checks with PASS or FAIL
    8 TypeMatrix.mq5 MQL5\Scripts\IcustomGroups\ Which values each slot accepts through IndicatorCreate() and iCustom(), with edge values, saved as type_matrix.csv
    9 ShiftCost.mq5 MQL5\Scripts\IcustomGroups\ BandsLite with the intended inputs against the plain call, saved as shift_cost.csv
    10 SaveLayout.mq5 MQL5\Scripts\IcustomGroups\ Prints the layout of a custom indicator and a ready iCustom() call, reports a stale layout file, and saves the layout for the Strategy Tester
    11 GroupCallerEA.mq5 MQL5\Experts\IcustomGroups\ Tester EA that trades BandsLite signals through the class or through a plain iCustom() call
    12 TesterProbeEA.mq5 MQL5\Experts\IcustomGroups\ Shows what IndicatorParameters() returns inside the Strategy Tester
    13 BandsLite.layout.txt MQL5\Files\IcustomGroups\ The BandsLite layout written by SaveLayout.mq5, read by GroupCallerEA.mq5 in the tester
    14 crosscheck.py MQL5\Files\IcustomGroups\ Python 3 consistency check of the type tables, the shift, and the signals
    15 MQL5.zip Unpack into the terminal's data folder All 14 files, with MQL5 as the root folder and an IcustomGroups subfolder in Include, Indicators, Scripts, Experts, and Files

    Every MQL5 file compiles with 0 errors and 0 warnings in MetaEditor build 6230. Tested on MetaTrader 5 build 6230, MetaQuotes-Demo, hedging account. crosscheck.py was run with Python 3.12.

    Attached files |
    IndicatorInputs.mqh (29.42 KB)
    BandsLite.mq5 (4.75 KB)
    InputEcho.mq5 (3.5 KB)
    TypeSlots.mq5 (3.35 KB)
    SlotProbe.mq5 (2.99 KB)
    NeedsInputs.mq5 (2.32 KB)
    TypeMatrix.mq5 (11.8 KB)
    ShiftCost.mq5 (4.93 KB)
    SaveLayout.mq5 (2.76 KB)
    GroupCallerEA.mq5 (5.44 KB)
    TesterProbeEA.mq5 (2.51 KB)
    crosscheck.py (7.57 KB)
    MQL5.zip (27.38 KB)
    Pesaran–Timmermann Test in MQL5: Separating Real Directional Skill from a Lucky Hit Rate Pesaran–Timmermann Test in MQL5: Separating Real Directional Skill from a Lucky Hit Rate
    This article implements the Pesaran–Timmermann directional accuracy test in pure MQL5 and applies its rolling right-tail p-value as a gate to enable or disable an Expert Advisor. Forecasts are scored without look-ahead, and the framework includes an EA, a rolling statistical display, and a self-test. The method is evaluated on XAUUSD, EURUSD and GBPUSD, with a coin-flip control to quantify false alarms.
    Building a Divergence System (Part VI): A Scoring Divergence Engine Building a Divergence System (Part VI): A Scoring Divergence Engine
    A reusable MQL5 divergence engine that stores all confirmed pivots, selects clean pivot pairs, and measures price extension in ATR, oscillator disagreement, and bar spacing into a 0–100 score. It logs named rejection reasons for filtered pairs and exposes per‑bar queries. Integration is reduced to four steps, and the score can drive an adaptive trailing system that scales its SAR step by divergence strength.
    Association Rules and Probability Theory in Forex: A Signal Filter Without Neural Networks or Magic Association Rules and Probability Theory in Forex: A Signal Filter Without Neural Networks or Magic
    We explore an alternative to neural network signal filters: association rules and basic probability theory in MQL5, without Python or external libraries. This guide demonstrates how to discretize market conditions (RSI, EMA, ATR, momentum, session), compile statistics on support, confidence, lift, and edge using Laplace smoothing, and apply the result as a transparent entry filter before placing a trade.
    Neural Networks in Trading: Bidirectional Adaptive Temporal Correlation (Main Components) Neural Networks in Trading: Bidirectional Adaptive Temporal Correlation (Main Components)
    We continue implementing the BAT framework in MQL5, showing how bidirectional correlation and the SATMA module enable the analysis of market dynamics in the context of the current state. Key architectural solutions that enable the framework to be adapted for financial data analysis are presented.