Trading Agents
MetaTrader 5 trading agents and a research harness honest enough to say no.
- Quant & trading
- Multi-agent systems
- Role
- Sole engineer and researcher
- Client
- Personal project (own prop-firm challenge attempt)
- Timeline
- Mar - Aug 2026
- Status
- Research

- automated tests
- 451
- automated tests
- commits, Mar - Aug 2026
- 170
- commits, Mar - Aug 2026
- strategy ideas tested and killed
- 14
- strategy ideas tested and killed
- blend: backtest Sharpe, then live-demo profit factor
- 3.55 → 0.27
- blend: backtest Sharpe, then live-demo profit factor
- modelled FTMO pass rate after the selection-bias test
- 90% → 52%
- modelled FTMO pass rate after the selection-bias test
The problem
Prop firms such as FTMO sell challenges: grow a $100k account by 10% without breaking a 5% daily or 10% total loss limit, and you get funded. Most retail strategies fail, and most retail backtests overstate their edge through look-ahead bias, ideal fills, ignored spread and swap, and selection bias.
The goal was two things: an execution bot that cannot break the firm's rules even when the broker connection drops, and a research process strict enough to tell a real edge from a backtest artifact before paying a challenge fee.
Architecture
Bar close, closed bars only
At each M15 close the executor pulls closed bars only and skips data older than 25 minutes. LiveTrader computes causal indicators and routes them to the enabled strategies.
- Service
- Data
- AI model
- External
Hard problems I solved
A self-audit for look-ahead leakage
The March README claimed 15, 14 and 16 of 19 walk-forward windows passing on EURUSD, GBPUSD and USDJPY. A self-audit on 22 May found that _vectorized_swing_structure used highs.shift(-1) and shift(-2), so the H4 structure flag at bar t could see two future bars.
Approach. Swings are now confirmed at t-2 using only bars up to t, and a mutation test perturbs every bar after a cutoff and asserts earlier outputs are identical. The same audit moved Sharpe to R-multiples, added 0.5-pip slippage on entry and exit, and added a live/backtest equivalence test.
The then-current strategy dropped from 3, 3 and 12 passing windows to 1, 2 and 8 of 19. The fix made the numbers worse and was kept.
A Sharpe 3.55 backtest that lost on demo
A two-strategy blend (imbalance-zone continuation plus H4 stop-cluster fade) backtested at Sharpe 3.55, with daily-return correlation between the legs of -0.03 to +0.03 and lower drawdown than either leg alone.
Approach. Before any funding: cost stress from 0.5 to 3 pips of slippage, an 818-entry live-vs-backtest parity check, shipped off by default and run on a demo account first.
Live demo, 1-3 June: profit factor 0.27, -1.07%. The +0.09R per-trade edge did not survive real costs; the blend was abandoned and logged as falsified.
An accounting artifact in a stat-arb engine
A pairs/basket strategy showed +0.677R per trade out of sample. Three days into a live demo, an exit at 'target' lost money.
Approach. Traced to backtest P&L computed as Σ pos·Δspread with β re-estimated every bar, which adds an unrealizable -Δβ·logB term: the spread is redefined each bar and mechanically mean-reverts. Re-accounted on tradable legs, and a leg-level P&L cross-check became a standing rule. The same demo exposed a hedging-mode close bug that opened ghost positions, also fixed.
Edge on tradable legs: -0.007R per trade. Strategy killed.
A Monte Carlo that respects concurrent positions
The first FTMO Monte Carlo bootstrapped trades as independent. A trend book actually held about 18 correlated positions at once (29 at peak), so drawdowns arrived together.
Approach. A mark-to-market portfolio engine that values every open position each step, under two intraday-low conventions, with shared-index bootstrap, path-dependent drawdown sizing, regime splits and leave-one-out attribution. B=20,000 with a pinned seed.
P(pass within 6 weeks) fell from about 56% under the naive model to 0.36%, with 12.67% bust. Killed; a risk-parity follow-up was killed too.
Testing the best result for selection bias
The Connors RSI2 daily book backtested at 70% win rate, +0.2335R per trade, PF 1.72 and about 90% modelled FTMO pass. It traded 7 of the 10 FX pairs in the data store.
Approach. The identical code ran on FX crosses that were never candidates, with cost removed as a control and a power check, then a permutation test of picking the best 7 of 10 pairs from a zero-edge pool.
Out of universe: -0.0361R (t=-0.42) against +0.2165R (t=+2.64) on the book's pairs. Selection explains about half the edge; selection-adjusted pass rate is 52%. Written verdict: do not fund a real challenge on this book.
A disconnect that looked like a -100% drawdown
On 25 July the live demo halted with 'TOTAL -10% breached (-100%)' without losing anything. account_info() had returned equity=0 when MT5's IPC pipe dropped, and the kill switch believed it.
Approach. Every broker read now raises instead of returning a plausible default. A connection probe tells 'genuinely flat' from 'terminal dead', so reconciliation cannot mark live trades closed. Reconnect refuses a terminal logged into a different account, with retries every 5 minutes and hourly Telegram alerts.
Code
The old version used shift(-1) and shift(-2), so the flag at bar t saw two future bars. The test turns that whole class of bug into a red build instead of a good-looking backtest.
# standard.py: a 5-bar swing at t-2 can only be confirmed at t
swing_high_conf = (
(highs.shift(2) > highs.shift(4))
& (highs.shift(2) > highs.shift(3))
& (highs.shift(2) > highs.shift(1))
& (highs.shift(2) > highs)
)
swing_high_vals = highs.shift(2).where(swing_high_conf)
# test_swing_no_leakage.py: mutate the future, the past must not move
def test_swing_structure_no_lookahead():
df = _synthetic_h4(seed=1)
bull_full, bear_full = _vectorized_swing_structure(df)
cutoff = 400
df_mut = df.copy()
df_mut.iloc[cutoff + 1 :, :] = df_mut.iloc[cutoff + 1 :, :] * 1.05
bull_mut, bear_mut = _vectorized_swing_structure(df_mut)
pd.testing.assert_series_equal(
bull_full.iloc[: cutoff + 1].reset_index(drop=True),
bull_mut.iloc[: cutoff + 1].reset_index(drop=True),
check_names=False,
)def _positions_or_raise(self, **kwargs):
"""positions_get() returns None on error, and on some builds when flat.
Distinguish the two with a connection probe."""
positions = self._mt5.positions_get(**kwargs)
if positions is not None:
return positions
if self._mt5.account_info() is not None:
return () # connected and genuinely flat
if not self._reconnect():
raise ConnectionError(
f"MT5 disconnected while reading positions "
f"(last_error={self._mt5.last_error()})"
)
return self._mt5.positions_get(**kwargs) or ()
async def get_account_info(self) -> dict:
info = self._mt5.account_info()
if info is None:
# A dropped terminal must NOT look like a zeroed account: callers
# size risk and trip loss kills off these numbers, and equity=0
# reads as a -100% drawdown. Reconnect, or fail loudly.
info = self._mt5.account_info() if self._reconnect() else None
if info is None:
raise ConnectionError("MT5 account_info() unavailable: terminal disconnected")
return {"balance": info.balance, "equity": info.equity, "margin_free": info.margin_free}can_trade, risk_reason = self.risk.can_trade(pair, direction) # Gate 1
if not can_trade:
return {"decision": "SKIP", "reason": risk_reason}
desired_lot = self.risk.calculate_lot_size(signal["sl_pips"], pair_config, risk_pct_override)
allowed_lot, clip_reason = self.risk.clamp_lot_for_exposure( # Gate 1.5: clip, don't reject
pair, direction, desired_lot, positions)
cal = self.calendar.check(pair) # Gate 2: Forex Factory
sent = self.sentiment.analyze(headlines, pair) # Gate 3: LLM, logged only
conf = self.confirmation.check(signal, h4_data, spread, spread_avg) # Gate 4
if cal["status"] == "BLOCKED":
return {"decision": "WAIT", "reason": reason, ...}
if conf["status"] == "REJECTED":
return {"decision": "SKIP", "reason": reason, ...}
# Sentiment is ADVISORY only as of 2026-05-23 (per agents-review doc).
# ... the historical bot showed 0.35 -> -0.65 -> -0.15 noise on identical
# headlines. Veto was probably rejecting more good trades than bad ones.
if cal["status"] == "CAUTION" or conf["status"] == "WEAK":
return {"decision": "EXECUTE_REDUCED", "lot_size": round(allowed_lot * 0.5, 2), ...}
return {"decision": "EXECUTE", "lot_size": allowed_lot, ...}What I built
Live execution on MT5
- Async M15 bar-close loop routing three strategies (ZLEMA momentum, imbalance-zone, H4 stop-cluster fade) plus a daily Connors runner
- MT5Executor: market and pending limit orders, filling-mode negotiation (error 10030), stop clamping (error 10016)
- SQLite state for positions, pending orders and risk, reconciled against the broker before any trade
- Telegram alerts and a narrated per-bar decision log, so a day with no trades can be explained
Agents and risk
- Deterministic orchestrator: risk, currency exposure, calendar, confirmation, then EXECUTE, REDUCED, WAIT or SKIP
- Forex Factory calendar agent (JSON API, HTML fallback) and a 7-check confirmation agent
- LLM headline sentiment with a 15-minute hash-keyed cache, JSON-only replies and neutral fail-open
- Kill switches: daily loss, total loss, 3-day drawdown breaker, Friday flatten, USD-weighted exposure clip
Research harness
- Bar-by-bar backtester with half-spread per side, 0.5-pip slippage and pending-limit fill simulation
- Walk-forward over 19 rolling windows per pair (12-month in-sample, 3-month out-of-sample, 2020-2025)
- Concurrency-aware FTMO Monte Carlo with regime splits and leave-one-out attribution
- 47 strategy generators over 271 Parquet datasets: FX, metals, indices, crypto, US stocks
Research discipline
- A pre-registration with a kill bar before each test, a mechanical verdict script after it
- Strategy ledger tagging every idea by mechanism, horizon, market and regime
- Look-ahead mutation tests and live/backtest equivalence tests
- MT5 broker-truth recorder for real M15 bars, spreads and swaps
Screens
Out-of-sample Sharpe for all 19 windows, before and after the 22 May audit. Drawn from the repo's own walk-forward logs.
The selection-bias test on the best book: out-of-universe edge, permutation-adjusted edge and the modelled pass rate that followed.
Stack
Data and quant
- Python 3.12
- pandas
- numpy
- scipy
- pyarrow (Parquet)
Execution
- MetaTrader5 Python API
- asyncio
- SQLite
- python-telegram-bot
Agents
- Anthropic SDK (MiniMax-M2.7 endpoint)
- BeautifulSoup fallback
- pydantic-settings
Research
- Custom bar-by-bar backtester
- QuantStats
- vectorbt (early runner)
- plotly
- matplotlib
Quality
- pytest
- pytest-asyncio
- loguru
- Mutation tests for look-ahead
How it was built
Built solo with an AI-native workflow: I set the research questions and kill bars and made every fund-or-kill call, and Claude Code implemented (136 of 170 commits carry its co-author trailer). The gates are mine: 451 tests, look-ahead mutation tests, live/backtest parity checks and a demo run before any money.
The repository is private, and account numbers, broker logins and server names are withheld.