Every 15 minutes my bot scans 100 liquid US stocks. On most cycles several of them look like buys. It can hold at most 10 positions. Two questions follow: which candidates win, and who decides the parameters, me once, or the data every month?
This post covers both: Top-K ranking for the first, Walk-Forward optimization with a strict adoption gate for the second. The bot runs against a Trading 212 practice (demo) account; nothing here is a claim that the strategy makes money. It's about making parameter changes boring and safe.
Part 1: don't buy in scan order
The naive loop:
for ticker in universe: if signal(ticker) == "BUY" and free_slots > 0: buy(ticker) This buys whatever comes first in your list. List order is not a strategy. If AAPL is first alphabetically, it gets priority every single cycle.
The fix is to separate collecting from allocating:
candidates = [score(t) for t in universe] candidates = [c for c in candidates if c.action == "BUY"] candidates.sort(key=lambda c: (c.conviction, c.expected_return), reverse=True) for c in candidates: lot = min(MAX_POSITION_EUR, free_capital) if open_positions >= 10: skip(c, "SLOTS_FULL") elif lot < 50: skip(c, "FREE_CAPITAL_BELOW_MIN_LOT") else: buy(c.ticker, lot) Hard constraints, in order: at most 10 open positions, minimum lot 50 €, lot capped by the per-position limit and by free capital. Every skipped candidate gets a reason, so you can see when the bot is capital-bound versus signal-bound.
Exits are plain rules: a −3 % stop-loss, and a trailing stop that arms at +4 % and closes if the gain falls back to +2 %. That +4/+2 pair, along with lot sizes, is what the optimizer is allowed to touch.
Part 2: why not tune once?
Parameters fitted to last year's trend can be wrong in this year's chop. But "re-tune on all the data every month" is just overfitting on a schedule. Walk-Forward sits in between: tune on one window, judge on the next one, which the tuner never saw.
Once a month (a systemd timer, first Sunday 00:00 UTC):
- Take the last 60 sessions.
- First 75 % = in-sample, last 25 % = out-of-sample.
- Grid-search lot sizes and trailing parameters on the in-sample part only (198 combinations in "coarse" mode).
- Re-run the best in-sample configuration on the out-of-sample part.
Part 3: the fitness function
Raw profit is a bad objective. It rewards configurations that made a bit more with a much deeper drawdown, and ignores costs. I use:
fitness = net realized PnL − 1.5 × max drawdown − frictions (FX fees + slippage) The 1.5 weight is a choice, not a law. The point is that drawdown and costs are part of the score, not a footnote you look at afterwards.
Part 4: the adoption gate (the important part)
Finding a "best" configuration is easy; the grid always has a winner. The question is whether to use it. New parameters go live only if, out of sample:
- net PnL > 0,
- profit factor ≥ 1.10,
- fitness ≥ the current baseline's fitness on the same out-of-sample window.
def adopt(candidate_oos, baseline_oos) -> bool: return ( candidate_oos.net_pnl > 0 and candidate_oos.profit_factor >= 1.10 and candidate_oos.fitness >= baseline_oos.fitness ) Fail any condition and the current parameters stay. Comparing against the baseline on the same window matters: a candidate that's positive but worse than what you already run isn't an improvement.
Most months the answer is "no change". That's not the optimizer failing; that's the gate doing its job. A system that changes parameters every month is usually fitting noise.
Part 5: make it survive the real world
The optimizer once failed on a DNS error while downloading data. Because it was a monthly timer, it simply didn't run again for a month and nobody noticed. Now the unit has:
[Service] Restart=on-failure RestartSec=30min [Unit] StartLimitBurst=3 [Timer] OnCalendar=Sun *-*-01..07 00:00:00 UTC Persistent=true It retries up to three times, 30 minutes apart, and Persistent=true makes a missed run catch up after a reboot. For a job that runs twelve times a year, retry logic isn't optional.
Takeaways
- Collect all candidates, then rank, then allocate under hard constraints.
- Log why every candidate was skipped.
- Tune in-sample, judge out-of-sample, never both on the same data.
- Put drawdown and costs inside the fitness function.
- Adopt new parameters only if they're positive, robust (PF ≥ 1.10) and beat the baseline out of sample.
- Treat "no change" as a successful month.
- Give rare scheduled jobs retries and catch-up.
The PIT and fail-closed parts of this bot are open source: https://github.com/Manelofthh/pit-guard
The full template (Top-K, Walk-Forward optimizer with the adoption gate, backtester with spread/slippage/FX costs, systemd installer, 91 offline tests, Trading 212 demo API) is InversionBot V4: https://buy.stripe.com/7sY28k1mGgsh6LH8MJdby01. It's an engineering template, not financial advice, and makes no promise of returns.

