Trading Bot Configuration: Parameters and Switchable Filters
To change a trading bot’s parameters without touching its code, move every value that may differ between runs into a versioned configuration file, validate that file strictly when the bot starts, and record which configuration produced each backtest and each trade. Optional filters become truly switchable when each one sits behind an explicit on/off flag and the off state is tested to behave exactly like a build without the filter. This article covers what belongs in the file, formats, validation and defaults, feature flags, versioning and logging, for Python bots and MQL5 Expert Advisors, with a tested Python loader. It also names the price of configurability: every switch doubles the number of variants you can backtest, and the more variants you try, the more likely the best one is overfit.
What belongs in a trading bot config file, and what stays in code?
The Twelve-Factor App defines configuration as everything that is likely to vary between deploys and requires a strict separation of config from code. It stores config in environment variables and warns that config files are easily checked in by mistake and tend to scatter. For credentials, follow that advice. Strategy parameters are a different case: a backtest can only be reproduced if its parameters are versioned together with the code, so this article keeps them in one validated file. For a trading bot, “deploys” include the paper and the live account, different instruments, backtests and parameter studies. The split below keeps each kind of value in one place:
| Where | What | Examples |
|---|---|---|
| Config file, versioned | Values that may differ between runs | Instruments, timeframes, indicator lengths, risk limits, trading hours, filter switches and their parameters |
| Code | Logic and invariants | Signal rules, order handling, reconciliation, the meaning and unit of each parameter, hard safety limits |
| Environment or secret store | Credentials and account identifiers | API keys, passwords, account numbers, host names |
Two rules help. First, every parameter lives in exactly one place; a value in the file that the code quietly overrides is worse than no file at all. Second, hard safety limits, such as the largest position the system may ever hold, stay in code or in a separate file that changes rarely and only after review. A typo in a strategy experiment must not be able to raise the maximum position size of the live system.
Keep separate files for the paper and the live account, and have the bot compare the connected account with the one its configuration names before it sends anything.
Config file formats: TOML, JSON or MQL5 input sets
Any format works if it is parsed strictly and versioned together with the code. The choice is mostly about who edits the file.
- TOML: readable, allows comments and has typed values. Python’s standard library has parsed it with
tomllibsince version 3.11; the module reads TOML but does not write it. - JSON: universal and easy to generate, but without comments, so explanations have to live elsewhere.
- MQL5 inputs: an Expert Advisor’s parameters are its
inputvariables. According to the MQL5 reference, the program can only read them; the user changes them in the properties window. Variables declared withsinputare not used in the optimization of input parameters, which suits settings such as a magic number or a log level that must not vary in a parameter search. Enumerations offer a drop-down list instead of free numbers.
For Expert Advisors, the MetaTrader 5 help describes saving a parameter set as a set-file that can be moved between computers, or as a version inside the platform. Treat the set-file as the EA’s configuration file: commit it next to the source code, one per instrument or account, so that the settings that run live never exist only inside a terminal.
Validation and defaults: fail at startup, not at the first trade
A misspelled key is a typical configuration bug: the file says lookbak_bars = 50, a loader that only reads the keys it knows skips it, and the bot runs with the default without anyone noticing. Schema languages do not prevent this on their own. In JSON Schema, any additional properties are allowed unless additionalProperties is set to false, properties are not required unless they are listed in required, and the default keyword is an annotation that is not used to fill in missing values during validation.
The loader therefore has to do three things explicitly: reject unknown keys, apply defaults itself, and refuse to start on any error. Risk limits deserve no default at all; a missing daily loss limit should stop the bot instead of silently meaning zero, infinity or a value chosen for another account. Cross-field rules, such as a session start before its end, belong in the same check.
The example below follows these rules for a TOML file. In DEFAULTS, a type instead of a value marks a required key. It was tested with Python 3.12 against a valid file, a misspelled key, missing required keys, wrong types, booleans given as numbers, out-of-range values, a malformed time and an unsupported schema version; it reads a local file and connects to nothing.
# strategy.toml: example values only, not a recommendation schema_version = 1 [risk] max_position = 2 # lots or contracts per symbol daily_loss_limit = 500.0 # in account currency [filters.trend] enabled = true lookback_bars = 200 [filters.session] enabled = false start = "08:00" # HH:MM, UTC end = "16:30"
# load_config.py: validates a strategy configuration at startup.
# Python 3.11+ (tomllib), standard library only.
import hashlib
import json
import re
import sys
import tomllib
SCHEMA_VERSION = 1
DEFAULTS = { # every key the bot knows; a type instead of a value = required, no default
"schema_version": int,
"risk": {"max_position": int, "daily_loss_limit": float},
"filters": {
"trend": {"enabled": False, "lookback_bars": 200},
"session": {"enabled": False, "start": "00:00", "end": "23:59"},
},
}
RANGES = {"risk.max_position": (1, 100), "risk.daily_loss_limit": (0.0, 1e9),
"filters.trend.lookback_bars": (2, 5000)}
def merge(defaults, given, path=""):
"""Effective config = defaults + given values. Unknown keys, missing
required keys and wrong types are errors, never silently ignored."""
out, errors = {}, [f"unknown key '{path}{k}'" for k in given if k not in defaults]
for key, default in defaults.items():
name = path + key
if isinstance(default, dict):
value = given.get(key, {})
if not isinstance(value, dict):
errors.append(f"'{name}' must be a table")
value = {}
out[key], sub = merge(default, value, name + ".")
errors += sub
continue
kind = default if isinstance(default, type) else type(default)
if key not in given:
if isinstance(default, type):
errors.append(f"'{name}' is required")
out[key] = default
continue
value = given[key]
if kind is float and type(value) is int:
value = float(value)
if type(value) is not kind:
errors.append(f"'{name}' must be {kind.__name__}")
out[key] = value
return out, errors
def check(cfg):
errors = [] if cfg["schema_version"] == SCHEMA_VERSION else ["unsupported schema_version"]
for path, (low, high) in RANGES.items():
value = cfg
for part in path.split("."):
value = value[part]
if not low <= value <= high:
errors.append(f"'{path}' = {value} outside {low}..{high}")
s = cfg["filters"]["session"] # this example has no sessions across midnight
if not all(re.fullmatch(r"([01]\d|2[0-3]):[0-5]\d", t) for t in (s["start"], s["end"])):
errors.append("session start and end must be HH:MM")
elif s["start"] >= s["end"]:
errors.append("session start must be before end")
return errors
def config_id(cfg):
canonical = json.dumps(cfg, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:12]
if __name__ == "__main__":
with open(sys.argv[1], "rb") as f:
cfg, errors = merge(DEFAULTS, tomllib.load(f))
errors = errors or check(cfg)
if errors:
sys.exit("config rejected:\n " + "\n ".join(errors))
print(f"config_id={config_id(cfg)}")
print(json.dumps(cfg, sort_keys=True))On success, python3 load_config.py strategy.toml prints a short configuration ID, the first 12 hexadecimal characters of the SHA-256 hash of the effective configuration as canonical JSON, followed by the configuration itself. Both belong in the startup log. Any error ends the program with exit code 1 before a single order is possible.
Switchable filters: feature flags with a tested off state
A filter is an extra condition that can block a signal: a trend filter, a session window, a volatility threshold. Making it optional takes more than an if statement. Pete Hodgson’s article on feature toggles at martinfowler.com distinguishes release, experiment, ops and permissioning toggles. A filter that is still being evaluated resembles an experiment toggle, which Hodgson describes for comparing code paths; a switch that stops new entries in an emergency is an ops toggle of the long-lived “kill switch” kind. The article treats toggles as inventory with a carrying cost: keep their number low and remove the ones that are no longer needed. A retired flag should not come back with a different meaning; new behavior gets a new name.
In code, each filter becomes one function with its own configuration block, and a disabled filter is skipped entirely, including its data requirements. The decision returns the name of the blocking filter, so the log shows why a signal did not trade. Tested with Python 3.9 and 3.12:
# filters.py: each optional filter is one function with its own config block.
def trend_ok(signal, bar, fc):
# bar["sma"]: moving average over fc["lookback_bars"], computed upstream
return (bar["close"] > bar["sma"]) == (signal == "long")
def session_ok(signal, bar, fc):
return fc["start"] <= bar["time_utc"] < fc["end"] # "HH:MM", UTC
FILTERS = {"trend": trend_ok, "session": session_ok}
def apply_filters(signal, bar, cfg):
"""Returns (allowed, name of the blocking filter). Disabled filters are skipped."""
for name, check in FILTERS.items():
fc = cfg["filters"][name]
if fc["enabled"] and not check(signal, bar, fc):
return False, name
return True, NoneThe critical test is the off state. Run the backtest with every filter disabled and compare the trade list with the reference run of the version before the filters existed; the two must be identical. A filter that still changes results when switched off, because it shifts a warm-up period, consumes data or alters a shared indicator, is not switchable. Hodgson recommends testing the toggle configuration that is expected to go live and the fallback with the new toggles off; testing every possible combination is not necessary.
Versioning: tie every result to code and configuration
A backtest result without its configuration cannot be reproduced, and a trade without its configuration cannot be explained. Version the configuration like code:
- Keep configuration files in the same repository as the code, so one commit identifies both.
- Give the file a
schema_version. When the meaning of a key changes, increase it and migrate old files instead of reinterpreting them silently. - Compute the configuration ID from the effective configuration after defaults, not from the file text, so that comments and key order do not change it.
- Save the effective configuration with every backtest report, together with the code commit, the data period and the cost assumptions.
- Treat a configuration change for the live system like a code change: reviewed, tested on paper and deployed at a defined time.
Avoid reloading the configuration while positions are open unless the code was built for it. A risk limit that changes mid-position, or a filter that switches on between entry and exit, creates states that no backtest covered.
Logging the active configuration per backtest and per trade
The configuration ID makes logging cheap. At startup, write the full effective configuration, its ID, the code commit and whether the bot runs against a paper or a live account. Every later event needs only the ID:
- Per backtest: configuration ID, effective configuration, data snapshot and period, costs and slippage model, and a running count of how many configurations were tested in the same study.
- Per signal: configuration ID, the inputs of the decision and, for a blocked signal, the name of the filter that blocked it.
- Per order and fill: configuration ID next to your own order ID, so the trade can be matched to the backtest that justified it.
With this in place, a live trade that looks wrong can be replayed with exactly the settings it ran under, and a backtest report shows at a glance whether it used the same configuration as the live system. Which other fields an order log needs, and how to keep it tamper-evident, is covered in the article on a trading system audit trail.
Risks: more switches, more ways to overfit
Configurability makes experiments cheap, and that is its main risk: one on/off switch gives two variants, five such switches already give 32, and the more configurations are tried, the more likely it is that the best one merely fits the past. In a paper on backtest overfitting, Bailey, Borwein, López de Prado and Zhu show how quickly that happens: for strategies without any real edge, seven independent configurations are enough for the expected best in-sample Sharpe ratio of a two-year backtest to reach 1, while the expected out-of-sample Sharpe ratio is 0. How to count variants and correct for them is covered in multiple testing in backtests.
- Count and log every configuration tested, including the discarded ones.
- Decide which filters are hypotheses before testing them, and keep a period of data out of the search.
- Prefer a few filters with a clear rationale to many switches tuned to history.
Operational risks come on top: the wrong file deployed to the live account, a paper configuration pointing at a live account, a default hiding a missing value, a configuration reloaded mid-position. Validation at startup, the configuration ID in every log line and a check of the connected account catch many of these before an order is sent. Trading involves a risk of loss up to total loss; configuration discipline reduces avoidable errors, not market risk.
What to do next
- List every value in the code that may differ between runs and move it into the configuration file, with unit and allowed range.
- Move credentials and account identifiers into the environment or a secret store.
- Reject unknown keys and missing required keys at startup, and give risk limits no defaults.
- Put each optional filter behind its own flag and test that the off state reproduces the reference run.
- Compute a configuration ID and write it into every backtest report and every order event.
- Log the number of configurations tested per study.
- For Expert Advisors, commit the set-files next to the source code.
If you want the structure checked by someone else, a code review of the trading system covers configuration, versioning and logging alongside the order and risk logic.
Frequently asked questions
How do I make trading bot parameters configurable without changing code?
Move every value that may differ between runs into a configuration file, such as TOML or JSON, versioned next to the code. Load and validate it at startup, rejecting unknown keys, wrong types and out-of-range values, apply defaults explicitly and keep credentials in the environment. Then log a hash of the effective configuration with every backtest and every trade.
What is a feature flag in a trading system?
A feature flag is a switch in the configuration that turns a code path on or off without a new build, for example an optional trend filter or a switch that blocks new entries. Each flag needs a tested off state and a clear purpose, and flags that are no longer needed should be removed, because every flag adds variants to test.
Should risk limits in a trading bot have default values?
Better not. A missing daily loss limit or maximum position size should stop the bot at startup instead of silently falling back to zero, infinity or a value chosen for another account. Defaults suit harmless settings, such as a log level or an optional filter that stays off unless it is enabled.
How do I know which settings produced a trade?
Compute an ID from the effective configuration, for example a SHA-256 hash of its canonical JSON, and write the full configuration with that ID into the startup log. Every signal, order and fill then carries the ID. A trade can be replayed with exactly the settings it ran under, and a backtest report with the same ID shows that test and live used the same configuration.
Does MetaTrader 5 support configuration files for Expert Advisors?
An Expert Advisor’s parameters are its input variables, which the program can only read. The Strategy Tester can save a parameter set as a set-file that can be moved between computers, or keep versions inside the platform. Commit the set-files next to the EA’s source code, so the settings used live are versioned like the code.
Sources and status
- The Twelve-Factor App: III. Config — 12factor.net (retrieved November 19, 2026)
- tomllib: Parse TOML files — Python documentation (Python Software Foundation) (retrieved November 19, 2026)
- Understanding JSON Schema: object (additionalProperties, required) — JSON Schema (retrieved November 19, 2026)
- Understanding JSON Schema: annotations (default) — JSON Schema (retrieved November 19, 2026)
- Input Variables (input, sinput) — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
- Strategy Tester: testing, inputs and parameter sets — MetaTrader 5 Help (MetaQuotes) (retrieved November 19, 2026)
- Feature Toggles (aka Feature Flags), Pete Hodgson (2016, last revised October 9, 2017) — martinfowler.com (retrieved November 19, 2026)
- Pseudo-Mathematics and Financial Charlatanism: The Effects of Backtest Overfitting on Out-of-Sample Performance (Notices of the AMS, May 2014; authors’ version) — D. H. Bailey, J. M. Borwein, M. López de Prado, Q. J. Zhu (carmamaths.org) (retrieved November 19, 2026)
As of November 2026. Third-party rules, prices and APIs may have changed since; the providers' current documentation and the official texts are authoritative.
This article is also available in German: Parameter ändern ohne Neuprogrammierung: Konfiguration bauen.
Want your trading system’s configuration, versioning and logging reviewed? Get in touch — a free intro call clarifies the current structure and what a review would cover. More: Trading system code review and audit.