Expert Advisors • Indicators • Scripts • Libraries

MQL.RobotFX.org is the biggest collection of MetaTrader expert advisors (MT5 & MT4), indicators, scripts and libraries that can be used to improve trading results, minimize risks or simply automate trading tasks

Metatrader 5 Libraries | InputRules: Rules Between Inputs and the Share of Passes They Reject | MQL5 Release

Fresh MQL5 code release – perfect for enhancing your MT4/MT5 strategies.

Image for InputRules: Rules Between Inputs and the Share of Passes They Reject

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.

Watch in-depth trading tutorials and EA reviews on the RobotFX YouTube channel. Subscribe for free tips.

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.

Complement community code with advanced automation from RobotFX.

80358

Best MetaTrader Indicators + Profitable Expert Advisors