How do you connect an agent’s proposals to MT5 demo orders so every order passes code checks and a human? This post builds the level-2 flow: ten checks in code, approval over Telegram, a send step with its own magic number, a four-layer kill switch, and seven drills that deliberately break things.
One rule runs through all of it. A blocked proposal is skipped. Don’t loosen a limit mid-session; change it outside trading hours and rerun the drills.
Terms used below:
- Level 2 and level 3: steps on an autonomy ladder. Level 2: the agent proposes, code checks, you approve each demo order. Level 3: no per-order approval but every check stays, demo only, after conditions you wrote in advance are met.
- Pre-trade check: code checks that run right before an order: demo account, symbol, SL, TP, lot, spread, position count, daily loss, news window. One failed line means no order.
- Kill switch: an emergency stop that disables trading the moment it’s on, usually blocking new orders and cancelling pending ones. This post has four layers, from a STOP file to closing the terminal.
- Fail-safe: on a network error, API error or unclear state, the system does nothing more: no new orders, and SL/TP already attached stay put.
- Magic number: an ID attached to every order a program sends (the
magicfield). The agent’s orders use their own number, so they’re separate from your manual orders when counting positions and reconciling. - retcode: the result code the server returns after
order_send; 10009 (TRADE_RETCODE_DONE) means done. A passingorder_checkreturns 0 with the comment “Done”. - Reconciliation: comparing your records (log, Telegram messages) with what MT5 actually holds, by ID, before you conclude or do anything else; it prevents duplicate orders.
- Long polling and
chat_id: long polling means the program callsgetUpdateswith a wait time and the server holds the connection until a message arrives or time runs out.chat_ididentifies a conversation; the bot accepts commands only from yours. - Drawdown: the share of equity lost from the previous peak. After a drawdown x (as a decimal: 20% is 0.2) you have 1 − x left, so you need a gain of x ÷ (1 − x) to get back: 20% needs 25%, 50% needs 100%.
- Monte Carlo simulation: running thousands of random trade sequences under assumed probabilities and counting how many hit a threshold; a fixed seed makes the rerun identical.
One path from proposal to demo order
At level 2 every demo order goes through exactly six steps. The agent only
does step 1: it writes a JSON proposal (the shadow-mode format) into
proposals/. From step 2 on it’s code you’ve read, and you.
| Step | Who | What | Logged in logs/flow.jsonl |
|---|---|---|---|
| 1. Propose | Agent | Writes JSON into proposals/; no lot, no ID |
RECEIVED, or DUPLICATE if the ID exists |
| 2. First check | Code: pre_trade_check |
Ten conditions; lot computed by code, rounded down | BLOCKED with reasons, or continue |
| 3. Approve (level 2 only) | You, on Telegram | Read the summary, look at the chart yourself, send /approve or /cancel with the ID in time |
AWAITING_APPROVAL, then APPROVED, CANCELLED, EXPIRED or STOP |
| 4. Second check | Code | Fresh prices and the STOP file; lot no larger than what you approved | STOP or BLOCKED, or continue |
| 5. Send | Code: send_demo_order |
order_check then order_send, own magic number, comment ai-<id>; never resends |
SENT, then FILLED, REJECTED or UNKNOWN |
| 6. Reconcile | You and reconcile |
MT5 against the log and Telegram by ID, at the end of each day and immediately after any UNKNOWN |
Conclusion in your journal |
Level 3 drops step 3 but keeps every check, adds a daily order cap and a rehearsed kill switch. This post runs level 2; level 3 is only prepared, and switched on (on demo) only when your written conditions are met.
Three principles hold at every level:
- The agent can’t send orders. It has no tool that calls
order_sendand never runs the sending script. You run the flow yourself in a separate PowerShell window. - SL and TP sit on the order at the server. A trailing stop runs inside the platform, so it stops working when the platform is closed, unlike SL and TP. Don’t hand exits to the agent or to trailing.
- Fail-safe. API errors, a lost connection, odd data or an unclear state mean no new orders.
Why so strict? On 1 August 2012, in the first 45 minutes of trading, Knight Capital’s order router sent more than 4 million orders while working 212 customer orders. The firm lost more than 460 million USD and was later fined 12 million USD for inadequate risk controls on market access. Before the open, an internal system had sent 97 error emails that nobody acted on; they weren’t designed as alerts, so they usually went unread. Logs and messages aren’t enough. Someone has to read them, stop conditions must be written down, and the stop switch must have been tested.
Giving a model-driven system too much functionality, permission or autonomy is “excessive agency”. The defences are human approval for high-impact actions and authorisation checks in the downstream system rather than trust in the model’s judgment. Automated-trading risk controls apply to new technology such as AI as well; this post scales them down to one person. The agent doesn’t know the future and can be wrong, so the safeguards live in code, not in instructions to the agent.
Preparation: a demo-only terminal, MT5 switches, limits and agent rules
Open File Explorer, go to C:\trading-agent-lab, right-click an empty spot and
choose Open in Terminal; the prompt should read PS C:\trading-agent-lab>. (A
“terminal” in MT5 terms is the MT5 program, not this window.) Every Python
command calls .venv\Scripts\python directly, so there’s no need to activate
the virtual environment. The MetaTrader5 package is Windows-only; on a Mac
use a Windows VM or VPS.
Step 1: an MT5 terminal used only for demo. If this machine has never
logged in to a live account, use the existing terminal. If it has, install a
second copy: run the MT5 installer, click Settings, set Installation folder to
C:\MT5-Demo, and open that copy when it’s done. Each copy needs its own
folder; two can’t share one.
Log in with File → Login to Trade Account, using the login, master password and server of the DEMO account. The master password gives full control of the account, so type it only in this dialog, never in code, prompts or chat. Read- only work used the investor password; this flow sends demo orders, so it needs the master. Read-only scripts and MCP servers that stop when they detect a master login will stop here, by design; don’t change them. The Python library attaches to the logged-in terminal and uses no API key, so no key anywhere in this flow can withdraw or move money.
Expected: the demo terminal is open and logged in to the DEMO account.
Step 2: switches. Tools → Options (Ctrl+O), Expert Advisors tab:
- Untick “Disable automatic trading through the external Python API”. It’s ticked by default for safety. Untick it only in this demo terminal.
- Tick “Disable automated trading when switching accounts” if it isn’t. It blocks EAs and scripts from trading after an account switch, such as demo to live. It isn’t documented whether it covers Python, so the code checks for a demo account before every order anyway.
- Click OK, then turn on the AutoTrading button on the toolbar (newer builds may call it Algo Trading).
Expected: the Python API box unticked, the account-switch box ticked, AutoTrading on.
Step 3: check with a script. With several MT5 terminals installed, set
TL_MT5_PATH to the demo terminal’s executable first (right-click the demo
terminal’s icon → Open file location → right-click the selected file → Copy as
path). The variable only lives in the current PowerShell window, so set it in
the flow and reconciliation windows too.
cd C:\trading-agent-lab
New-Item -ItemType Directory -Force config, proposals, logs, reports
if (-not (Test-Path src\__init__.py)) { New-Item -ItemType File src\__init__.py }
notepad src\check_terminal.py
notepad config\limits.json
.venv\Scripts\python -m src.check_terminalOnly with several terminals:
$env:TL_MT5_PATH = "[PATH FROM COPY AS PATH]"
.venv\Scripts\python -m src.check_terminalsrc/check_terminal.py:
"""Quick check of the attached terminal: folder, connection, AutoTrading button, account type."""
import os
import MetaTrader5 as mt5
path = os.environ.get("TL_MT5_PATH", "").strip('"') # only needed with several terminals installed
if not (mt5.initialize(path) if path else mt5.initialize()):
raise SystemExit("initialize() error: " + str(mt5.last_error()))
try:
t, a = mt5.terminal_info(), mt5.account_info()
if t is None or a is None:
raise SystemExit("Could not read terminal or account info: " + str(mt5.last_error()))
print("Terminal folder :", t.path)
print("Connected :", t.connected)
print("AutoTrading :", t.trade_allowed)
print("tradeapi_disabled:", t.tradeapi_disabled)
print("Demo account :", a.trade_mode == mt5.ACCOUNT_TRADE_MODE_DEMO)
finally:
mt5.shutdown()Expected (the folder depends on your machine):
Terminal folder : C:\MT5-Demo
Connected : True
AutoTrading : True
tradeapi_disabled: False
Demo account : TrueIn MetaTrader5 5.0.6231, ACCOUNT_TRADE_MODE_DEMO is 0. The
tradeapi_disabled field appears in the documentation’s example without
explanation; its name suggests the Python API box. Check it yourself: tick,
untick and rerun.
Step 4: the limits file config/limits.json. JSON is strict: no comments,
no trailing comma after the last item, straight quotes, Windows paths with
doubled backslashes. The numbers are examples; set your own before running
and write the reasons in your journal.
{
"level": 2,
"magic": 26111101,
"demo_terminal_folder": "C:\\MT5-Demo",
"broker_symbol": {"XAUUSD": "XAUUSD", "EURUSD": "EURUSD", "BTCUSD": "BTCUSD"},
"lot_cap": {"XAUUSD": 0.05, "EURUSD": 0.10, "BTCUSD": 0.05},
"max_spread": {"XAUUSD": 0.50, "EURUSD": 0.00020, "BTCUSD": 60.0},
"max_price_drift": {"XAUUSD": 2.0, "EURUSD": 0.0005, "BTCUSD": 150.0},
"max_positions": 1,
"daily_loss_percent": 2.0,
"max_orders_per_day": 3,
"approval_minutes": 10,
"max_proposal_age_minutes": 30,
"deviation_points": 20,
"filling": "RETURN",
"max_consecutive_errors": 3,
"news_windows_utc": [["2026-11-13 13:15", "2026-11-13 14:15"]]
}- Spread and price drift are in price units: 0.50 for gold is 0.50 USD, 0.00020 for EURUSD is 2 pips. Measure your demo broker’s normal spread for a few days before setting the cap.
news_windows_utcholds start/end pairs in UTC that you fill in each morning from the economic calendar. The sample line only shows the format; it isn’t a real calendar.max_proposal_age_minutesblocks proposals older than that, so a file forgotten inproposals/can’t become an order.- Change
broker_symbolif your broker names symbols differently, for example with a suffix. initialize()without a path finds a terminal on its own and may even launch one. So the flow and reconciliation also readTL_MT5_PATH, compare the attached terminal’s folder withdemo_terminal_folder, and stop if they differ.
Step 5: block the agent from editing control files. Merge into your
existing .claude/settings.json (don’t create a second deny or ask key).
Change the old Edit(./config/...) line to Edit(./config/**), add Edit
lines for the files in src/ and logs/, and keep everything else, including
mcp__terminal__trade_*, which blocks MT5’s own order tool if you ever
connected that server. Without it the agent has a second, unchecked way to
place orders.
{
"permissions": {
"defaultMode": "default",
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Edit(./config/**)",
"Edit(./AGENTS.md)",
"Edit(./CLAUDE.md)",
"Edit(./src/__init__.py)",
"Edit(./src/lot.py)",
"Edit(./src/lot_mt5.py)",
"Edit(./src/check_proposal.py)",
"Edit(./src/pre_trade_check.py)",
"Edit(./src/telegram_approve.py)",
"Edit(./src/send_demo_order.py)",
"Edit(./src/flow_level2.py)",
"Edit(./src/reconcile.py)",
"Edit(./logs/**)",
"mcp__mcp-tradingview__delete_*",
"mcp__terminal__trade_*",
"Read(~/.openbb_platform/**)",
"mcp__openbb__install_skill",
"mcp__openbb__run_pipeline",
"mcp__openbb__openbb_dispatch",
"mcp__openbb__openbb_batch_dispatch"
],
"ask": [
"mcp__mcp-tradingview__create_*",
"mcp__mcp-tradingview__get_active_watchlist",
"mcp__mcp-tradingview__update_*",
"mcp__mcp-tradingview__add_to_watchlist",
"mcp__mcp-tradingview__remove_from_watchlist",
"mcp__mcp-tradingview__stop_alerts",
"mcp__mcp-tradingview__restart_alerts",
"mcp__coingecko__execute"
]
},
"autoMemoryEnabled": false,
"env": {
"PYTHONUTF8": "1"
}
}Save, then type /permissions in Claude Code. Expected: Read(./.env),
mcp__terminal__trade_*, mcp__openbb__install_skill,
mcp__openbb__run_pipeline and mcp__coingecko__execute are all still there.
If you never connected OpenBB or CoinGecko, keeping their lines does no harm.
Edit rules block every Claude Code file-editing tool, but they don’t stop a
script that opens a file itself, and rules on shell commands aren’t a security
boundary. The real safeguards are three: the agent session stays in Manual and
you answer No when it asks to run the flow or delete STOP; an order only goes
when /approve comes from your Telegram; and the code itself checks for a demo
account.
Add to the end of AGENTS.md yourself (the agent can’t edit it):
## Demo order flow
- The agent only writes JSON proposals into proposals/, in the shadow decision format; no lot, no extra fields.
- The agent does not run src/flow_level2.py, src/send_demo_order.py or src/reconcile.py, and never deletes the STOP file.
- To change a limit or the check code, propose it only; I edit, commit and rerun the drills myself.The pre-trade check: ten conditions, one failure means no order
pre_trade_check takes the agent’s JSON and returns pass or fail with
reasons, the lot and the USD risk. Its data comes from three places: balance,
prices and symbol specs from MT5; limits from config/limits.json; the 1%
risk from RISK_PERCENT in src/check_proposal.py.
From the proposal, code takes only symbol, side, entry, SL and TP; it never
reads a lot. It computes the lot two ways and takes the smaller: the fixed
convention in check_proposal (USD per lot per 1.0 price move), and the
broker’s own specification in lot_by_broker, with the SL distance measured
from the current price. Then it caps by the symbol’s lot cap and rounds DOWN to
volume_step; below volume_min, no trade.
Several lines are one-person versions of standard automated-trading controls:
a maximum size per order, a position limit, a price collar against a
reference price, and sanity checks on price data such as the bid/ask spread.
Orders for a symbol without a configured size cap should be blocked, so a
symbol missing from the config fails. A position read error (positions_get
returning None) also fails; it’s never read as zero positions.
A worked example with made-up prices: demo balance and equity 1,000 USD, so 1% is 10 USD. The agent proposes XAUUSD BUY, entry 4000.00, SL 3995.00, TP 4010.00.
- Prices: at check time ask 4000.50, bid 4000.20 (ask is what you buy at, bid what you sell at). Spread 0.30, under the 0.50 cap; price is 0.50 from entry, under the 2.0 drift limit.
- Fixed-convention lot: 10 ÷ (5 × 100) = 0.02. This measures SL from the agent’s entry: 4000.00 − 3995.00 = 5 USD.
- Broker lot, 1 lot = 100 oz: a market buy fills at the ask (4000.50), not at 4000.00, so the real loss at SL is measured from the ask: 5.50 USD, or 550 USD per lot. 10 ÷ 550 = 0.018, rounded down to 0.01.
- The smaller: 0.01 lot, real risk 5.50 USD. It passes and goes to approval.
The function runs twice: before the approval message, and right before
order_send. The second run matters because price, spread, position count and
the STOP file can all change while you read the message.
| # | Check | How the code does it | If it fails |
|---|---|---|---|
| 1 | Demo account | account_info().trade_mode equals ACCOUNT_TRADE_MODE_DEMO; a read error also fails |
Block |
| 2 | Connection, AutoTrading | terminal_info().connected and trade_allowed both True |
Block |
| 3 | Valid, fresh proposal | check_proposal: allowed fields only, allowed symbol, numeric entry and SL, SL on the right side; time_utc no older than max_proposal_age_minutes |
Block, naming the field or reason |
| 4 | TP and symbol limits | TP numeric and on the right side; config has broker_symbol, lot_cap, max_spread, max_price_drift for the symbol |
Block |
| 5 | Spread | ask − bid not above max_spread |
Block |
| 6 | Price drift and SL | Current price within max_price_drift of entry; SL still on the right side and not closer than the broker minimum (trade_stops_level) |
Block |
| 7 | Agent positions | positions_get, count positions with the agent’s magic, must be under max_positions; a read error fails |
Block |
| 8 | Daily loss | Start-of-day equity (UTC day, stored in logs/) minus current equity, against daily_loss_percent |
Block until the day ends |
| 9 | News window | Current UTC time inside a pair in news_windows_utc |
Block |
| 10 | Order count and lot | Orders sent today under max_orders_per_day; final lot not below volume_min |
Block |
After these ten, send_demo_order still calls order_check before sending.
Open the five files for the next sections (Notepad asks to create each; paste the matching block, Ctrl+S):
notepad src\pre_trade_check.py
notepad src\telegram_approve.py
notepad src\send_demo_order.py
notepad src\flow_level2.py
notepad src\reconcile.pysrc/pre_trade_check.py (uses src/check_proposal.py, src/lot.py and
src/lot_mt5.py):
"""Check layer before a demo order. One failed line means no order."""
import json
import math
from datetime import datetime, timezone
from pathlib import Path
import MetaTrader5 as mt5
from src.check_proposal import RISK_PERCENT, check_proposal # fields, symbol, SL, fixed-convention lot
from src.lot_mt5 import lot_by_broker # lot from the broker's own specification
CONFIG = json.loads(Path("config/limits.json").read_text(encoding="utf-8-sig"))
def _start_of_day_equity(equity_now):
'''The first run of the UTC day stores equity in logs/; later runs read it back.'''
p = Path("logs/start_of_day_equity.json")
today = datetime.now(timezone.utc).date().isoformat()
if p.exists():
d = json.loads(p.read_text(encoding="utf-8"))
if d.get("date") == today:
return d["equity"]
p.parent.mkdir(exist_ok=True)
p.write_text(json.dumps({"date": today, "equity": equity_now}), encoding="utf-8")
return equity_now
def _in_news_window(now):
for a, b in CONFIG["news_windows_utc"]:
start = datetime.strptime(a, "%Y-%m-%d %H:%M").replace(tzinfo=timezone.utc)
end = datetime.strptime(b, "%Y-%m-%d %H:%M").replace(tzinfo=timezone.utc)
if start <= now <= end:
return True
return False
def pre_trade_check(p, orders_today):
'''p: the agent's proposal JSON. Returns dict: ok, reasons, lot, risk_usd, broker_symbol.'''
res = {"ok": False, "reasons": [], "lot": 0.0, "risk_usd": 0.0, "broker_symbol": None}
acc, term = mt5.account_info(), mt5.terminal_info()
if acc is None or acc.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO:
res["reasons"].append("could not confirm a demo account")
return res
if term is None or not term.connected:
res["reasons"].append("terminal not connected to the server")
return res
balance = min(acc.balance, acc.equity)
ok, reasons, lot_fixed = check_proposal(p, balance) # fields, symbol, SL side, fixed-convention lot
if not ok:
res["reasons"] = reasons
return res
try: # the proposal must be fresh
t = datetime.fromisoformat(p["time_utc"].replace("Z", "+00:00"))
age_min = (datetime.now(timezone.utc) - t).total_seconds() / 60
except (KeyError, TypeError, AttributeError, ValueError):
age_min = None
if age_min is None or not 0 <= age_min <= CONFIG["max_proposal_age_minutes"]:
res["reasons"].append("time_utc missing, malformed or too old")
return res
sym, side, entry, sl = p["symbol"], p["action"], p["entry"], p["sl"]
tp = p.get("tp")
bsym = CONFIG.get("broker_symbol", {}).get(sym)
limits = [CONFIG.get(k, {}).get(sym) for k in ("lot_cap", "max_spread", "max_price_drift")]
if bsym is None or None in limits:
res["reasons"].append("config has no limits for " + sym) # no cap set: no order
return res
lot_cap, max_spread, max_drift = limits
if not isinstance(tp, (int, float)) or (tp <= entry if side == "BUY" else tp >= entry):
res["reasons"].append("TP missing or on the wrong side")
if not term.trade_allowed:
res["reasons"].append("AutoTrading button is off")
mt5.symbol_select(bsym, True) # show the symbol in Market Watch if hidden
info, tick = mt5.symbol_info(bsym), mt5.symbol_info_tick(bsym)
if info is None or tick is None:
res["reasons"].append("could not read specification or price of " + bsym)
return res
price = tick.ask if side == "BUY" else tick.bid
if tick.ask - tick.bid > max_spread:
res["reasons"].append(f"spread {tick.ask - tick.bid:.5f} above the cap")
if abs(price - entry) > max_drift:
res["reasons"].append("price has moved too far from the proposed entry")
if (side == "BUY" and sl >= price) or (side == "SELL" and sl <= price):
res["reasons"].append("SL now on the wrong side of the current price")
return res
if abs(price - sl) < info.trade_stops_level * info.point:
res["reasons"].append("SL closer than the broker's minimum stop distance")
positions = mt5.positions_get()
if positions is None: # read error: never treat it as 0 positions
res["reasons"].append("could not read positions: " + str(mt5.last_error()))
return res
mine = sum(1 for x in positions if x.magic == CONFIG["magic"])
if mine >= CONFIG["max_positions"]:
res["reasons"].append(f"agent already has {mine} position(s)")
sod = _start_of_day_equity(acc.equity)
if sod - acc.equity >= sod * CONFIG["daily_loss_percent"] / 100:
res["reasons"].append("daily loss cap reached: no new orders until the UTC day ends")
if _in_news_window(datetime.now(timezone.utc)):
res["reasons"].append("inside a news window")
if orders_today >= CONFIG["max_orders_per_day"]:
res["reasons"].append("daily order cap reached")
risk_usd = balance * RISK_PERCENT / 100
try:
lot_broker = lot_by_broker(risk_usd, abs(price - sl), info)
except ValueError as err: # missing specification: don't guess
res["reasons"].append("lot_by_broker: " + str(err))
return res
lot = min(lot_fixed, lot_broker, lot_cap)
lot = round(math.floor(lot / info.volume_step + 1e-9) * info.volume_step, 8) # DOWN
if lot < info.volume_min:
res["reasons"].append("lot below volume_min: no trade")
if res["reasons"]:
return res
loss_per_lot = abs(price - sl) / info.trade_tick_size * info.trade_tick_value_loss
res.update(ok=True, lot=lot, risk_usd=round(lot * loss_per_lot, 2), broker_symbol=bsym)
return resApproval over Telegram: your chat only, three commands, a deadline
When a proposal passes the first check, the flow sends you a message through
the morning-report bot, using the same TL_BOT_TOKEN and TL_CHAT_ID
environment variables. It shows symbol, timeframe, side, entry, SL, TP, the
lot computed by code, USD risk, the agent’s short reason, the ID and the
deadline.
- Open the chart yourself and compare with your plan.
- Type one of three commands:
/approve <id>,/cancel <id>or/stop.
The ID is 8 characters that code derives from the proposal’s content with
SHA-256. The agent can’t choose it, and the same proposal always gets the same
ID. No answer by the deadline means the proposal is dropped, with no order. To
attach a chart image, send it with sendPhoto as the morning report does,
using an image drawn by code from data, never one made by the agent.
The bot reads with getUpdates long polling. getUpdates and webhooks are
mutually exclusive (getUpdates doesn’t work while a webhook is set), and
pending updates are kept for at most 24 hours. After each read the code sets
offset to the highest update_id + 1, which acknowledges those updates so
they don’t come back. At startup, start() reads all old messages: old
/approve and /cancel are dropped, so yesterday’s approval can’t trigger
anything, but an old /stop still takes effect and becomes a STOP file.
Telegram also accepts a negative offset to forget old updates, but that would
discard an old /stop, so this flow doesn’t use it.
Only your chat_id is accepted; messages from anyone else are ignored. No
command opens a position. A network or Telegram error is never an approval.
The code prints only the error name, never the URL, because the URL contains
the token.
Proposals in this flow come only from code reading MT5 demo candles, or from you. Don’t wire TradingView alerts (including ones created over MCP) to a webhook to generate proposals or orders: TradingView’s terms allow data, alerts and webhooks for display only, and prohibit using them for automated order generation, order checks or algorithmic decisions. A webhook can notify you, nothing more. TradingView webhooks need two-factor authentication, only accept ports 80 and 443, cancel the request if the receiver takes longer than 3 seconds, and shouldn’t carry passwords or credentials in the body.
Sample approval message (made-up prices; your ID will differ):
DEMO | proposal ad68ca86
XAUUSD H1 BUY | entry 4000.0 | SL 3995.0 | TP 4010.0
lot 0.01 (computed by code) | risk 5.5 USD
reason: example, made-up prices
Expires in 10 minutes. Send /approve ad68ca86 or /cancel ad68ca86. Stop everything: /stop| You send | The flow | Log |
|---|---|---|
/approve ad68ca86 |
Re-checks with fresh prices, then sends the demo order | APPROVED, then SENT or BLOCKED |
/cancel ad68ca86 |
Drops the proposal, no order | CANCELLED |
/stop |
Stops waiting and writes a STOP file; later proposals are blocked until you delete STOP | STOP |
| No reply in time | Drops the proposal | EXPIRED |
src/telegram_approve.py:
"""Approve proposals over Telegram with long polling, and send notices. Accepts commands only from your chat_id."""
import json
import os
import time
import urllib.parse
import urllib.request
from pathlib import Path
_offset = None # read position, kept for one run
def _fetch(wait_s):
params = {"timeout": wait_s}
if _offset is not None:
params["offset"] = _offset
url = ("https://api.telegram.org/bot" + os.environ["TL_BOT_TOKEN"] # URL contains the token: never print
+ "/getUpdates?" + urllib.parse.urlencode(params))
with urllib.request.urlopen(url, timeout=wait_s + 15) as r:
res = json.load(r)
if not res.get("ok"):
raise RuntimeError("Telegram refused getUpdates")
return res["result"]
def send_message(text):
'''Send one message to your chat with sendMessage. Raises on error; the caller catches.'''
url = "https://api.telegram.org/bot" + os.environ["TL_BOT_TOKEN"] + "/sendMessage" # token: never print
data = urllib.parse.urlencode({"chat_id": os.environ["TL_CHAT_ID"].strip(),
"text": text[:4096]}).encode("utf-8")
with urllib.request.urlopen(url, data=data, timeout=30) as r:
if not json.load(r).get("ok"):
raise RuntimeError("Telegram refused sendMessage")
def _your_text(u):
msg = u.get("message") or {}
if str(msg.get("chat", {}).get("id")) != os.environ["TL_CHAT_ID"].strip():
return None # another chat: ignore
return " ".join((msg.get("text") or "").lower().split())
def start():
'''Call once at startup to read all old messages.
An old /stop still takes effect; old /approve and /cancel are ignored.'''
global _offset
while True:
old = _fetch(1)
if not old:
return
for u in old:
_offset = u["update_id"] + 1 # acknowledge
if _your_text(u) == "/stop":
Path("STOP").write_text("old /stop from Telegram", encoding="utf-8")
def read_commands(wait_s):
global _offset
out = []
for u in _fetch(wait_s):
_offset = u["update_id"] + 1
text = _your_text(u)
if text == "/stop":
Path("STOP").write_text("/stop from Telegram", encoding="utf-8") # becomes layer 1
if text:
out.append(text)
return out
def wait_for_approval(pid, limit_s):
'''Returns APPROVED, CANCELLED, STOP or EXPIRED. A network error is never an approval.'''
deadline = time.time() + limit_s
while time.time() < deadline:
try:
cmds = read_commands(max(1, min(20, int(deadline - time.time()))))
except Exception as e:
print("Telegram error:", type(e).__name__) # error name only, never the URL
time.sleep(5)
continue
for text in cmds:
if text == "/stop":
return "STOP"
if text == "/cancel " + pid:
return "CANCELLED"
if text == "/approve " + pid:
return "APPROVED"
return "EXPIRED"Chat bridges into an agent are a different thing
Read this if you plan to use one; the three-command flow doesn’t. The key
difference is where messages go. A chat bridge feeds messages into an agent
that has a shell. This flow feeds them into code; the agent never sees them
and has no order_send.
Claude Code Channels (a research preview, so details may change) is a plugin
that forwards Telegram, Discord or iMessage messages into a running Claude Code
session. Messages arrive only while the session is open; ones sent while it’s
closed wait at Telegram (up to 24 hours) and arrive when you reopen it, and the
plugin doesn’t drop old ones the way start() does. Only allowlisted senders’
direct messages get through; on Telegram and Discord you add yourself with a
pairing code. Group mode is off by default; turning it on without limiting
senders lets every member message the session.
The official Telegram plugin also forwards Claude Code’s tool-permission prompts. The first message shows only a line like “Permission: Bash” with three buttons: See more, Allow, Deny. You only see the agent’s description and the actual command after See more, yet Allow works straight from the first message. Anyone who can message through the channel can approve or deny tool use in the session. If nobody answers, the session waits; it doesn’t deny on its own.
| Chat bridge (e.g. Channels) | This post’s three-command flow | |
|---|---|---|
| Where messages go | Into the open Claude Code session, as requests; the agent can read files and run commands within the session’s permissions | Into telegram_approve.py; the agent doesn’t read them |
| Who can send | Allowlisted senders; any of them can approve tool use | Only TL_CHAT_ID; other chats ignored |
| What it accepts | Free text, plus tool-permission prompts answered with buttons | Exactly /approve id, /cancel id, /stop |
| What you approve | One tool use; Allow is clickable before you’ve seen the command | One demo order proposal; lot and risk by code, ID hashed by code |
| No answer | The session waits | EXPIRED: no order; a network error is never approval |
| While you’re away | No timed auto-deny; use dontAsk mode or close the session |
Create a STOP file; the flow only runs when you run it |
If you use a chat bridge anyway:
- Ask only read-only things, such as summarising
logs/flow.jsonl. - Keep the session in Manual with the deny rules above.
- Never press Allow before See more and reading the whole command.
- Deny any Bash request from the phone, and anything that runs
src.flow_level2,src.send_demo_order,src.reconcile, callsorder_sendor deletes STOP; do those at the computer. - Never run that session with
--dangerously-skip-permissions, which offers no protection against prompt injection. - The only path to
order_sendstays the three-command flow.
For Telegram specifically:
- Create a separate bot with BotFather (
/newbot) for the bridge; never reuseTL_BOT_TOKEN. Telegram allows onegetUpdatesreader per token: sharing causes409 Conflict, the plugin andtelegram_approve.pysteal each other’s messages, and/approveor/stopcan land in the agent session instead of the code (then/stopnever becomes a STOP file). - Don’t run
/telegram:configurewith the token: that’s a skill the agent runs, so the token becomes part of the conversation sent to the model and is stored in the session files under.claude\projects. Don’t putTELEGRAM_BOT_TOKENin the environment of the window runningclaudeeither: every command the agent runs can see it. - Write the token yourself into the file the plugin reads at startup: run the
two lines below, type
TELEGRAM_BOT_TOKEN=and paste the token right after the equals sign, with no Enter at the end, then Ctrl+S. A trailing newline stops the plugin reading the token, so it exits and the bot stays silent. - After pairing, run
/telegram:access policy allowlistso strangers who message the bot no longer get a pairing code. - If you ever paste the token into an AI chat, revoke it in BotFather, create a new one and update the file.
New-Item -ItemType Directory -Force "$env:USERPROFILE\.claude\channels\telegram"
notepad "$env:USERPROFILE\.claude\channels\telegram\.env"Sending the demo order and reading retcodes
send_demo_order.py is the only file in the project that calls order_send.
The request has action (market deal), symbol, volume (lot), type (buy or
sell), price, sl, tp, deviation (maximum slippage in points), magic,
comment (ai- plus the ID), type_time and type_filling.
It calls order_check first; a passing check returns retcode 0 and “Done”. A
successful request still doesn’t guarantee the trade operation will succeed,
so after order_send the code compares the retcode with TRADE_RETCODE_DONE
(10009).
It never resends. If order_send returns None or raises, the status is
UNKNOWN: you don’t know whether the order reached the server. The flow then
creates a STOP file. Run the reconciliation before anything else, and delete
STOP only when you know whether the order went. Don’t resend just because no
Telegram message arrived. Rerunning the same proposal file is pointless anyway:
the flow logs DUPLICATE. Wait for a new proposal.
First run:
- Save
src/send_demo_order.pyandsrc/flow_level2.pyand open the demo terminal. - Line 1 below prints the current UTC time.
- Line 2 opens Notepad: paste the sample proposal, replace
time_utcanddata_untilwith that time, and set entry, SL and TP from the current price in the demo terminal (for gold, say SL 5 USD away and TP 10 USD away). Keep the other fields; save. - Line 3 runs the flow. The window prints each log line, Telegram receives
the approval message, and you send
/approvewith the ID.
Expected: the log shows RECEIVED, AWAITING_APPROVAL, APPROVED, SENT,
FILLED. In MT5, the Toolbox Trade tab shows the new position with SL and TP;
the History tab shows the matching order and deal. The flow handles every
file in proposals/ in name order, moves each to proposals/done, and exits.
proposals/sample_valid.json (made-up prices; the agent writes exactly these
fields, never a lot):
{
"time_utc": "2026-11-11T02:00:00Z",
"symbol": "XAUUSD",
"timeframe": "H1",
"action": "BUY",
"entry": 4000.0,
"sl": 3995.0,
"tp": 4010.0,
"short_reason": "example, made-up prices",
"data_until": "2026-11-11T01:59:59Z",
"prompt_version": "decision-v1"
}(Get-Date).ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'")
notepad proposals\sample_valid.json
.venv\Scripts\python -m src.flow_level2Sample output (UTC; lot and prices depend on when you run it):
2026-11-11T02:03:10+00:00 ad68ca86 RECEIVED sample_valid.json
2026-11-11T02:03:11+00:00 ad68ca86 AWAITING_APPROVAL
2026-11-11T02:05:42+00:00 ad68ca86 APPROVED
2026-11-11T02:05:43+00:00 ad68ca86 SENT XAUUSD BUY lot 0.01
2026-11-11T02:05:43+00:00 ad68ca86 FILLED retcode 10009 | order ... | lot 0.01 | sent at ... | filled at ...On filling modes: the documentation’s example uses ORDER_FILLING_RETURN, but
your broker may accept only FOK (fill the whole order or cancel) or IOC (fill
what’s possible, cancel the rest). On retcode 10030, change filling in the
config outside trading hours, note why, and rerun the drills. In every case
below, nothing is resent automatically.
| retcode | Meaning | What to do |
|---|---|---|
10009 TRADE_RETCODE_DONE |
Request completed | Logged FILLED; check the Trade tab shows SL and TP |
10010 TRADE_RETCODE_DONE_PARTIAL |
Only part of the request completed | Logged PARTIAL_FILL; read the real lot in the Trade tab; don’t top up |
10004 TRADE_RETCODE_REQUOTE |
Requote | Don’t resend; wait for a new proposal |
10006 TRADE_RETCODE_REJECT |
Request rejected | Read the comment in the log; no blind retries |
10014 TRADE_RETCODE_INVALID_VOLUME |
Invalid volume | Open the symbol’s Specification; check volume_min, volume_step |
10016 TRADE_RETCODE_INVALID_STOPS |
Invalid SL or TP | Check the symbol’s minimum stop distance |
10018 TRADE_RETCODE_MARKET_CLOSED |
Market closed | Wait for the session; EURUSD and XAUUSD close at weekends |
10019 TRADE_RETCODE_NO_MONEY |
Not enough money | Don’t raise leverage or lot; review risk |
10027 TRADE_RETCODE_CLIENT_DISABLES_AT |
Automated trading disabled in the terminal | Check AutoTrading and the Python API box (demo terminal only) |
10030 TRADE_RETCODE_INVALID_FILL |
Invalid filling mode | Change filling in the config outside trading hours |
10031 TRADE_RETCODE_CONNECTION |
No connection to the trade server | Don’t resend; check the connection; reconcile before continuing |
order_send returns None |
No result (not a retcode; see last_error) |
UNKNOWN: STOP is on; reconcile first, never resend |
src/send_demo_order.py:
"""The ONLY place in the project that calls order_send. Demo accounts only; never resends."""
import MetaTrader5 as mt5
FILLING = {"FOK": mt5.ORDER_FILLING_FOK, "IOC": mt5.ORDER_FILLING_IOC,
"RETURN": mt5.ORDER_FILLING_RETURN}
def send_demo_order(bsym, side, lot, sl, tp, pid, cfg):
'''Returns (status, detail): FILLED, PARTIAL_FILL, REJECTED, UNKNOWN or BLOCKED.'''
acc = mt5.account_info()
if acc is None or acc.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO:
return "BLOCKED", "could not confirm a demo account"
tick = mt5.symbol_info_tick(bsym)
if tick is None:
return "BLOCKED", "no price: " + str(mt5.last_error())
price = tick.ask if side == "BUY" else tick.bid
req = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": bsym,
"volume": lot,
"type": mt5.ORDER_TYPE_BUY if side == "BUY" else mt5.ORDER_TYPE_SELL,
"price": price,
"sl": sl,
"tp": tp,
"deviation": cfg["deviation_points"], # max slippage, in points
"magic": cfg["magic"], # the agent's own number
"comment": "ai-" + pid, # proposal id, for reconciliation
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": FILLING[cfg["filling"]],
}
chk = mt5.order_check(req)
if chk is None:
return "BLOCKED", "order_check returned nothing: " + str(mt5.last_error())
if chk.retcode != 0: # a passing check returns retcode 0, "Done"
return "BLOCKED", f"order_check {chk.retcode} {chk.comment}"
try:
res = mt5.order_send(req)
except Exception as e:
return "UNKNOWN", "order_send raised " + type(e).__name__ + ": reconcile first"
if res is None:
return "UNKNOWN", "order_send returned nothing " + str(mt5.last_error())
detail = (f"retcode {res.retcode} | order {res.order} | lot {res.volume}"
f" | sent at {price} | filled at {res.price}")
if res.retcode == mt5.TRADE_RETCODE_DONE:
return "FILLED", detail
if res.retcode == mt5.TRADE_RETCODE_DONE_PARTIAL:
return "PARTIAL_FILL", detail
return "REJECTED", f"retcode {res.retcode} {res.comment}"src/flow_level2.py:
"""Level-2 flow, demo only: proposal -> check -> approval -> re-check -> demo order -> log."""
import hashlib
import json
import os
from datetime import datetime, timezone
from pathlib import Path
import MetaTrader5 as mt5
from src import telegram_approve as tg
from src.pre_trade_check import CONFIG, pre_trade_check
from src.send_demo_order import send_demo_order
LOG = Path("logs/flow.jsonl")
def log(pid, status, detail=""):
rec = {"time_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"id": pid, "status": status, "detail": detail}
LOG.parent.mkdir(exist_ok=True)
with LOG.open("a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
print(rec["time_utc"], pid, status, detail)
def read_log():
if not LOG.exists():
return []
return [json.loads(line) for line in LOG.read_text(encoding="utf-8").splitlines() if line.strip()]
def orders_today():
today = datetime.now(timezone.utc).date()
return sum(1 for r in read_log() if r["status"] == "SENT"
and datetime.fromisoformat(r["time_utc"]).date() == today)
def make_id(p):
'''CODE makes the id from the proposal's content: same proposal, same id; the agent can't choose it.'''
cols = ("symbol", "timeframe", "time_utc", "action", "prompt_version")
key = "|".join(str(p.get(k)) for k in cols)
return hashlib.sha256(key.encode("utf-8")).hexdigest()[:8]
def notify(text):
try:
tg.send_message("DEMO | " + text)
except Exception as e: # a Telegram error never loses the log
print("Telegram send error:", type(e).__name__)
def handle(path):
try:
p = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
log("file-" + path.stem, "BLOCKED", "file is not valid JSON")
return
if not isinstance(p, dict):
log("file-" + path.stem, "BLOCKED", "proposal is not a JSON object")
return
if "error" in p: # the model-calling script wrote an error instead of a proposal
log("error-" + path.stem, "SOURCE_ERROR", str(p["error"]))
n = CONFIG["max_consecutive_errors"]
if [r["status"] for r in read_log()][-n:] == ["SOURCE_ERROR"] * n:
Path("STOP").write_text("proposal source failed repeatedly", encoding="utf-8")
notify(f"proposal source failed {n} times in a row, STOP is on. Existing SL/TP stay on the server.")
return
pid = make_id(p)
if any(r["id"] == pid for r in read_log()):
log(pid, "DUPLICATE", "id already handled, skipped")
return
log(pid, "RECEIVED", path.name)
if Path("STOP").exists():
log(pid, "STOP", "STOP file present")
return
if p.get("action") == "STAY_OUT":
log(pid, "NO_TRADE", "agent chose to stay out")
return
res = pre_trade_check(p, orders_today())
if not res["ok"]:
log(pid, "BLOCKED", "; ".join(res["reasons"]))
notify(f"{pid} blocked: " + "; ".join(res["reasons"]))
return
approved_lot = res["lot"]
if CONFIG["level"] == 2:
mins = CONFIG["approval_minutes"]
msg = (f"proposal {pid}\n{p['symbol']} {p.get('timeframe')} {p['action']}"
f" | entry {p['entry']} | SL {p['sl']} | TP {p['tp']}\n"
f"lot {approved_lot} (computed by code) | risk {res['risk_usd']} USD\n"
f"reason: {p.get('short_reason', '')}\n"
f"Expires in {mins} minutes. Send /approve {pid} or /cancel {pid}. Stop everything: /stop")
notify(msg)
log(pid, "AWAITING_APPROVAL")
answer = tg.wait_for_approval(pid, mins * 60)
log(pid, answer)
if answer != "APPROVED":
return
if Path("STOP").exists(): # kill switch turned on while waiting
log(pid, "STOP", "STOP file present after approval")
return
res = pre_trade_check(p, orders_today()) # price, spread, positions may have changed
if not res["ok"]:
log(pid, "BLOCKED", "re-check: " + "; ".join(res["reasons"]))
notify(f"{pid} blocked on re-check: " + "; ".join(res["reasons"]))
return
lot = min(res["lot"], approved_lot) # never more than the lot you approved
log(pid, "SENT", f"{res['broker_symbol']} {p['action']} lot {lot}")
status, detail = send_demo_order(res["broker_symbol"], p["action"], lot, p["sl"], p["tp"], pid, CONFIG)
log(pid, status, detail)
if status == "UNKNOWN": # not sure the order went: STOP first, notify after
Path("STOP").write_text("UNKNOWN: reconcile first", encoding="utf-8")
notify(f"{pid} {status}: {detail}")
if status == "UNKNOWN":
notify("status UNKNOWN, STOP is on. Run the reconciliation before removing STOP.")
if CONFIG["level"] == 3 and orders_today() >= CONFIG["max_orders_per_day"]:
Path("STOP").write_text("level 3: daily order cap reached", encoding="utf-8")
notify("daily order cap reached, STOP is on. Review before removing STOP.")
def main():
if CONFIG["level"] not in (2, 3):
raise SystemExit("level in config/limits.json must be 2 or 3")
path = os.environ.get("TL_MT5_PATH", "").strip('"') # several terminals: set it
if not (mt5.initialize(path) if path else mt5.initialize()):
raise SystemExit("initialize() error: " + str(mt5.last_error()))
try:
term = mt5.terminal_info()
if term is None or Path(term.path) != Path(CONFIG["demo_terminal_folder"]):
raise SystemExit("Attached to the wrong terminal. Set TL_MT5_PATH or fix demo_terminal_folder, then rerun.")
tg.start()
done = Path("proposals/done")
done.mkdir(parents=True, exist_ok=True)
for f in sorted(Path("proposals").glob("*.json")):
tg.read_commands(1) # pick up a /stop sent between two proposals
handle(f)
f.replace(done / f.name)
finally:
mt5.shutdown()
if __name__ == "__main__":
main()When you hit UNKNOWN:
order_sendreturnedNoneor raised: you don’t know if the order reached the server.- The flow logs
UNKNOWN, creates STOP and notifies you; it doesn’t resend. - Run
python -m src.reconcile: it compares the log with deals carrying the agent’s magic and commentai-<id>. - Check the Trade and History tabs in MT5. A deal exists: record that the order went. No deal: wait for a new proposal.
- Write down the cause, then delete STOP. Never resend just because no Telegram message arrived.
A four-layer kill switch and stop conditions written in advance
| Layer | How to trigger | Effect | Turning the system back on |
|---|---|---|---|
| 1. STOP file | PowerShell: New-Item -ItemType File STOP |
The flow logs STOP and opens nothing new; existing positions keep SL and TP |
Write the cause in your journal, then Remove-Item STOP |
2. /stop on Telegram |
Send /stop in the private chat with the bot |
Stops a pending approval at once; code turns it into a STOP file | As layer 1 |
| 3. AutoTrading button | Click it on the MT5 toolbar (may read Algo Trading) | The terminal forbids programs from trading; the pre-trade check reports it off and sends nothing | Click it again after reconciling |
| 4. Full stop | Ctrl+C in the flow window, then close the demo terminal | No program left that can send orders | Reopen the terminal, run src.check_terminal and src.reconcile, then the flow |
The flow only sends market orders (TRADE_ACTION_DEAL), so there are no
pending orders to cancel. If you ever use pending orders, the kill switch must
also delete them with TRADE_ACTION_REMOVE. Disabling Expert Advisors in the
MT5 settings only forbids EAs from trading; it doesn’t stop them running. To
stop an EA completely, remove it from the chart, close the chart, or close the
platform. A full stop in the middle of sending can leave an unclear state, so
reconcile afterwards.
No layer closes open positions: SL and TP stay at the server. To close one, do it yourself in the Trade tab (double-click the position, or right-click → Close Position).
New-Item -ItemType File STOP
Test-Path STOP
Remove-Item STOPLine 1 turns STOP on. Line 2 prints True while it exists. Run line 3 only
after writing down the cause.
Write the stop conditions before running, enforced in code or as a procedure
you commit to. Never let the agent decide whether to stop. Copy the table into
reports/stop-conditions.md, fill in your numbers, and commit it before the
first level-2 run. After any stop, delete STOP only once the cause and fix are
in your journal.
| Group | Condition | Action |
|---|---|---|
| Risk | Daily loss hits the cap (e.g. 2% of start-of-day equity) | Code blocks new orders until the day ends |
| Risk | Drawdown from the equity peak beyond your preset level, chosen with the recovery table and simulation below (e.g. 20% at 1% risk per trade: needs 25% to recover) | Create STOP, go back to shadow |
| Risk | Demo equity at some point below your hard-stop level (e.g. 50% of start: needs 100% to recover) | Create STOP, stop completely; rewrite the plan; don’t top up virtual money to keep going |
| Behaviour | Daily order cap reached; repeated duplicate proposals | Block; at level 3 code creates STOP |
| Behaviour | Proposals with odd symbols, missing SL, extra fields | Block and notify; if it repeats, create STOP and review the prompt |
| Technical | Proposal source fails 3 times in a row (e.g. 429); any UNKNOWN |
Code creates STOP; reconcile before continuing |
| Technical | The provider changes the model or version | Back to shadow; rerun the shadow tests |
| Market | Inside a news window; spread above the cap | Code blocks by window and spread cap |
| Security | Suspected leak of the bot token, an API key or a password; odd content in the agent’s memory | Create STOP; revoke and rotate the keys |
| Cost | Token spend for the day over budget | Stop the model calls; existing SL and TP stay |
Choosing a drawdown threshold
Two tools. First pick a drawdown you can still recover from, with the recovery table. Then use the simulation to see, for exactly the number of trades you plan, how often that threshold stops a good system by mistake and how often it lets a bad one keep going.
The recovery table. After a drawdown x you have 1 − x, so you need x ÷ (1 − x): 10% needs 11.1%, 20% needs 25%, 50% needs 100%, 80% needs 400%. It climbs fast, so your stop must sit where recovery is still realistic.
The Monte Carlo. 10,000 sequences of 200 trades each, seed 20261123. Risk per trade is a fixed fraction of current equity, as in the check layer; TP pays +2R, SL costs 1R, costs 0.1R per trade. Scenario A hits TP with probability 1/3, an expectation of −0.10R: no edge, losing to costs. Scenario B hits TP 40% of the time: +0.10R.
- At 1% risk per trade, 81.6% of A’s sequences draw down at least 20% at some point. Even B has 89.8% of sequences drawing down at least 10%.
- At 5% risk, 89.9% of A and 32.9% of B fall to half their starting equity at some point, which then needs 100% to recover.
- The last column is the median maximum drawdown: half the sequences go deeper. For B at 1% risk that’s 15.4%.
The model is simple: independent trades, constant probabilities, no lot rounding or slippage. Reality is usually worse.
Every probability here is for 200 trades. With the sample cap of 3 orders a
day (at most 15 a week), 200 trades takes at least about 13 weeks. Any number
must be read with its trade count: fewer trades, lower chances of hitting a
threshold; more trades, higher, even for a system with an edge. So before you
choose, set N_TRADES to the total you’ll run under that threshold and rerun.
If you extend the run, rerun with the new number: drawdown is measured from
the highest peak since the start and doesn’t reset weekly.
Take 15 trades (one week at 3 a day) at 1% risk: even losing all 15 is only a 15.3% drawdown, so no sequence reaches 20%. A 10% threshold stops 10.0% of A and 3.8% of B. One week is too few trades for a drawdown threshold to tell a good system from a bad one; in the first week, the real limits are the daily loss cap and the daily order cap.
A stop threshold is a test with two kinds of error: stopping a good system, and letting a bad one run. At 1% risk over 200 trades, a 10% threshold stops 89.8% of B, so it stops a system with a small edge too. A 20% threshold stops 81.6% of A and 23.9% of B, but when it triggers you need 25% to recover.
Risk per trade stays at 1%, matching the check layer, so read the 1.0% rows;
0.5% is for comparison, and 2% and 5% show why you don’t exceed the cap. Going
below 1% means changing RISK_PERCENT in check_proposal.py (and its tests),
committing, and rerunning the seven drills; writing a number in reports/
alone doesn’t change any lot.
“Blown” here means equity at some point at or below 50% of the start. From 2,000 USD down to 1,000 USD, 1% is 10 USD. With a 12 USD gold SL, 1 lot loses 1,200 USD, so the lot works out to 0.0083 and rounds down to 0: the check layer won’t allow another trade (a 5 USD SL still allows 0.01).
notepad src\drawdown_risk.py
notepad tests\test_drawdown_risk.py
.venv\Scripts\python -m pytest -q tests\test_drawdown_risk.py
.venv\Scripts\python src\drawdown_risk.pypytest prints 4 passed; the last command takes a few seconds and prints the
output below. Different numbers mean the file differs (seed, path count, trade
count or scenario parameters). Changing parameters for your plan is fine as
long as you label them as assumptions.
src/drawdown_risk.py:
# src/drawdown_risk.py: the "lose x%, need how much to recover" table and a Monte Carlo of drawdowns
# when risk per trade is a fixed fraction of current equity. Every parameter is an ASSUMPTION.
# Reads no MT5, no network, sends no orders. .venv\Scripts\python src\drawdown_risk.py
import random
import statistics
SEED = 20261123 # fixed seed: a rerun gives the same numbers
N_PATHS = 10_000 # simulated trade sequences
N_TRADES = 200 # trades per sequence
RISKS = [0.005, 0.01, 0.02, 0.05] # risk per trade, as a fraction of current equity
SCENARIOS = { # name: (P(TP), R won at TP, cost per trade in R)
"A | no edge": (1 / 3, 2.0, 0.1),
"B | small edge": (0.40, 2.0, 0.1),
}
LOSSES = [0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.40, 0.50, 0.70, 0.80, 0.90]
BLOWN = 0.50 # "blown" here: equity at some point <= 50% of the start
def gain_to_recover(loss):
"""A loss of fraction `loss` (0 <= loss < 1) needs a gain of loss / (1 - loss) to get back."""
if not 0 <= loss < 1:
raise ValueError("loss must be in [0, 1)")
return loss / (1 - loss)
def expected_r(p_tp, win_r, cost_r):
"""Expected R per trade: TP gives win_r - cost, SL loses 1 + cost."""
return p_tp * (win_r - cost_r) - (1 - p_tp) * (1 + cost_r)
def simulate(p_tp, win_r, cost_r, risks, n_paths=N_PATHS, n_trades=N_TRADES, seed=SEED):
"""Returns {risk: [(max drawdown from peak, lowest equity), ...]}, starting equity 1.
All risk levels share the same trade outcomes, so they're compared on the same luck."""
rng = random.Random(seed)
out = {r: [] for r in risks}
for _ in range(n_paths):
path = [rng.random() < p_tp for _ in range(n_trades)]
for r in risks:
up, down = 1 + r * (win_r - cost_r), 1 - r * (1 + cost_r)
eq = peak = low = 1.0
dd = 0.0
for hit_tp in path:
eq *= up if hit_tp else down
if eq > peak:
peak = eq
elif 1 - eq / peak > dd:
dd = 1 - eq / peak
if eq < low:
low = eq
out[r].append((dd, low))
return out
def main():
print("Lose x%, gain needed to recover (= x / (1 - x))")
for x in LOSSES:
print(f"lose {x:>4.0%} -> need {gain_to_recover(x):>6.1%}")
print(f"\nSimulation: {N_PATHS} paths x {N_TRADES} trades, seed {SEED}. Assumed parameters, "
"not trading results; ignores lot rounding and slippage.")
for name, (p_tp, win_r, cost_r) in SCENARIOS.items():
print(f"Scenario {name}: P(TP) {p_tp:.1%}, +{win_r}R / -1R, cost {cost_r}R, "
f"expectation {expected_r(p_tp, win_r, cost_r):+.2f}R per trade")
print("risk/trade | drawdown >= 10% | drawdown >= 20% | equity <= 50% | max drawdown (median)")
for r, items in simulate(p_tp, win_r, cost_r, RISKS).items():
n = len(items)
p10 = sum(s >= 0.10 for s, _ in items) / n
p20 = sum(s >= 0.20 for s, _ in items) / n
blown = sum(low <= BLOWN for _, low in items) / n
med = statistics.median(s for s, _ in items)
print(f"{r:>10.1%} | {p10:>15.1%} | {p20:>15.1%} | {blown:>13.1%} | {med:>21.1%}")
if __name__ == "__main__":
main()tests/test_drawdown_risk.py:
import pytest
from src.drawdown_risk import expected_r, gain_to_recover, simulate
def test_gain_to_recover():
assert gain_to_recover(0.0) == 0.0
assert gain_to_recover(0.2) == pytest.approx(0.25) # lose 20%, need 25%
assert gain_to_recover(0.5) == 1.0 # lose 50%, need 100%
with pytest.raises(ValueError):
gain_to_recover(1.0)
def test_expected_r():
assert expected_r(1 / 3, 2.0, 0.0) == pytest.approx(0.0) # no edge before costs
assert expected_r(1 / 3, 2.0, 0.1) == pytest.approx(-0.1) # costs push it negative
def test_same_seed_same_result():
a = simulate(1 / 3, 2.0, 0.1, [0.01], n_paths=50, n_trades=100, seed=7)
b = simulate(1 / 3, 2.0, 0.1, [0.01], n_paths=50, n_trades=100, seed=7)
assert a == b
def test_more_risk_deeper_drawdown():
res = simulate(1 / 3, 2.0, 0.1, [0.01, 0.05], n_paths=200, n_trades=200, seed=1)
# same trade sequence: 5% risk per trade always draws down at least as much as 1%
assert all(s5 >= s1 for (s1, _), (s5, _) in zip(res[0.01], res[0.05]))Output (assumed parameters, not trading results):
Lose x%, gain needed to recover (= x / (1 - x))
lose 5% -> need 5.3%
lose 10% -> need 11.1%
lose 15% -> need 17.6%
lose 20% -> need 25.0%
lose 25% -> need 33.3%
lose 30% -> need 42.9%
lose 40% -> need 66.7%
lose 50% -> need 100.0%
lose 70% -> need 233.3%
lose 80% -> need 400.0%
lose 90% -> need 900.0%
Simulation: 10000 paths x 200 trades, seed 20261123. Assumed parameters, not trading results; ignores lot rounding and slippage.
Scenario A | no edge: P(TP) 33.3%, +2.0R / -1R, cost 0.1R, expectation -0.10R per trade
risk/trade | drawdown >= 10% | drawdown >= 20% | equity <= 50% | max drawdown (median)
0.5% | 83.7% | 22.9% | 0.0% | 15.3%
1.0% | 99.7% | 81.6% | 1.1% | 28.8%
2.0% | 100.0% | 99.6% | 39.7% | 50.6%
5.0% | 100.0% | 100.0% | 89.9% | 86.1%
Scenario B | small edge: P(TP) 40.0%, +2.0R / -1R, cost 0.1R, expectation +0.10R per trade
risk/trade | drawdown >= 10% | drawdown >= 20% | equity <= 50% | max drawdown (median)
0.5% | 27.1% | 0.7% | 0.0% | 7.9%
1.0% | 89.8% | 23.9% | 0.0% | 15.4%
2.0% | 100.0% | 87.2% | 1.8% | 29.2%
5.0% | 100.0% | 100.0% | 32.9% | 60.9%Preparing level 3, demo only. Switch "level": 3 only when your written
conditions are met: the check layer has run for the period you set, the seven
drills pass, all four kill-switch layers have been tried, and there are no
unresolved incidents. At level 3 the flow skips the approval message but keeps
every check. When max_orders_per_day is reached, code creates STOP and waits
for you, following the usual control of limiting repeated automated executions:
once the count is hit, the strategy is disabled until a person re-enables it.
At level 3 you approve the rule set and limits before switching on, instead of
each order. Never move up a level because demo is in profit.
Seven drills, daily reconciliation, common errors
A drill means deliberately causing a fault to see whether the system reacts
correctly. Run all seven after any change to code, prompt or config, and
before changing level. Record results in reports/drills-[date].md:
scenario, the log line seen, pass or not.
Drills 1 to 6 run for real on the demo terminal, because they’re blocked
before order_send or you /cancel them. Drill 7 (connection lost while
sending) is hard to cause by hand, so have the agent write a test with a fake
MT5 using the prompt at the end of this post.
To make each drill file: copy the sample proposal, set time_utc to the
current UTC time, and change exactly one thing per the table. Give every file
a different time, except drill 1, which needs two identical files: the ID comes
from symbol, timeframe, time, side and prompt version, so two files that match
on those are one proposal.
The 429 in drill 5 is the “too many requests” error a model API can return.
The convention here: when the model-calling script exhausts its retries on
that error, it writes {"error": "429"} into proposals/ instead of a
proposal. Delete STOP after drills 5 and 6 before the next one.
| # | Scenario | How to cause it | Correct result |
|---|---|---|---|
| 1 | Same proposal twice | Two identical files at current prices; /cancel when the approval arrives |
File 1: CANCELLED. File 2: DUPLICATE, no second approval message |
| 2 | Proposal with "lot": 0.5 |
Add that line to the sample | BLOCKED: field not allowed: ['lot'] |
| 3 | Missing SL | Delete the sl line |
BLOCKED: missing numeric entry or SL |
| 4 | Symbol not allowed | Change symbol to GBPJPY |
BLOCKED: symbol not on the allowed list |
| 5 | Proposal source returns 429 three times | Three files, each only {"error": "429"} |
Three SOURCE_ERROR lines, a STOP file, one warning message; no order |
| 6 | STOP present, valid proposal | New-Item -ItemType File STOP, then run the flow |
RECEIVED then STOP; no approval message |
| 7 | Connection lost while sending | Test with a fake MT5 whose order_send returns None |
UNKNOWN, STOP file, a notice; order_send called exactly once |
Reconcile daily with src/reconcile.py. It only reads: it prints open
positions with the agent’s magic, and matches each ID in the log with MT5
deals whose comment is ai-<id>. A match is a log saying FILLED and a deal
on MT5. Three cases need action at once:
- Log
UNKNOWN, MT5 has a deal: the order went; record it. - Log
FILLED, no deal on MT5: check the History tab by hand; the broker may have changed the comment. - MT5 has a deal with the agent’s magic but the log has no such ID: there’s a path that sends orders outside the flow. Create STOP immediately and find it.
Regular reconciliation against an independent source catches system faults early. For every demo order, also add a line to your trading journal: proposed entry, sent price, fill price. That separates the drift from waiting for approval from slippage at the fill.
A level-2 week is graded on process, not P&L: every order went through the check layer, carries an ID and magic, the drills pass, and the log matches MT5. Demo results are simulated, not investment advice.
src/reconcile.py (read only, sends nothing):
"""Reconciliation, read only: the agent's magic-number deals on MT5 against logs/flow.jsonl."""
import json
import os
import time
from pathlib import Path
import MetaTrader5 as mt5
from src.pre_trade_check import CONFIG
path = os.environ.get("TL_MT5_PATH", "").strip('"') # several terminals: set it
if not (mt5.initialize(path) if path else mt5.initialize()):
raise SystemExit("initialize() error: " + str(mt5.last_error()))
try:
now = int(time.time())
# a wide window (3 days back to 1 day ahead) so server time doesn't matter
deals = mt5.history_deals_get(now - 3 * 86400, now + 86400)
positions = mt5.positions_get()
if deals is None or positions is None:
raise SystemExit("Could not read MT5 yet: " + str(mt5.last_error()) + ". Status is still UNKNOWN.")
on_mt5 = {}
for d in deals:
if d.magic == CONFIG["magic"] and d.comment.startswith("ai-"):
on_mt5.setdefault(d.comment[3:], []).append(f"deal {d.ticket} {d.symbol} {d.volume} price {d.price}")
for p in positions:
if p.magic == CONFIG["magic"]:
print("OPEN", p.ticket, p.symbol, p.volume, "SL", p.sl, "TP", p.tp, p.comment)
last = {}
log = Path("logs/flow.jsonl")
for line in (log.read_text(encoding="utf-8").splitlines() if log.exists() else []):
if line.strip():
r = json.loads(line)
last[r["id"]] = r["status"] # each id's final status
for pid in sorted(set(last) | set(on_mt5)):
if last.get(pid) in ("SENT", "FILLED", "PARTIAL_FILL", "UNKNOWN") or pid in on_mt5:
print(pid, "| log:", last.get(pid, "NOT IN LOG"), "| MT5:", on_mt5.get(pid, "no deal found"))
finally:
mt5.shutdown().venv\Scripts\python -m src.reconcileWhen everything matches:
OPEN 111 XAUUSD 0.01 SL 3995.0 TP 4010.0 ai-ad68ca86
ad68ca86 | log: FILLED | MT5: ['deal 222 XAUUSD 0.01 price 4000.55']| You see | Usual cause | Fix |
|---|---|---|
No module named 'MetaTrader5' |
Another Python, not .venv; or not installed |
Use .venv\Scripts\python; .venv\Scripts\python -m pip install MetaTrader5 |
No module named 'src' |
Wrong folder, or ran python src\flow_level2.py |
cd C:\trading-agent-lab, then use -m src.flow_level2 |
initialize() error |
Terminal not open or not logged in; TL_MT5_PATH points to the wrong file |
Open and log in to the demo terminal; fix TL_MT5_PATH |
Attached to the wrong terminal |
Several terminals and this window has no TL_MT5_PATH, or demo_terminal_folder differs from the real folder |
Set TL_MT5_PATH; set demo_terminal_folder to what src.check_terminal prints |
KeyError: 'TL_BOT_TOKEN' |
Variable not set, or the window opened before you set it | Set it as for the morning report; open a new PowerShell window |
HTTP Error 401: Unauthorized at startup, or repeated Telegram error: HTTPError |
Wrong or revoked token (401), or another program reads the same bot (409) | Check the token in BotFather; if leaked, revoke and set a new TL_BOT_TOKEN. Ctrl+C and rerun to see the code at startup |
AWAITING_APPROVAL but no message; Telegram send error in the window |
Wrong TL_CHAT_ID, or you never sent /start to the bot |
Message the bot, find your chat ID again, fix TL_CHAT_ID, open a new window |
HTTP Error 409: Conflict |
Two flow windows; a webhook is set on the bot; or another program reads the same bot, such as a Channels session using this token | Run one flow window; quit the Channels session; bridges and webhooks need their own bot |
JSONDecodeError at startup |
config/limits.json syntax |
Look for a trailing comma, curly quotes, a single \ in a path |
BLOCKED: AutoTrading button is off, or retcode 10027 |
AutoTrading off, or the Python API box still ticked | Turn it on; recheck the demo terminal’s Expert Advisors tab |
BLOCKED: time_utc missing, malformed or too old |
Proposal older than max_proposal_age_minutes, or time not in the form 2026-11-11T02:00:00Z |
Fill in the current UTC time with line 1 of the first-run block |
BLOCKED: config has no limits for XAUUSD |
The symbol is missing from one of the limit tables | Add broker_symbol, lot_cap, max_spread, max_price_drift for it |
It passes when every bad case is blocked with a reason, order_send runs only
for the valid case, and the log matches MT5.
Try it: have the agent write the drill tests
You're in [C:\trading-agent-lab], in Plan mode. Read AGENTS.md first.
Context: I run a level-2 flow on an MT5 DEMO account only. The agent writes JSON proposals into proposals/ ->
src/pre_trade_check.py checks -> Telegram waits for my approval -> re-check -> src/send_demo_order.py sends a
demo order -> logs/flow.jsonl. You don't know future prices; this task needs no market view.
Task: read src/flow_level2.py, src/pre_trade_check.py, src/telegram_approve.py and src/send_demo_order.py, then
plan [tests/test_drills.py] for these cases:
1) the same proposal handled twice -> the second logs DUPLICATE;
2) a proposal with "lot": 0.5 -> BLOCKED, field not allowed;
3) sl missing -> BLOCKED;
4) symbol = "GBPJPY" -> BLOCKED;
5) three {"error": "429"} files in a row -> a STOP file and exactly one warning message;
6) STOP file already present, valid proposal -> logs STOP;
7) approved but order_send returns None -> logs UNKNOWN, STOP file exists, no resend;
8) [YOUR CASE, e.g. /approve from another chat_id -> EXPIRED].
Constraints:
- Don't edit anything in src/ or config/; only create new files in tests/. If you find a bug in src/, write a
proposed fix for me to apply.
- Don't import the real MetaTrader5, don't call the network, don't read .env. Put a fake MetaTrader5 module into
sys.modules before importing src; replace _fetch and send_message in src/telegram_approve.py with fakes that
record into a list.
- Set TL_BOT_TOKEN and TL_CHAT_ID to fake values in tests/conftest.py, before importing src; never a real token.
- Run each test in a temp folder (tmp_path, monkeypatch.chdir) so the real logs/ and STOP are untouched.
- Every price in the tests is made up, and says so in a comment; lots must round down to steps of 0.01.
- Valid proposals use the current UTC time as time_utc, because the check blocks stale proposals.
- Each test asserts the final status in the log and how many times order_send was called: 0 for cases blocked
before sending, exactly 1 for case 7.
Output: (1) a plan listing the tests, the fakes and how order_send calls are counted; stop and wait for my
approval. (2) After I approve: the test code. (3) The command I run myself:
[.venv\Scripts\python -m pytest -q tests/test_drills.py].
Check: before reporting done, list each test with its expected log line. If anything in src/ is unclear, ask me;
don't guess.The order to work in:
- Before the session: open the MT5 demo terminal and run
src.check_terminal; updatenews_windows_utcfrom the economic calendar and commit the config. - The agent writes JSON proposals into
proposals/; in real operation, never edit the numbers in the agent’s proposal. - Run
.venv\Scripts\python -m src.flow_level2; read the approval message, check the chart yourself, and send/approveor/cancelwith the ID in time. - Anything odd:
/stopor create STOP first, investigate after; delete STOP only once the reason is written down. - End of day: run
src.reconcile, match MT5, log and Telegram by ID; add each demo order to your journal. - After any change to code, prompt or config: commit, rerun the seven drills,
save
reports/drills-[date].md. - End of each day, after reconciling: record demo equity; the peak is the
highest recorded equity since level 2 was last switched on; drawdown =
1 − today’s equity ÷ peak. If it reaches the threshold in
reports/stop-conditions.md, create STOP and go back to shadow. Don’t loosen the threshold.
Key takeaways
- On
UNKNOWN(you don’t know whether the order reached the server) the flow turns STOP on and never resends; reconcile by magic number and theai-<id>comment. - The lot is the smaller of the fixed convention and the broker’s specs,
capped per symbol and rounded down; it’s checked again right before
order_send. - Four kill-switch layers: STOP file,
/stopon Telegram, the AutoTrading button, a full stop. None of them closes open positions for you. - Only one file calls
order_send, and an order only goes after/approvefrom your chat and two passing checks.
Comments