Disclosure: I'm packaging this project as a paid template. This post is about the engineering, and every technique below works without it. Nothing here is financial advice, and I'm not claiming the strategy is profitable.
I've spent the last few months building a small quant bot in Python that runs on a Debian VM under systemd, scans 100 liquid US stocks every 15 minutes and sends market orders to a Trading 212 practice (demo) account. The strategy is deliberately boring: trend and momentum scoring, a −3 % stop-loss and a trailing stop.
The interesting part was everything around the strategy. Three things bit me, and I suspect they bite most hobby bots:
- Look-ahead bias — using data at decision time that wasn't available yet.
- Non-idempotent execution — the same order going out twice.
- Parameters tuned once and never re-validated.
Here's what I ended up with for each.
1. Point-In-Time (PIT) data: one rule, enforced everywhere
The rule is short:
# Every data point carries the moment it became available. assert item.available_utc <= decision_utc What makes it hard is that "available" is not the timestamp most data sources give you.
Daily candles. A daily bar dated today isn't complete until the session closes. If your bot runs at 15:30 New York time and uses today's daily candle, its "close" is a price from the future. So each candle gets a candle_end_utc, checked against the real NYSE close for that date (holidays and early closes included), and an available_utc that can't be earlier than that close. An incomplete intraday daily candle is rejected, not "used as best effort".
News. A headline's useful timestamp is when it was published, and it must also have been received before the decision. If the provider's publication time can't be verified, the item is rejected.
Stale series. If the latest completed session is missing from a ticker's series, that ticker is excluded from the cycle rather than evaluated on old data.
The design choice I'd recommend most: make every rejection explicit. I ended up with 30+ reason codes:
INTRADAY_INCOMPLETE_DAILY_CANDLE CANDLE_END_UTC_MISMATCH_WITH_NYSE_CLOSE CANDLE_SESSION_IS_HOLIDAY STALE_DAILY_SERIES_MISSING_LATEST_SESSION UNVERIFIABLE_PROVIDER_PUBLICATION_TIME EVENT_AFTER_RECEIPT RETROSPECTIVE_CAPTURE_AFTER_DECISION ... "The bot didn't trade today" tells you nothing. "14 tickers excluded with STALE_DAILY_SERIES_MISSING_LATEST_SESSION" tells you the data provider had a bad morning.
The same validator also checks the portfolio snapshot: used + reserved + available capital must add up to the configured cap, no position may exceed the per-position cap, and there can be at most 10 open positions. A snapshot that fails is rejected, not patched.
Finally, the backtester and the live loop share the same definition of "available". If your backtest is looser than production, you're testing a different system from the one you run.
2. Idempotent and fail-closed order execution
The naive loop looks like this:
strategy says BUY AAPL → POST order → timeout (did it fill?) → next cycle: BUY AAPL again My executor runs three checks before any buy:
- Read the broker portfolio (
GET /equity/portfolio). If the ticker is already held, the buy is blocked. The broker is the source of truth. - Read the local order log. Orders I submitted that aren't in the portfolio yet still count, so broker lag can't cause a duplicate.
- If the portfolio can't be read, block the buy.
Number 3 is the one I got wrong. My first version looked roughly like this:
def get_open_positions(): try: resp = session.get(PORTFOLIO_URL, timeout=15) if resp.ok: return resp.json() return [] # ← HTTP 429? "you hold nothing" except Exception: return [] # ← DNS failure? "you hold nothing" An empty list means "no positions", so the duplicate check passes and the total-capital check sees 0 € invested. A transient network error quietly turns every safety guard off. That's fail-open.
The fix is to make "I don't know" a distinct state:
class PortfolioUnavailableError(RuntimeError): pass def get_open_positions(strict: bool = False): try: resp = session.get(PORTFOLIO_URL, timeout=15) if resp.ok and isinstance(data := resp.json(), list): return data raise PortfolioUnavailableError(f"HTTP {resp.status_code}") except PortfolioUnavailableError: if strict: raise return [] except Exception as exc: if strict: raise PortfolioUnavailableError(type(exc).__name__) from exc return [] # in the executor if action in ("BUY", "INCREASE"): try: positions = get_open_positions(strict=True) except PortfolioUnavailableError as exc: return block("PORTFOLIO_NOT_VERIFIABLE", reason=str(exc)) # persisted for audit Some details that matter:
- Exits are treated differently. Missing a buy because the broker is flaky costs nothing. Being unable to even attempt a stop-loss exit is worse, so sells don't go through the same block.
- The caller has to cooperate too. My cycle runner read the portfolio once at the start and passed the list down. After a failed read it was passing
[], which skips the executor's own check. Now it passesNone, which forces the executor to fetch again, strictly. - Blocked orders are logged just like sent ones. The "no"s are as important to audit as the "yes"es.
- Expect a test to break. When I fixed this, an existing test that "successfully placed a buy" started failing. Its mock returned garbage for the portfolio call and the buy only went through because of the fail-open bug.
The tests I added cover HTTP 429, 503, network errors, timeouts, a non-list JSON body, a verified empty portfolio (buy allowed) and a verified portfolio that already holds the ticker (buy blocked).
3. Top-K ranking and Walk-Forward tuning
Top-K. Candidates aren't bought in scan order. Each cycle collects every candidate, ranks them by conviction and expected return, then fills slots top-down: at most 10 positions, minimum lot 50 €, lot capped by the per-position limit and by free capital. Every skipped candidate is logged with its reason.
Walk-Forward. Once a month a systemd timer runs the optimizer:
- Take the last 60 sessions.
- Split them: the first 75 % in-sample, the last 25 % out-of-sample.
- Grid-search lot sizes and trailing-stop parameters on the in-sample part only (198 combinations at "coarse" resolution).
- Re-run the best in-sample configuration on the out-of-sample part.
The fitness function penalises risk and costs:
fitness = net realized PnL − 1.5 × max drawdown − frictions (FX fees + slippage) And the part I think matters most, the adoption gate. 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.
Otherwise the current parameters stay. Most months "no change" is the right answer, and the system is designed to accept that.
Operational lesson. The optimizer once failed on a DNS error while fetching data, and since it was a monthly timer, it simply didn't run again for a month. The unit now has Restart=on-failure, RestartSec=30min, StartLimitBurst=3 and the timer has Persistent=true, so it retries and catches up after a reboot.
What I'd tell anyone building one
- Make time a first-class field:
available_utcon everything, checked against a real market calendar. - Give every rejected data point and blocked order a reason code.
- Treat "I don't know the state" as its own state, and never let it become "empty".
- Test the failure paths (429, timeouts, bad payloads), not just the happy path.
- Re-tune parameters on a schedule, but make adoption hard.
- Use the same validation code in backtest and live.
Known limitations (being honest)
- It runs against the demo environment only.
- Market data comes from Yahoo Finance via
yfinance, which is unofficial and has no SLA. - The engine supports news sentiment, but no news provider is wired in by default.
- Position values for capital caps use quantity × average price from the broker, with no FX conversion.
I've open-sourced a small, dependency-free version of the two guards (PIT checks + fail-closed portfolio reads, 27 tests, MIT): https://github.com/Manelofthh/pit-guard
Happy to answer questions about any of it — especially if you've solved the PIT problem for news differently.
I've packaged the full project as a self-hosted template (Python 3.12+, systemd installer, 91 offline tests, EN/ES docs, demo-only): https://buy.stripe.com/7sY28k1mGgsh6LH8MJdby01. It's an engineering template, not financial advice, and comes with no promise of returns.