Watch how to download trading robots for free
Find us on Telegram!
Join our fan page
Interesting script?
So post a link to it -
let others appraise it
You liked the script? Try it in the MetaTrader 5 terminal
Libraries

InputRules: Rules Between Inputs and the Share of Passes They Reject - library for MetaTrader 5

Rico Hehl
Rico Hehl
  • Principal Software Engineer & Lead Cybersecurity Architect at  Posido Trading Solutions
  • Spain
  • 657
I'm a software architect based in Spain. I develop, fix, port and test Expert Advisors for MetaTrader 4 and MetaTrader 5 in MQL4 and MQL5.
Views:
39
Published:
\MQL5\Include\InputRules\
InputRules.mqh (14.59 KB) view
\MQL5\Scripts\InputRules\ \MQL5\Experts\InputRules\
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

What it does

Many Expert Advisors have inputs that only make sense together: a minimum below a maximum, a fast period below a slow one, a trailing step that matters only while trailing is on. The usual answer is a check in OnInit that returns INIT_PARAMETERS_INCORRECT, and the tester skips the pass. What nobody sees before the optimization is how many passes that check will reject. With three such rules on the small grid of the demo EA, 10206 of 12096 passes were rejected, and in a genetic optimization with wider ranges 435 of the first 512 passes failed and the tester stopped after the first generation.

InputRules keeps the rules in one function that OnInit and OnTesterInit both call. In OnInit, Check() tests the current values and returns INIT_PARAMETERS_INCORRECT with a Journal line that names the rule and the values that break it. In OnTesterInit, which runs in the terminal before the first pass, Estimate() reads the ranges set in the Strategy Tester with ParameterGetRange, goes through the combinations of the declared inputs and prints how many each rule would reject and how many would run. Above a share you set it prints a warning, and the EA can stop the optimization before it starts.

A third kind of rule covers an input that is used only while a switch is on. With trailing off, every value of the trailing step gives the same pass, so the optimization repeats one result many times. In an optimization Check() rejects these repeats and lets only the pass with one chosen idle value run; in a single test it rejects nothing for this reason. The test script InputRulesTest checks 21 cases on values and ranges it sets in memory, and the demo EA InputRulesDemo never trades and runs in the tester mode "Math calculations".

The estimate of InputRules before an optimization of the demo EA, and the passes the tester then rejected
The estimate of InputRules before an optimization of the demo EA, and the passes the tester then rejected

Using it

The demo EA declares its rules like this. The rules sit in one function, and OnInit and OnTesterInit each create the rules, declare them and use them; the empty OnTesterDeinit is needed because the compiler refuses OnTesterInit without it (error 375).

#include <InputRules\InputRules.mqh>

input group "Inputs connected by rules" // the inputs that DeclareInputRules connects
input ENUM_TIMEFRAMES InpTimeframe       = PERIOD_M15; // Timeframe, must be below the higher timeframe
input ENUM_TIMEFRAMES InpHigherTimeframe = PERIOD_H1;  // Higher timeframe
input int             InpMinDistance     = 10;         // Minimum distance, must be below the maximum
input int             InpMaxDistance     = 30;         // Maximum distance
input bool            InpUseTrailing     = true;       // Trailing on or off
input double          InpTrailStep       = 5.0;        // Trailing step, only used while trailing is on
input group "InputRules"                // the estimate before an optimization
input double          InpMaxRejectShare  = 0.25;       // Warn when more than this share of passes is rejected (0.25 = 25 %)
input bool            InpStopAboveShare  = false;      // Stop such an optimization instead of only warning

void DeclareInputRules(CInputRules &rules)
  {
//--- enums need IR_ENUM, so that the estimate can read their ranges
   IR_ENUM(rules, InpTimeframe);
   IR_ENUM(rules, InpHigherTimeframe);
//--- the rules
   IR_RULE(rules, InpTimeframe, <, InpHigherTimeframe);
   IR_RULE(rules, InpMinDistance, <, InpMaxDistance);
   IR_ONLY_WHEN(rules, InpTrailStep, InpUseTrailing, true, 5.0);
  }

int OnInit()
  {
   CInputRules rules;
   DeclareInputRules(rules);
   return rules.Check();
  }

int OnTesterInit()
  {
   CInputRules rules;
   DeclareInputRules(rules);
//--- INIT_FAILED stops the optimization before its first pass
   if(!rules.Estimate(InpMaxRejectShare) && InpStopAboveShare)
     {
      Print("InputRulesDemo: optimization stopped, because InpStopAboveShare is true");
      return INIT_FAILED;
     }
   return INIT_SUCCEEDED;
  }

void OnTesterDeinit()
  {
  }

A single test with InpMinDistance 40 and InpMaxDistance 30 ends at once, and the journal of the tester says why:

InputRules: rejected, rule 2 does not hold: InpMinDistance < InpMaxDistance (InpMinDistance = 40, InpMaxDistance = 30)
tester stopped because OnInit reports incorrect input parameters

Before an optimization with the slow complete algorithm, the timeframes from M15 to H4 and from H1 to H4, both distances from 0 to 50 in steps of 10, trailing on and off and the trailing step from 1 to 10 in steps of 2, the Experts tab of the terminal shows:

InputRules: checking 6 inputs and 3 rules before the optimization
InputRules: InpTimeframe from PERIOD_M15 to PERIOD_H4, 7 values
InputRules: InpHigherTimeframe from PERIOD_H1 to PERIOD_H4, 4 values
InputRules: InpMinDistance from 0 to 50 step 10, 6 values
InputRules: InpMaxDistance from 0 to 50 step 10, 6 values
InputRules: InpTrailStep from 1 to 11 step 2, 6 values
InputRules: InpUseTrailing from false to true, 2 values
InputRules: 12096 combinations of the declared inputs, all checked
InputRules: rule 1, InpTimeframe < InpHigherTimeframe: 4320 rejected (35.7 %)
InputRules: rule 2, InpMinDistance < InpMaxDistance: 4536 rejected (37.5 %)
InputRules: rule 3, InpTrailStep only while InpUseTrailing == true: 1350 rejected as repeats (11.2 %)
InputRules: 10206 of 12096 would be rejected (84.4 %), 1890 run
InputRules: WARNING: 84.4 % rejected, the limit is 25.0 %

The estimate counts six values for the trailing step, from 1 to 11 in steps of 2: the tester rounds the 4.5 steps of a real input up, and it ran 12096 passes, the number the estimate counted with these six values. The rules between inputs and with constants are checked first, in the order of declaration, then the only-when rules; a combination is counted for the first of them that rejects it, so the counts per rule add up to the total.

The rules

Each macro passes the names of its variables as text, so the Journal lines use the names of the code. A rule compares numbers, bool values and enums; it does not take strings. Check() goes through the IR_RULE and IR_LIMIT rules first, in the order of declaration, and then through the IR_ONLY_WHEN rules. The first of them that rejects the values is the one the Journal names and the estimate counts, so a broken rule wins over a repeat even when the IR_ONLY_WHEN rule is declared before it.

Macro What it declares
IR_RULE(rules, left, op, right) A rule between two inputs, such as InpMinDistance < InpMaxDistance; op is <, <=, >, >=, == or !=
IR_LIMIT(rules, var, op, limit) A rule between an input and a constant, such as InpPeriod >= 2
IR_ONLY_WHEN(rules, var, switch, active, idle) var is used only while switch == active. While it is unused it breaks no other rule, and in an optimization only the pass with var == idle runs. If var is not optimized, it must stand at idle, or in an optimization every pass with the switch off is rejected
IR_ENUM(rules, var) An enum input. An optimized enum needs it, because the tester reports enum ranges as member positions
IR_INPUT(rules, var) An input without a rule, so that its values count in the combinations and the count matches the passes of the tester

Real numbers are compared with a relative tolerance of 1e-9, so 0.1 + 0.2 equals 0.3; when one side is a float the tolerance is 1e-6, because a float keeps about seven digits. Before the first check the library checks the declarations themselves: an unknown operator, an input compared with itself, a bool compared with a number, an enum compared with a real number, a string, a constant after == or != that the input can never equal, an active or idle value of IR_ONLY_WHEN that it can never take (2.5 for an int, 300 for a uchar), an input with two switches or as its own switch, and a circle of switches. A limit such as InpPeriod < 2.5 on an int is allowed. Each mistake gets a line "InputRules: declaration error: ..." in the Journal, Check() returns INIT_FAILED and Estimate() refuses, so a wrong rule is not mistaken for a wrong input.

Method What it does
int Check() For OnInit: INIT_SUCCEEDED, INIT_PARAMETERS_INCORRECT with the reason in the Journal, or INIT_FAILED after a declaration error. Repeats are rejected only in an optimization (MQL_OPTIMIZATION)
int Check(optimization) The same check, with the mode given, for a test
LastVerdict(), LastRule() Verdict of the last check (INPUT_RULES_PASS, INPUT_RULES_BROKEN, INPUT_RULES_REPEAT or INPUT_RULES_INVALID) and the index of the rule behind it, -1 if none
Inputs(), Rules(), Errors(), RuleText(rule) The numbers of declared inputs, rules and declaration errors, and a rule as written in the code
bool Estimate(max_share) For OnTesterInit: reads the ranges, checks the combinations and prints the result; false when more than max_share (0 to 1) would be rejected, when an input never takes its idle value or when no estimate is possible
SetSampling(full_limit, sample_size, seed) Up to full_limit combinations (default 1000000, at most 1e9) all are checked, above that a sample of sample_size (default 100000, at most 10000000) drawn with seed (default 1)
Combinations(), Checked(), Broken(), Repeats(), Sampled() The counts of the last estimate and whether it checked a sample
RuleRejects(rule), RejectedShare() Combinations for which a rule was the first to reject them, in the order of checking above, and the share of the checked combinations that would be rejected

The estimate

Estimate() reads the range of every declared input with ParameterGetRange and counts its values the way the tester runs them. For a whole number the tester rounds the number of steps down and never passes the stop value; for a real number it rounds it to the nearest whole number, halves up, so 1 to 10 in steps of 2 gives six values. An enum range arrives as member positions in the order of declaration. In OnTesterInit, IR_ENUM finds the members of its enum by trying the values from -65536 to 65535 and takes them in ascending order of value; for ENUM_TIMEFRAMES, with its 22 members, positions 1 to 15 are M1 to H4. An input the tester does not know, such as a misspelled name, is counted with its current value, and the Journal says so.

Up to 1000000 combinations the estimate checks all of them; in the test script one million combinations of three inputs and two rules took 11 to 13 ms. Above that it checks a random sample of 100000 combinations, drawn with replacement and seed 1, so the same ranges give the same result, and it prints the share with a 95 % interval. A range with more than 1e15 values is counted as 1e15 values. Optimized inputs that no rule names change the number of passes but not the share, so only the declared inputs are counted. Repeats count as rejected, because Check() rejects them in the optimization. When the share lies above the limit but both round to the same value with one decimal, the warning prints as many decimals as it takes to tell them apart, such as "25.04 % rejected, the limit is 25.00 %".

An input that is used only while a switch is on must be able to take its idle value. If the idle value lies outside its range, or if the input is not optimized and stands at another value, every pass with the switch off is rejected in an optimization. With InpUseTrailing fixed at false, InpTrailStep fixed at 7.5 and only the distances optimized, Check() would reject every pass as a repeat, although no two of them repeat each other. The estimate then prints a warning for the input, "a dependent input that is not optimized must stand at its idle value" when it has only one value, and a line of its own, "refused, because an input never takes its idle value", and returns false whatever the share.

Estimate() belongs in OnTesterInit, which runs in the terminal before the first pass. On a test agent ParameterGetRange failed with error 4014, so Estimate() does not run there and prints "no estimate on a test agent" instead. In a single test OnTesterInit does not run, and the terminal printed no estimate.

The test script

InputRulesTest declares rules on variables of its own and gives the estimate ranges in memory, so it needs neither the Strategy Tester nor symbol data. It has no inputs and prints one PASS or FAIL line per case and a summary; the estimate cases also print what OnTesterInit would print.

Case What it checks
01 Operators on whole numbers: each holds on one side of the limit only
02 Real numbers: 0.1 + 0.2 equals 0.3, 1e-6 apart does not; floats to 7 digits; whole numbers exact
03 Rules between inputs: int with int, double with int, the first broken rule counts, before a repeat
04 Only-when: outside an optimization nothing is rejected, inside only the idle value runs
05 An unused input breaks no rule: trail 12.5 < 10 counts only while trailing is on
06 Chain of switches: with c off, a is unused even though b is on
07 Enums: a mode as switch, a timeframe against PERIOD_M15
08 Declaration errors: operator, two switches, own switch, circle, impossible constants
09 Values of a range as the tester runs them: real steps rounded, whole steps rounded down
10 Estimate of 288 combinations equals a plain count: 168 broken, 1 broken, 45 repeats
11 Enum range as positions 1 to 15 is M1 to H4: 8 of 15 below M15, 120 of 225 pairs; IR_ENUM needed
12 Sample: 20000 draws of the 288 combinations, within 3 sigma, same seed same counts
13 Edge ranges: step 0, start above stop, one value, fixed, unknown name: 1 combination
14 Idle value 5 not in 6 to 10, nor in one value 7.5, nor fixed at 7.5: passes with trailing off rejected, refused
15 Limit: 50 % rejected is within 0.5, above 0.49; 1.5 counts as 1, -0.1 as 0; 25.04 % against 25.00 %
16 1000000 combinations of a < b < c all checked: 161700 pass, as C(100, 3)
17 Enum scan: off outside OnTesterInit; with it, a value that is no member found is an error
18 Declaration errors: a < a, bool with int, enum with real, string, idle 300 for a uchar
19 Random draws below 3e9 are even; one 32-bit draw would put 65 % below 1.5e9
20 Huge ranges: 1e20 values count as 1e15, the idle value is found or missed at once
21 Check(true) on each of the 288 combinations agrees with the estimate: 168, 45, 1, 214 rejected

The last line of a run is "InputRulesTest: 21 of 21 cases passed". The cases were checked against the code they guard: 18 faults were put into the library one at a time, such as dropping the exemption of unused inputs, turning the sign of the tolerance or rounding the steps the wrong way, and each of them made at least one case fail.

The demo EA

InputRulesDemo never trades and has no OnTick: run it in the Strategy Tester with the model "Math calculations", which needs no history; the symbol and the timeframe of the tester do not matter. Its OnTester returns a smooth function of the inputs that is always above 0, so a rejected pass, with result 0, stands out in the optimization results. With the default inputs every rule holds.

Input Default Meaning
InpTimeframe PERIOD_M15 Timeframe, must be below the higher timeframe
InpHigherTimeframe PERIOD_H1 Higher timeframe
InpMinDistance 10 Minimum distance, must be below the maximum
InpMaxDistance 30 Maximum distance
InpUseTrailing true Trailing on or off
InpTrailStep 5.0 Trailing step, only used while trailing is on
InpMaxRejectShare 0.25 Warn when more than this share of passes is rejected (0.25 = 25 %)
InpStopAboveShare false Stop such an optimization instead of only warning

The default of 0.25 follows a rule of thumb from forum threads about rejected passes and the genetic algorithm. It is not a measured limit; the runs below do not give one.

In the Strategy Tester

The demo EA ran in the Strategy Tester of MetaTrader 5 build 6320 with "Math calculations". With the default inputs the single test passed with OnTester result 25, and so did a test with "1 minute OHLC" on EURUSD H1. The optimization with the slow complete algorithm and the ranges shown above ran 12096 passes; the tester journal has 10206 of them with the error "incorrect input parameters", the number the estimate printed. Each pass of the report was checked against the three rules: every pass with result 0 breaks a rule, and every pass that breaks a rule has result 0. With InpStopAboveShare set to true, the same estimate was followed by "OnTesterInit failed. Optimization cannot be started.", and no pass ran.

A genetic optimization with the distances from 0 to 1000 in steps of 1 and the trailing step from 0 to 10 in steps of 0.1 has 5667317656 combinations. The estimate checked a sample and printed "about 84.0 % would be rejected (95 % interval 83.7 % to 84.2 %)". The tester then reported "435 passes of 512 failed, genetic optimization stopped at generation 0", 85.0 % of its first generation. Four more genetic runs optimized only the minimum distance and the trailing step, 101101 combinations, with the maximum distance fixed at 800, 700, 500 and 300. Each went on through 19 further generations to "genetic optimization finished on pass 2100 (of 101101)". Of these 2100 passes the tester ran between 264 and 310 and took the others from its result cache, and the report lists between 260 and 299 passes:

Maximum distance Estimate Rejected in generation 0 Rejected in the report
800 20.1 % 38 of 200 39 of 260
700 30.1 % 66 of 200 77 of 276
500 50.0 % 102 of 200 124 of 299
300 70.0 % 146 of 200 178 of 297

The first generation came close to the estimate in every run. In the later generations the genetic algorithm drew fewer rejected passes, so the share over the whole run was lower. One run stopped at 85 % in its first generation, and another went on at 73 %; the two had different inputs and populations, so these runs do not show where the tester stops.

How to use it

  1. Copy the six .mqh files to MQL5\Include\InputRules\, InputRulesTest.mq5 to MQL5\Scripts\InputRules\ and InputRulesDemo.mq5 to MQL5\Experts\InputRules\, and compile the script and the demo EA.
  2. Run the script on any chart. It needs no permission to trade. The Experts tab shows one line per case and the summary.
  3. Run InputRulesDemo in the Strategy Tester with "Math calculations", once as a single test and once as an optimization with the slow complete algorithm and a few ranges. The estimate stands in the Experts tab of the terminal before the first pass.
  4. In your own EA, write the rules into one function, call Check() in OnInit and Estimate() in OnTesterInit, and add an empty OnTesterDeinit. Declare every optimized enum with IR_ENUM.
  5. Before a long optimization, read the estimate. If most passes would be rejected, narrow the ranges until fewer combinations break a rule, for example by letting a maximum start above the highest minimum.

Related

PassRecorder, another library in the CodeBase, stores the passes of an optimization in an SQLite file, and its demo EA runs in "Math calculations" as well. InputRules decides before each pass whether it runs; PassRecorder keeps a record of the passes afterwards. The two were not tested together in one EA.

Limits

  • MetaTrader 5 only.
  • IR_ENUM numbers the members in the order of their values, the tester in the order of their declaration. It fits an enum whose members are declared in ascending order of value, with no two of the same value, between -65536 and 65535, such as ENUM_TIMEFRAMES. The library cannot check the order of declaration; for another enum the estimate uses wrong values, while Check() in OnInit, which sees the real values, is not affected.
  • A constant compared with an enum input is checked to be a whole number in the range of the type, not to be a member of the enum.
  • Rules work on the inputs alone. A rule that needs the symbol or the account, such as a stop above the stops level, cannot be declared.
  • A real input set to be optimized from 0.5 to 2.0 with step 0 was run by the tester from 0.5 to 5 in steps of 0.05, 91 values, and ParameterGetRange reported that range, so the estimate counted it as well. A tester run with a start above the stop and a range of one value ended with an error of the terminal and no result, so these cases are checked only by the test script.
  • The refusal of Estimate() on a test agent is in the code, but no test ran Estimate() on an agent.
  • In a genetic optimization the tester chooses the combinations itself. The estimate gives the share among all combinations; the share among the passes the tester runs can differ, as the table above shows.
  • ParameterSetRange is not used: the library does not change a range, it only reports it.
Prop Firm Equity Guard Prop Firm Equity Guard

Protects prop firm challenge and funded accounts: watches equity in real time and closes all trades before the daily loss or maximum loss limit is broken, with an optional profit target lock and a live progress panel.

Demetra Symbol Spec Sheet Demetra Symbol Spec Sheet

Puts the contract specification of the chart symbol on one sheet, including the money value of one point and the margin for one lot.

Channel Breakout EA with ATR trailing stop and risk-percent sizing Channel Breakout EA with ATR trailing stop and risk-percent sizing

Donchian channel breakout Expert Advisor with EMA trend filter, ATR stop, ATR trailing stop, break-even and position size from risk % of balance.

MACD Signals MACD Signals

Indicator edition for new platform.