Episode 37 · AI Trading · Building a Complete Trading System

Reconciling demo events from MT5 candle to Telegram

Join the EA log, the MT5 deals and the Telegram log by event_id over at least 10 signals, including refusals, a duplicate and an unknown state.

How do you prove that an event travelled correctly from the spec, through the code and the Strategy Tester, to a demo order and a Telegram message?

This post reconciles at least 10 signals (accepted, refused and not filled) in one table keyed by event_id. The easy mistake: a profitable demo trade, or a “bot is running fine” message, isn’t enough. You also need refused cases and a duplicate.

Terms used below:

  • Reconciliation: comparing the records of the same event in the rules, the terminal and the reports.
  • Deal: MT5’s record of an actual fill. An entry deal opens a position, an exit deal closes it with the profit.
  • Slippage: the gap between the price the EA asked for and the price it got.
  • Kill switch: a way to stop the EA from opening anything new, here an empty file named STOP.

The order path and the notification path stay apart

Lock the version and the sample data, then run the Strategy Tester with visualization. Reconcile at least 10 signals, including accepted, refused and unfilled ones. Then run forward on demo and build a report with timestamps, event ID, order ID, fill, SL/TP, quantity, costs and state.

The signals behind demo orders come only from an EA, or code, running on the MT5 demo’s candles. TradingView alerts and webhooks are never part of the order path, demo included: TradingView’s Terms of Use (sections 3 and 27, checked 2026-11-27) license them for display only. A message only says what the log confirms; an alert never stands in for a fill. If you also run TradingView alerts as notifications, as in the webhook post, the Webhook status column of the Alert log only reconciles notifications. An alert that was sent may not have been received, and it’s never an order.

Order path (demo) Notification path Never
MT5 demo candles Telegram says exactly what the log confirms An alert or webhook creating an order, demo included
The EA or code produces the signal TradingView alerts, if any, only notify An alert standing in for a fill
Request → ticket and fill Webhook status only reconciles notifications
Reconcile with MT5’s Journal and History

Reporting a refused order

The trigger is right, but the minimum lot costs more than the risk budget.

  • The rule passes; the pre-trade risk check doesn’t.
  • No order is sent; the state is logged as refused, with the reason.
  • Telegram says DEMO, no trade, risk limit, and shows no P/L.
  • Keep the chart screenshot and the log, so someone else can check it.
Step What
1 The rule
2 Tester and log
3 Event ID
4 A reconciliation report

Worked example: one demo event, end to end

Pick an event with a known timestamp. Write down the spec version, a screenshot of the signal, the input hash and the event_id. Run it dry: the log says why there’s a signal, the assumed entry, SL and TP, the quantity and the budget. Check the numbers by hand before trying it on demo.

On demo, keep the request, the ticket and fill confirmation, every state change and the report message. The timestamps must be in this order:

Order Timestamp What
1 The MT5 candle closes A closed candle on demo
2 No earlier than 1: the code produces the signal The log says why there’s a signal
3 After the signal: the request is sent Entry, SL, TP, quantity, budget
4 After the request: ticket and fill confirmed A different fill: compute the gap and the real total risk

The signal behind a demo order comes from code running on the MT5 demo’s candles; no TradingView alert or webhook is in this path. If the fill price differs from the plan, compute the difference and the real total risk; never edit the original log to make them match.

Hand in one refused case and one signal blocked as a duplicate event_id with it. The capstone passes when you can reproduce both the success path and the failures, with a way to stop and to reconcile. A profitable demo trade replaces none of this, and none of it is enough to switch the system to real money.

Not enough Needed
A “bot is running fine” message A success path you can reproduce
One profitable demo trade One refused case with its reason
One signal blocked as a duplicate event_id
A way to stop (kill switch) and to reconcile

Three records, one table

The EA from the demo-only EA post writes demo_guard_log.csv. Two more scripts produce the other records, and a third joins them.

The MT5 deals. src/export_deals.py reads the demo account’s deals for the EA’s magic number and writes data/deals.csv. It refuses a non-demo account and sends nothing:

# src/export_deals.py: copy the demo account's deals for one EA (by magic number) to a CSV. Read-only: sends nothing.
# Run with the MT5 demo terminal open and logged in:
#   .venv\Scripts\python src\export_deals.py 2026-11-23 2026-11-28 36036
import csv, sys
from datetime import datetime, timedelta, timezone

import MetaTrader5 as mt5

COLS = ["ticket", "order", "time_server", "symbol", "type", "entry", "volume", "price", "magic", "position_id",
        "profit", "commission", "swap", "comment"]


def export(date_from, date_to, magic, out="data/deals.csv"):
    if not mt5.initialize():
        raise SystemExit(f"MT5 not reachable: {mt5.last_error()}")
    try:
        info = mt5.account_info()
        if info is None or info.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO:
            raise SystemExit("Not a demo account (or no account): stopping.")
        deals = mt5.history_deals_get(date_from, date_to + timedelta(days=1)) or ()
    finally:
        mt5.shutdown()
    mine = [d for d in deals if d.magic == magic]
    with open(out, "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(COLS)
        for d in sorted(mine, key=lambda d: d.time_msc):
            t = datetime.fromtimestamp(d.time, timezone.utc).strftime("%Y.%m.%d %H:%M:%S")   # server time
            w.writerow([d.ticket, d.order, t, d.symbol, d.type, d.entry, d.volume, d.price, d.magic,
                        d.position_id, d.profit, d.commission, d.swap, d.comment])
    print(f"{len(mine)} deals with magic {magic} of {len(deals)} in the period -> {out}")


if __name__ == "__main__":
    day = lambda s: datetime.strptime(s, "%Y-%m-%d").replace(tzinfo=timezone.utc)
    export(day(sys.argv[1]), day(sys.argv[2]), int(sys.argv[3]))

The Telegram reports. src/report_events.py turns each new line of the EA log into a DEMO message that says only what the line says, using src/notifier.py from the Telegram post. Each attempt goes to logs/telegram_sent.csv. A failed message is retried on the next run; the retry is a message, never an order:

# src/report_events.py: turn new lines of DemoGuard's log into DEMO Telegram messages that say only what the log says.
# Logs every attempt to logs/telegram_sent.csv. A failed message is retried on the next run; it never touches an order.
#   .venv\Scripts\python src\report_events.py "C:\path\to\MQL5\Files\demo_guard_log.csv"
import csv, os, sys
from datetime import datetime, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import notifier  # noqa: E402

SENT_LOG = Path("logs/telegram_sent.csv")


def message(r):
    s, eid = r["state"], r["event_id"]
    body = {"refused": f"no trade: {r['reason']}",
            "check_failed": f"no trade: OrderCheck {r['retcode']} {r['reason']}",
            "not_sent": "checked, not sent (TradingEnabled=false)",
            "duplicate": "duplicate event blocked: not sent again",
            "filled": f"filled: ticket {r['ticket']}, {r['volume']} lot at {r['price']}",
            "partial": f"partly filled: ticket {r['ticket']}, {r['volume']} lot at {r['price']}; {r['reason']}",
            "resolved_filled": f"found after an unclear answer: ticket {r['ticket']}, {r['volume']} lot at {r['price']}",
            "rejected": f"rejected by the server: {r['retcode']} {r['reason']}",
            "unknown": f"UNKNOWN after retcode {r['retcode']}: EA blocked, check the terminal",
            "resolved_by_hand": "the unknown state was checked by hand; the EA runs again",
            "blocked": f"EA blocked: {r['reason']}"}.get(s)
    return None if body is None else f"DEMO | {s.upper()}\nevent {eid}\n{body}"


def done():
    if not SENT_LOG.exists():
        return set()
    with open(SENT_LOG, newline="", encoding="utf-8") as f:
        return {(r["event_id"], r["state"], r["logged_gmt"]) for r in csv.DictReader(f) if r["ok"] == "1"}


def run(ea_log, send):
    with open(ea_log, newline="", encoding="cp1252") as f:
        rows = list(csv.DictReader(f))
    already, new = done(), not SENT_LOG.exists()
    SENT_LOG.parent.mkdir(exist_ok=True)
    with open(SENT_LOG, "a", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        if new:
            w.writerow(["sent_gmt", "logged_gmt", "event_id", "state", "ok", "message_id"])
        for r in rows:
            text = message(r)
            if text is None or (r["event_id"], r["state"], r["logged_gmt"]) in already:
                continue
            ok, mid = send(text)
            w.writerow([datetime.now(timezone.utc).strftime("%Y.%m.%d %H:%M:%S"), r["logged_gmt"], r["event_id"],
                        r["state"], 1 if ok else 0, mid])
            print(("sent   " if ok else "FAILED ") + text.replace("\n", " | "))


def telegram(text):
    token, chat = os.environ["TELEGRAM_BOT_TOKEN"], os.environ["TELEGRAM_CHAT_ID"]
    res = notifier.call("sendMessage", {"chat_id": chat, "text": text}, token)
    return bool(res.get("ok")), (res.get("result") or {}).get("message_id", "")


if __name__ == "__main__":
    run(sys.argv[1], telegram)

The join. src/reconcile_events.py puts one row per event_id. It checks the timestamps are in order, that the EA’s ticket, volume and price match the MT5 deal, that every outcome was reported, and that no deal with the EA’s magic number is missing from the log. --offset is how many hours the MT5 server runs ahead of UTC in that period, measured as in the method-spec post:

# src/reconcile_events.py: one row per event_id across the EA log, the MT5 deals and the Telegram log.
# Reads files only. --offset N: the MT5 server runs N hours ahead of UTC in this period.
#   .venv\Scripts\python src\reconcile_events.py data\demo_guard_log.csv data\deals.csv logs\telegram_sent.csv --offset 2
import argparse, csv
from datetime import datetime, timedelta

OUTCOMES = ("filled", "partial", "resolved_filled", "rejected", "unknown", "resolved_by_hand",
            "not_sent", "refused", "check_failed")
TF = {"M15": 15, "H1": 60, "H4": 240}
POINT, CONTRACT, CLOCK_TOLERANCE = 0.01, 100, 2      # XAUUSD: check your symbol


def read(path, enc="utf-8"):
    with open(path, newline="", encoding=enc) as f:
        return list(csv.DictReader(f))


def t(s):
    return datetime.strptime(s, "%Y.%m.%d %H:%M:%S")


def reconcile(ea, deals, tg, offset):
    events, problems = {}, []
    for r in ea:
        if r["event_id"] == "-":
            continue
        e = events.setdefault(r["event_id"], {"lines": [], "duplicates": 0})
        e["lines"].append(r)
        if r["state"] == "duplicate":
            e["duplicates"] += 1
        elif r["state"] in OUTCOMES:
            e["outcome"] = r
        e.setdefault(r["state"], r)
    ins = {d["ticket"]: d for d in deals if d["entry"] == "0"}
    outs = {d["position_id"]: d for d in deals if d["entry"] == "1"}
    used = set()
    told = {(r["event_id"], r["state"]): r["ok"] == "1" for r in tg}
    rows = []
    for eid, e in events.items():
        sym, tf, bar, _ = eid.split("|")
        close_utc = t(bar + ":00") + timedelta(minutes=TF[tf]) - timedelta(hours=offset)
        out = e.get("outcome", e["lines"][-1])
        row = dict(event=bar[5:], outcome=out["state"], close_utc=close_utc.strftime("%m-%d %H:%M"),
                   lag="", ticket="", slip="", pnl="", telegram="")
        first = t(e["lines"][0]["logged_gmt"])
        if first < close_utc:
            problems.append(f"{bar}: logged {first:%H:%M:%S} before the bar closed at {close_utc:%H:%M} UTC")
        if "checked" in e and "sent" in e and t(e["sent"]["logged_gmt"]) < t(e["checked"]["logged_gmt"]):
            problems.append(f"{bar}: sent before checked")
        if out["state"] in ("filled", "partial", "resolved_filled"):
            d = ins.get(out["ticket"])
            if d is None:
                problems.append(f"{bar}: ticket {out['ticket']} not in the MT5 deals")
            else:
                used.add(d["ticket"])
                deal_utc = t(d["time_server"]) - timedelta(hours=offset)
                lag = (deal_utc - t(e["sent"]["logged_gmt"])).total_seconds()
                row["lag"] = f"{lag:+.0f}s"
                if lag < -CLOCK_TOLERANCE:
                    problems.append(f"{bar}: deal {-lag:.0f} s before 'sent': the PC clock is off; sync Windows time")
                if float(d["volume"]) != float(out["volume"]) or abs(float(d["price"]) - float(out["price"])) > POINT / 2:
                    problems.append(f"{bar}: EA log says {out['volume']} at {out['price']}, MT5 says {d['volume']} at {d['price']}")
                row["ticket"] = d["ticket"]
                slip = (float(d["price"]) - float(e["sent"]["price"])) / POINT
                row["slip"] = f"{slip:+.0f} pt ({slip * POINT * float(d['volume']) * CONTRACT:+.2f} USD)"
                o = outs.get(d["position_id"])
                row["pnl"] = "open" if o is None else f"{float(o['profit']) + float(o['commission']) + float(d['commission']):+.2f}"
        else:
            row["pnl"] = "none"
        states = [out["state"]] + (["duplicate"] if e["duplicates"] else [])
        marks = []
        for s in states:
            ok = told.get((eid, s))
            marks.append(f"{s} {'ok' if ok else 'FAILED' if ok is False else 'MISSING'}")
            if not ok:
                problems.append(f"{bar}: Telegram for '{s}' {'failed' if ok is False else 'never sent'}: resend the report, not the order")
        row["telegram"] = ", ".join(marks)
        rows.append(row)
    for tk, d in ins.items():
        if tk not in used:
            problems.append(f"deal {tk} at {d['time_server']} server has the EA's magic but no event: a second EA or a manual trade?")
    return rows, problems


def main():
    p = argparse.ArgumentParser()
    p.add_argument("ea_log"); p.add_argument("deals"); p.add_argument("telegram_log")
    p.add_argument("--offset", type=int, required=True)
    a = p.parse_args()
    rows, problems = reconcile(read(a.ea_log, "cp1252"), read(a.deals), read(a.telegram_log), a.offset)
    cols = [("event", 11), ("outcome", 16), ("close_utc", 11), ("lag", 5), ("ticket", 8), ("slip", 20), ("pnl", 7)]
    print(" ".join(f"{c:<{w}}" for c, w in cols) + " telegram")
    for r in rows:
        print(" ".join(f"{r[c]:<{w}}" for c, w in cols) + " " + r["telegram"])
    print(f"{len(rows)} events | " + ", ".join(f"{s} {sum(r['outcome'] == s for r in rows)}"
                                              for s in OUTCOMES if any(r["outcome"] == s for r in rows)))
    for x in problems:
        print("  " + x)
    print("OK" if not problems else f"{len(problems)} problem(s)")


if __name__ == "__main__":
    main()

In Windows PowerShell, from C:\trade-system-lab. File → Open Data Folder in MT5 shows where MQL5\Files is; copy the EA log from there:

Copy-Item "[DATA FOLDER]\MQL5\Files\demo_guard_log.csv" data\
.venv\Scripts\python src\report_events.py data\demo_guard_log.csv
.venv\Scripts\python src\export_deals.py 2026-11-23 2026-11-27 36036
.venv\Scripts\python src\reconcile_events.py data\demo_guard_log.csv data\deals.csv logs\telegram_sent.csv --offset 2

A made-up week of 10 events on XAUUSD H1, server at UTC+2. The reporter’s output, with a Telegram failure on the last message:

sent   DEMO | FILLED | event XAUUSD|H1|2026.11.23 09:00|ema-cross-v1 | filled: ticket 7710001, 0.05 lot at 4060.24
sent   DEMO | REFUSED | event XAUUSD|H1|2026.11.23 15:00|ema-cross-v1 | no trade: spread 62 > 50 points
sent   DEMO | REJECTED | event XAUUSD|H1|2026.11.24 07:00|ema-cross-v1 | rejected by the server: 10006 Request rejected
sent   DEMO | FILLED | event XAUUSD|H1|2026.11.24 13:00|ema-cross-v1 | filled: ticket 7710002, 0.05 lot at 4071.88
sent   DEMO | REFUSED | event XAUUSD|H1|2026.11.24 14:00|ema-cross-v1 | no trade: a position or order already exists on the symbol
sent   DEMO | FILLED | event XAUUSD|H1|2026.11.25 10:00|ema-cross-v1 | filled: ticket 7710003, 0.05 lot at 4090.10
sent   DEMO | DUPLICATE | event XAUUSD|H1|2026.11.25 10:00|ema-cross-v1 | duplicate event blocked: not sent again
sent   DEMO | UNKNOWN | event XAUUSD|H1|2026.11.25 16:00|ema-cross-v1 | UNKNOWN after retcode 10031: EA blocked, check the terminal
sent   DEMO | RESOLVED_BY_HAND | event XAUUSD|H1|2026.11.25 16:00|ema-cross-v1 | the unknown state was checked by hand; the EA runs again
sent   DEMO | FILLED | event XAUUSD|H1|2026.11.26 08:00|ema-cross-v1 | filled: ticket 7710004, 0.05 lot at 4095.62
sent   DEMO | REFUSED | event XAUUSD|H1|2026.11.26 12:00|ema-cross-v1 | no trade: stop 1000 points within stops level 1200; not dropping the SL
FAILED DEMO | FILLED | event XAUUSD|H1|2026.11.27 09:00|ema-cross-v1 | filled: ticket 7710005, 0.05 lot at 4102.33

The reconciliation:

event       outcome          close_utc   lag   ticket   slip                 pnl     telegram
11.23 09:00 filled           11-23 08:00 +1s   7710001  +4 pt (+0.20 USD)    +99.10  filled ok
11.23 15:00 refused          11-23 14:00                                     none    refused ok
11.24 07:00 rejected         11-24 06:00                                     none    rejected ok
11.24 13:00 filled           11-24 12:00 +1s   7710002  +38 pt (+1.90 USD)   -52.60  filled ok
11.24 14:00 refused          11-24 13:00                                     none    refused ok
11.25 10:00 filled           11-25 09:00 +1s   7710003  +0 pt (+0.00 USD)    open    filled ok, duplicate ok
11.25 16:00 resolved_by_hand 11-25 15:00                                     none    resolved_by_hand ok
11.26 08:00 filled           11-26 07:00 -39s  7710004  +2 pt (+0.10 USD)    open    filled ok
11.26 12:00 refused          11-26 11:00                                     none    refused ok
11.27 09:00 filled           11-27 08:00 +1s   7710005  +3 pt (+0.15 USD)    open    filled FAILED
10 events | filled 5, rejected 1, resolved_by_hand 1, refused 3
  2026.11.26 08:00: deal 39 s before 'sent': the PC clock is off; sync Windows time
  2026.11.27 09:00: Telegram for 'filled' failed: resend the report, not the order
  deal 7710099 at 2026.11.27 15:12:44 server has the EA's magic but no event: a second EA or a manual trade?
3 problem(s)

How to read it:

  • lag: seconds from “sent” in the EA log to the MT5 deal. −39 s on 11.26 is impossible; the PC clock (which the EA’s TimeGMT() uses) runs fast. Sync Windows time, and treat that day’s EA timestamps as 40 s early.
  • slip: positive is worse for a buy. 38 points on 11.24 cost 1.90 USD on 0.05 lot, so that trade risked 51.90 USD rather than 50.00, and the SL closed it at −52.60 after commission.
  • pnl: only for filled events, from MT5’s exit deal; “none” for refusals, which must never show a P/L.
  • telegram: the 11.27 fill was never reported. Rerun the reporter; never resend the order.
  • The stray deal: 7710099 carries the EA’s magic number but has no event. A second copy of the EA on another chart, or a manual trade with that magic? Find out before trusting any total.

The ten events cover what the capstone needs: 5 filled, 3 refused with reasons (spread, an open position, stops level), 1 rejected by the server, 1 unknown resolved by hand, and 1 duplicate blocked on 11.25.

The tests, tests/test_reconcile_events.py:

# tests/test_reconcile_events.py: the reconciliation rules on one or two hand-made events.
from src.reconcile_events import reconcile
from src.report_events import message

EID = "XAUUSD|H1|2026.11.23 09:00|ema-cross-v1"


def ea(*lines):
    keys = ("logged_gmt", "event_id", "state", "retcode", "ticket", "volume", "price", "reason")
    return [dict(zip(keys, l)) for l in lines]


FILLED = ea(("2026.11.23 08:00:01", EID, "checked", "0", "0", "0.05", "4060.20", ""),
            ("2026.11.23 08:00:01", EID, "sent", "0", "0", "0.05", "4060.20", ""),
            ("2026.11.23 08:00:02", EID, "filled", "10009", "77", "0.05", "4060.24", ""))
DEAL = [dict(ticket="77", time_server="2026.11.23 10:00:02", entry="0", volume="0.05", price="4060.24",
             position_id="77", commission="-0.35", profit="0")]
TOLD = [dict(event_id=EID, state="filled", ok="1")]


def test_clean_event_reconciles():
    rows, problems = reconcile(FILLED, DEAL, TOLD, offset=2)
    assert problems == [] and rows[0]["slip"] == "+4 pt (+0.20 USD)" and rows[0]["pnl"] == "open"


def test_ea_log_and_mt5_must_agree():
    rows, problems = reconcile(FILLED, [dict(DEAL[0], price="4060.54")], TOLD, offset=2)
    assert problems == [f"2026.11.23 09:00: EA log says 0.05 at 4060.24, MT5 says 0.05 at 4060.54"]


def test_wrong_offset_shows_as_logged_before_close():
    _, problems = reconcile(FILLED, DEAL, TOLD, offset=1)
    assert any("before the bar closed" in p for p in problems)


def test_missing_telegram_and_stray_deal_are_reported():
    stray = DEAL + [dict(DEAL[0], ticket="99", position_id="99")]
    _, problems = reconcile(FILLED, stray, [], offset=2)
    assert problems == ["2026.11.23 09:00: Telegram for 'filled' never sent: resend the report, not the order",
                        "deal 99 at 2026.11.23 10:00:02 server has the EA's magic but no event: a second EA or a manual trade?"]


def test_declined_message_claims_no_profit():
    text = message(dict(event_id=EID, state="refused", reason="spread 62 > 50 points", retcode="0",
                        ticket="0", volume="0.00", price="0.00"))
    assert text.startswith("DEMO | REFUSED") and "no trade" in text and " USD" not in text and "profit" not in text

Run .venv\Scripts\python -m pytest -q tests; you should see 5 passed.

The drill on demo

  1. Run the Strategy Tester first; then the demo account, with the symbol allowlist and one single EA on the chart.
  2. Reconcile timestamps, event ID, order number, SL/TP and state between MT5’s Journal and History and Telegram. Webhook status, if you use it, goes in a separate notification table, never reconciled like an order.
  3. Disconnect the network, send a duplicate event, trigger the kill switch; check the EA stops opening new orders.

Try it: review the capstone design

Review the attached capstone design. Draw two separate paths: the demo order path (code on MT5 candles → checks → demo EA → report) and the notification path (TradingView alert → receiver → log, Telegram). There is no arrow from the notification path to the order path. Test table for the order path: normal and duplicate events, stale data, unknown symbol, a non-demo account, missing SL, lot off the step, broker rejection, Telegram failure, restart and kill switch. Test table for the notification path: bad payload, a webhook with a duplicate event_id, a webhook that never arrives (Webhook status in the Alert log), a receiver answering slower than 3 seconds. Each row needs the expected action, the log line to see and the pass criterion. Confirm the code refuses every non-demo account, Telegram only reads, reports contain no secrets, and a retry can't create a duplicate order. Analyse the design and the demo account only; don't enable live orders.

Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.

Key takeaways

  • The timestamps run: MT5 candle closes, the EA takes the event, sends the request, gets confirmation; if the fill differs, compute the gap and never edit the original log.
  • A signal that passes but whose minimum lot exceeds the budget: no order, logged as refused with the reason; Telegram says DEMO with no P/L.
  • Drill on demo: cut the network, trigger the kill switch, and check the EA has stopped opening new orders.

Comments