What does an EA have to check before and after it sends a demo order, and why isn’t a passing OrderCheck enough?
This post builds a chain of checks that fails closed (when a condition is missing, the EA stands still) and logs checked, sent and filled as separate events. The easy mistake: guessing. If the EA can’t read whether the account is demo or real, it doesn’t guess; it stops and reports what’s missing.
Terms used below:
- Fail-closed: when a condition isn’t met or a state is unknown, refuse to act and give the reason.
- OrderCheck: MT5’s check of a trade request (margin, volume, stops) without sending it.
- OrderSend: sends the request; its answer has a retcode, and for a market order the deal ticket, volume and price.
- Retcode: the numeric result of a trade request, e.g. 10009 done, 10010 partly done, 10031 no connection.
- Allowlist: the symbols the EA may trade; everything else is refused.
The checks before a demo request
Before any demo request, check the account mode and permissions, the rule version, the symbol allowlist, a fresh enough quote, the spread and risk limits, the volume step, the stop distance and any existing orders. Call OrderCheck and read the retcode. When sending, read the retcode, the deal and the real fill. Netting and hedging accounts need their own design, tests and logs; this EA treats any position or pending order on the symbol as exposure, which works on both. No keys are created and no real account is touched in this post.
| Gate | Question | If not |
|---|---|---|
| Input | A signal from a closed MT5 candle | |
| 1 | Is the account confirmed as demo? | Stand still, report the missing condition |
| 2 | Symbol on the allowlist, quote fresh? | Refuse, log the reason |
| 3 | A valid SL and TP, stop far enough away? | Refuse; never drop the SL |
| 4 | Volume rounded down to the step still within min and max? | Refuse, log the reason; never round up to the minimum |
| 5 | Event ID not processed yet? | Return the known state; don’t send again |
| 6 | Does OrderCheck pass? | Read the retcode; don’t send |
| Passed | OrderSend on demo; log the retcode and ticket |
If a condition is missing or a state is unknown, the EA stands still and gives
the reason. TradingEnabled is false by default.
OrderCheck passing isn’t “filled”
The structural check passes, but the terminal loses its connection before the send.
- Log checked, sent and filled as three separate events.
- If you don’t know whether it was sent, look the state up by ID before any retry.
- Never send twice because no answer came back.
- The Telegram message reports the error or the unknown state, labelled DEMO; never a made-up profit.
| Wrong | Right |
|---|---|
| OrderCheck true → log “filled” | Checked, sent and filled are three separate events |
| No answer yet → send again | Look the state up by ID before any retry |
| No Telegram message yet → create a new order | Telegram reports the unknown state, labelled DEMO |
Retrying while the state is unknown can open a duplicate position. Look it up by ID first; reporting is a separate step of the flow.
Worked example: a valid request the terminal still refuses
Say XAUUSD needs a minimum of 0.01 lot with a 0.01 step, and the demo’s stops level differs from what the code assumes. The bot works out 0.009 lot, or places the stop too close. The right behaviour is to log that the conditions aren’t met. Don’t round up to 0.01 to force a trade, and don’t drop the SL to avoid the error.
The arithmetic for that case: with a 1,000-point stop (10 USD on gold with two decimals) and a tick value of 1 USD per 0.01 move per lot, one lot loses 1,000 USD at the stop. A risk budget of 9 USD gives 9 ÷ 1,000 = 0.009 lot, below the 0.01 minimum, so the request is refused. Rounding up would risk 10 USD, more than the budget you set.
Before the request, check the demo account mode, the symbol’s trade mode, fresh quote data, the quantity, the margin and the stop. After it, read the retcode and the real state; “the function returned” doesn’t replace a confirmed ticket. On a partial fill, update the real quantity and recompute the risk and the exit under the policy you wrote down.
| When | Step | What |
|---|---|---|
| Not sent yet | Before the request | Demo, trade mode, fresh quote, quantity, margin, stop |
| OrderSend | Send the request | Demo account only |
| An answer came | After the request | Read the retcode and the real state; wait for a confirmed ticket |
| If it happens | Partial fill | Update the real quantity; recompute risk and exit |
The EA, DemoGuard.mq5. It signals on an EMA cross on the last closed bar,
only to have something to gate; the gates are the point. Every refusal names
its reason, the log is read back on start so a sent event is never sent again,
and an unclear answer makes it look for its own position or deal before
anything else. If it can’t find one, it blocks until you check by hand:
//+------------------------------------------------------------------+
//| DemoGuard.mq5: a demo-only EA whose every gate fails closed. |
//| A missing or unknown condition means: do nothing, log why. |
//| Signal: EMA fast crosses above EMA slow on the last closed bar. |
//+------------------------------------------------------------------+
#property version "1.00"
input bool TradingEnabled = false; // false: every check and OrderCheck run, nothing is sent
input string AllowedSymbols = "XAUUSD"; // comma-separated, exact Market Watch names
input string RuleVersion = "ema-cross-v1";
input int EmaFast = 8;
input int EmaSlow = 21;
input double RiskMoney = 0; // account currency per trade; 0 = not set = no request
input int SlPoints = 0; // stop distance in points; 0 = not set = no request
input double TpR = 2.0; // take profit at TpR x the stop distance
input int MaxSpreadPoints = 0; // 0 = not set = no request
input int MaxQuoteAgeSec = 10;
input int DeviationPoints = 20;
input ulong Magic = 36036;
input string ResolvedUnknown = ""; // paste an event_id here after checking it by hand
#define LOG_FILE "demo_guard_log.csv"
#define STOP_FILE "STOP"
int g_fast = INVALID_HANDLE, g_slow = INVALID_HANDLE;
datetime g_last_bar = 0;
string g_seen[]; // event_ids that reached "sent": never sent again, even after a restart
string g_block = ""; // non-empty: stand still until a person fixes the cause and restarts the EA
//--- one CSV line per decision; the same file is read back on start
void Log(string event_id, string state, long retcode, ulong ticket, double volume, double price, string reason)
{
string r = reason;
StringReplace(r, ",", ";");
int h = FileOpen(LOG_FILE, FILE_READ|FILE_WRITE|FILE_CSV|FILE_ANSI|FILE_SHARE_READ, ',');
if(h == INVALID_HANDLE) { Print("cannot open ", LOG_FILE, ": ", GetLastError()); return; }
if(FileSize(h) == 0)
FileWrite(h, "logged_gmt", "event_id", "state", "retcode", "ticket", "volume", "price", "reason");
FileSeek(h, 0, SEEK_END);
FileWrite(h, TimeToString(TimeGMT(), TIME_DATE|TIME_SECONDS), event_id, state, IntegerToString(retcode),
IntegerToString((long)ticket), DoubleToString(volume, 2), DoubleToString(price, _Digits), r);
FileClose(h);
PrintFormat("%s | %s | %s", state, event_id, r);
}
bool Seen(string id)
{
for(int i = 0; i < ArraySize(g_seen); i++)
if(g_seen[i] == id) return true;
return false;
}
void AddSeen(string id)
{
int n = ArraySize(g_seen);
ArrayResize(g_seen, n + 1);
g_seen[n] = id;
}
//--- read the log back: sent events stay sent; an unresolved "unknown" blocks everything
void LoadLog()
{
ArrayResize(g_seen, 0);
if(!FileIsExist(LOG_FILE)) return;
int h = FileOpen(LOG_FILE, FILE_READ|FILE_CSV|FILE_ANSI|FILE_SHARE_READ|FILE_SHARE_WRITE, ',');
if(h == INVALID_HANDLE) { g_block = "cannot read the log: duplicates can't be ruled out"; return; }
string unknown = "";
while(!FileIsEnding(h))
{
string c[8];
for(int i = 0; i < 8; i++) c[i] = FileReadString(h);
if(c[2] == "sent" && !Seen(c[1])) AddSeen(c[1]);
if(c[2] == "unknown") unknown = c[1];
if((c[2] == "resolved_filled" || c[2] == "resolved_by_hand") && c[1] == unknown) unknown = "";
}
FileClose(h);
if(unknown != "" && unknown == ResolvedUnknown)
Log(unknown, "resolved_by_hand", 0, 0, 0, 0, "checked in the terminal by a person");
else if(unknown != "")
g_block = "unknown state for " + unknown + ": check the Trade and History tabs; then set ResolvedUnknown";
}
bool Allowed(string sym)
{
string parts[];
int n = StringSplit(AllowedSymbols, ',', parts);
for(int i = 0; i < n; i++)
{
StringTrimLeft(parts[i]);
StringTrimRight(parts[i]);
if(parts[i] == sym) return true;
}
return false;
}
bool HasExposure(string sym) // any position or pending order on the symbol, from any source
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
if(PositionGetTicket(i) > 0 && PositionGetString(POSITION_SYMBOL) == sym) return true;
for(int i = OrdersTotal() - 1; i >= 0; i--)
if(OrderGetTicket(i) > 0 && OrderGetString(ORDER_SYMBOL) == sym) return true;
return false;
}
//--- after an unclear answer: look for our position or entry deal before doing anything else
bool Lookup(string sym, datetime since, ulong &ticket, double &volume, double &price)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong t = PositionGetTicket(i);
if(t > 0 && PositionGetString(POSITION_SYMBOL) == sym && (ulong)PositionGetInteger(POSITION_MAGIC) == Magic
&& (datetime)PositionGetInteger(POSITION_TIME) >= since)
{
ticket = t; volume = PositionGetDouble(POSITION_VOLUME); price = PositionGetDouble(POSITION_PRICE_OPEN);
return true;
}
}
if(HistorySelect(since, TimeCurrent() + 60))
for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
{
ulong d = HistoryDealGetTicket(i);
if(d > 0 && HistoryDealGetString(d, DEAL_SYMBOL) == sym && (ulong)HistoryDealGetInteger(d, DEAL_MAGIC) == Magic
&& HistoryDealGetInteger(d, DEAL_ENTRY) == DEAL_ENTRY_IN)
{
ticket = d; volume = HistoryDealGetDouble(d, DEAL_VOLUME); price = HistoryDealGetDouble(d, DEAL_PRICE);
return true;
}
}
return false;
}
ENUM_ORDER_TYPE_FILLING Filling(string sym)
{
long modes = SymbolInfoInteger(sym, SYMBOL_FILLING_MODE);
if((modes & SYMBOL_FILLING_FOK) != 0) return ORDER_FILLING_FOK;
if((modes & SYMBOL_FILLING_IOC) != 0) return ORDER_FILLING_IOC;
return ORDER_FILLING_RETURN;
}
int OnInit()
{
g_fast = iMA(_Symbol, _Period, EmaFast, 0, MODE_EMA, PRICE_CLOSE);
g_slow = iMA(_Symbol, _Period, EmaSlow, 0, MODE_EMA, PRICE_CLOSE);
if(g_fast == INVALID_HANDLE || g_slow == INVALID_HANDLE) return INIT_FAILED;
LoadLog();
bool tester = MQLInfoInteger(MQL_TESTER) != 0; // the Strategy Tester only simulates orders
if(!tester && AccountInfoInteger(ACCOUNT_TRADE_MODE) != ACCOUNT_TRADE_MODE_DEMO)
g_block = "account is not confirmed as demo";
if(g_block != "") Log("-", "blocked", 0, 0, 0, 0, g_block);
Comment(g_block == "" ? "DemoGuard: DEMO, TradingEnabled=" + (TradingEnabled ? "true" : "false")
: "DemoGuard BLOCKED: " + g_block);
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
IndicatorRelease(g_fast);
IndicatorRelease(g_slow);
Comment("");
}
void OnTick()
{
datetime bar = iTime(_Symbol, _Period, 1); // the last closed bar
if(bar == 0 || bar == g_last_bar) return; // once per closed bar
g_last_bar = bar;
if(g_block != "") return; // already logged once in OnInit
double f[], s[];
ArraySetAsSeries(f, true);
ArraySetAsSeries(s, true);
if(CopyBuffer(g_fast, 0, 1, 2, f) != 2 || CopyBuffer(g_slow, 0, 1, 2, s) != 2) return;
if(!(f[1] <= s[1] && f[0] > s[0])) return; // no cross on the closed bar: nothing to log
string sym = _Symbol;
string id = StringFormat("%s|%s|%s|%s", sym, StringSubstr(EnumToString(_Period), 7),
TimeToString(bar, TIME_DATE|TIME_MINUTES), RuleVersion);
if(FileIsExist(STOP_FILE)) { Log(id, "refused", 0, 0, 0, 0, "STOP file present"); return; }
if(RiskMoney <= 0 || SlPoints <= 0 || MaxSpreadPoints <= 0)
{ Log(id, "refused", 0, 0, 0, 0, "RiskMoney/SlPoints/MaxSpreadPoints not set"); return; }
if(Seen(id)) { Log(id, "duplicate", 0, 0, 0, 0, "already sent; not sending again"); return; }
if(!Allowed(sym)) { Log(id, "refused", 0, 0, 0, 0, "symbol not in AllowedSymbols"); return; }
long mode = SymbolInfoInteger(sym, SYMBOL_TRADE_MODE);
if(mode != SYMBOL_TRADE_MODE_FULL && mode != SYMBOL_TRADE_MODE_LONGONLY)
{ Log(id, "refused", 0, 0, 0, 0, "symbol trade mode doesn't allow buys"); return; }
MqlTick tick;
double point = SymbolInfoDouble(sym, SYMBOL_POINT);
if(!SymbolInfoTick(sym, tick) || TimeCurrent() - tick.time > MaxQuoteAgeSec)
{ Log(id, "refused", 0, 0, 0, 0, "no fresh quote"); return; }
double spread = (tick.ask - tick.bid) / point;
if(spread > MaxSpreadPoints) { Log(id, "refused", 0, 0, 0, 0, StringFormat("spread %.0f > %d points", spread, MaxSpreadPoints)); return; }
long stops = SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL);
if(SlPoints <= stops) { Log(id, "refused", 0, 0, 0, 0, StringFormat("stop %d points within stops level %d; not dropping the SL", SlPoints, (int)stops)); return; }
double tick_value = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE_LOSS);
double tick_size = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE);
double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
double vmin = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN), vmax = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);
if(tick_value <= 0 || tick_size <= 0 || step <= 0) { Log(id, "refused", 0, 0, 0, 0, "tick value/size or volume step unknown"); return; }
double loss_per_lot = SlPoints * point / tick_size * tick_value;
double raw = RiskMoney / loss_per_lot;
double vol = MathFloor(raw / step + 1e-9) * step; // down to the step, never up
int vdigits = (int)MathMax(0, MathCeil(-MathLog10(step) - 1e-9));
vol = NormalizeDouble(vol, vdigits);
if(vol < vmin) { Log(id, "refused", 0, 0, 0, 0, StringFormat("volume %.3f below minimum %.2f; not rounding up", raw, vmin)); return; }
if(vol > vmax) { Log(id, "refused", 0, 0, 0, 0, StringFormat("volume %.2f above maximum %.2f; check RiskMoney", vol, vmax)); return; }
if(HasExposure(sym)) { Log(id, "refused", 0, 0, 0, 0, "a position or order already exists on the symbol"); return; }
int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
MqlTradeRequest req;
MqlTradeResult res;
MqlTradeCheckResult chk;
ZeroMemory(req); ZeroMemory(res); ZeroMemory(chk);
req.action = TRADE_ACTION_DEAL;
req.symbol = sym;
req.volume = vol;
req.type = ORDER_TYPE_BUY;
req.price = tick.ask;
req.sl = NormalizeDouble(tick.ask - SlPoints * point, digits);
req.tp = NormalizeDouble(tick.ask + TpR * SlPoints * point, digits);
req.deviation = DeviationPoints;
req.magic = Magic;
req.comment = "DemoGuard";
req.type_filling = Filling(sym);
if(!OrderCheck(req, chk) || chk.retcode != 0)
{ Log(id, "check_failed", chk.retcode, 0, vol, req.price, chk.comment); return; }
Log(id, "checked", 0, 0, vol, req.price, StringFormat("risk %.2f; margin %.2f; free after %.2f", vol * loss_per_lot, chk.margin, chk.margin_free));
if(!TradingEnabled) { Log(id, "not_sent", 0, 0, vol, req.price, "TradingEnabled=false"); return; }
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) || !MQLInfoInteger(MQL_TRADE_ALLOWED))
{ Log(id, "refused", 0, 0, vol, req.price, "Algo Trading is off in the terminal or for this EA"); return; }
AddSeen(id); // before sending: a crash mid-send must not lead to a resend
Log(id, "sent", 0, 0, vol, req.price, "");
datetime since = TimeCurrent() - 60;
if(!OrderSend(req, res)) // false isn't proof of "not filled": read the retcode
Print("OrderSend returned false, retcode ", res.retcode);
uint rc = res.retcode;
if(rc == TRADE_RETCODE_DONE && res.deal > 0)
Log(id, "filled", rc, res.deal, res.volume, res.price, "");
else if(rc == TRADE_RETCODE_DONE_PARTIAL)
Log(id, "partial", rc, res.deal, res.volume, res.price,
StringFormat("filled %.2f of %.2f; risk now %.2f", res.volume, vol, res.volume * loss_per_lot));
else if(rc == TRADE_RETCODE_DONE || rc == 0 || rc == TRADE_RETCODE_TIMEOUT || rc == TRADE_RETCODE_CONNECTION
|| rc == TRADE_RETCODE_ERROR)
{
ulong t = 0; double v = 0, p = 0;
if(Lookup(sym, since, t, v, p))
Log(id, "resolved_filled", rc, t, v, p, "found in positions or history after an unclear answer");
else
{
g_block = "unknown state for " + id + ": check the Trade and History tabs; then set ResolvedUnknown";
Log(id, "unknown", rc, 0, vol, req.price, res.comment);
Comment("DemoGuard BLOCKED: " + g_block);
}
}
else
Log(id, "rejected", rc, 0, vol, req.price, res.comment);
}To install it: MetaEditor (F4) → File → New → Expert Advisor (template), save
it as DemoGuard in MQL5\Experts, paste the code over the template and
compile with F7. Fix every error before anything else. Then View → Strategy
Tester: pick DemoGuard, XAUUSD, H1, a few months, “Every tick based on real
ticks” if your broker provides them, and Visualization.
| Input | First run | Why |
|---|---|---|
TradingEnabled |
false |
Every gate and OrderCheck run; nothing is sent |
RiskMoney |
50 | 0 means not set, and the EA refuses |
SlPoints |
1000 | 10 USD on two-decimal gold; 0 refuses |
MaxSpreadPoints |
50 | 0 refuses; check your symbol’s usual spread |
AllowedSymbols |
XAUUSD |
The exact Market Watch name |
The Strategy Tester only simulates orders, so the demo check is skipped
there; on a chart, a non-demo account blocks the EA in OnInit. The log is
demo_guard_log.csv in MQL5\Files; in the Strategy Tester, in the tester
agent’s own MQL5\Files folder.
The test cases to run in the Strategy Tester, one input change at a time:
| Case | Change | Expected log line |
|---|---|---|
| No SL | SlPoints = 0 |
refused, RiskMoney/SlPoints/MaxSpreadPoints not set |
| Volume below the step | RiskMoney = 9 |
refused, volume 0.009 below minimum 0.01; not rounding up |
| Stop too close | SlPoints under the symbol’s stops level |
refused, not dropping the SL |
| High spread | MaxSpreadPoints = 1 |
refused, spread … > 1 points |
| Not on the allowlist | AllowedSymbols = EURUSD |
refused, symbol not in AllowedSymbols |
| Kill switch | An empty file named STOP in the agent’s MQL5\Files |
refused, STOP file present |
| Sending in the tester | TradingEnabled = true |
checked, sent, filled with ticket, volume and price |
Duplicates and unknown states can’t be forced in the tester. On the demo
chart, remove and re-add the EA during a bar after a sent: the same event
must log duplicate. If a real unknown ever appears, the EA stays blocked
until you’ve looked at the Trade and History tabs and pasted that event ID
into ResolvedUnknown.
Checking the log, not trusting it
Ask the AI for tests of refusals, lost connections and unclear results. The output must keep the event, the request and the broker’s response linked, with secrets masked. Never retry with a new order just because no Telegram message arrived; reporting is a different step.
A script that checks the log follows the rules, src/check_guard_log.py:
# src/check_guard_log.py: check DemoGuard's log keeps checked, sent and filled apart. Reads the file only.
# .venv\Scripts\python src\check_guard_log.py data\demo_guard_log.csv
import csv, sys
from collections import Counter
FILLS = ("filled", "partial", "resolved_filled")
NEEDS_REASON = ("refused", "check_failed", "rejected", "unknown", "blocked")
def problems(rows):
out, checked, sent, open_unknown = [], set(), Counter(), None
for n, r in enumerate(rows, start=2): # line 1 is the header
eid, state = r["event_id"], r["state"]
if state == "checked":
checked.add(eid)
elif state == "sent":
if eid not in checked:
out.append(f"line {n}: {eid} sent without a checked line before it")
if sent[eid]:
out.append(f"line {n}: {eid} sent a second time")
if open_unknown:
out.append(f"line {n}: {eid} sent while {open_unknown} was still unknown")
sent[eid] += 1
elif state in FILLS:
if not sent[eid]:
out.append(f"line {n}: {eid} {state} but never sent")
if int(r["ticket"]) <= 0 or float(r["volume"]) <= 0 or float(r["price"]) <= 0:
out.append(f"line {n}: {eid} {state} without ticket, volume and price")
if open_unknown == eid:
open_unknown = None
elif state == "unknown":
open_unknown = eid
elif state == "resolved_by_hand" and open_unknown == eid:
open_unknown = None
if state in NEEDS_REASON and not r["reason"] and r["retcode"] in ("", "0"):
out.append(f"line {n}: {eid} {state} with no reason or retcode")
if open_unknown:
out.append(f"end: {open_unknown} is still unknown; the EA must stay blocked")
return out
def main(path):
with open(path, newline="", encoding="cp1252") as f: # MT5 writes FILE_ANSI
rows = list(csv.DictReader(f))
states = Counter(r["state"] for r in rows)
print(f"{len(rows)} lines | " + " | ".join(f"{k} {v}" for k, v in sorted(states.items())))
found = problems(rows)
for p in found:
print(" " + p)
print("OK" if not found else f"{len(found)} problem(s)")
return 1 if found else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1]))On a made-up log (copied to data\demo_guard_log.csv) with two planted
mistakes at the end:
logged_gmt,event_id,state,retcode,ticket,volume,price,reason
2026.12.01 09:00:02,XAUUSD|H1|2026.12.01 08:00|ema-cross-v1,refused,0,0,0.00,0.00,volume 0.009 below minimum 0.01; not rounding up
2026.12.01 13:00:01,XAUUSD|H1|2026.12.01 12:00|ema-cross-v1,refused,0,0,0.00,0.00,stop 30 points within stops level 50; not dropping the SL
2026.12.01 18:00:03,XAUUSD|H1|2026.12.01 17:00|ema-cross-v1,checked,0,0,0.05,4187.35,risk 50.00; margin 418.74; free after 9581.26
2026.12.01 18:00:03,XAUUSD|H1|2026.12.01 17:00|ema-cross-v1,not_sent,0,0,0.05,4187.35,TradingEnabled=false
2026.12.02 10:00:02,XAUUSD|H1|2026.12.02 09:00|ema-cross-v1,checked,0,0,0.05,4201.10,risk 50.00; margin 420.11; free after 9579.89
2026.12.02 10:00:02,XAUUSD|H1|2026.12.02 09:00|ema-cross-v1,sent,0,0,0.05,4201.10,
2026.12.02 10:00:02,XAUUSD|H1|2026.12.02 09:00|ema-cross-v1,filled,10009,7704211,0.05,4201.14,
2026.12.02 15:00:01,XAUUSD|H1|2026.12.02 14:00|ema-cross-v1,checked,0,0,0.05,4195.60,risk 50.00; margin 419.56; free after 9530.44
2026.12.02 15:00:01,XAUUSD|H1|2026.12.02 14:00|ema-cross-v1,sent,0,0,0.05,4195.60,
2026.12.02 15:00:31,XAUUSD|H1|2026.12.02 14:00|ema-cross-v1,unknown,10031,0,0.05,4195.60,No connection
2026.12.02 15:04:12,XAUUSD|H1|2026.12.02 14:00|ema-cross-v1,resolved_by_hand,0,0,0.00,0.00,checked in the terminal by a person
2026.12.03 11:00:02,XAUUSD|H1|2026.12.03 10:00|ema-cross-v1,checked,0,0,0.05,4210.05,risk 50.00; margin 421.01; free after 9528.99
2026.12.03 11:00:02,XAUUSD|H1|2026.12.03 10:00|ema-cross-v1,sent,0,0,0.05,4210.05,
2026.12.03 11:00:03,XAUUSD|H1|2026.12.03 10:00|ema-cross-v1,sent,0,0,0.05,4210.05,
2026.12.03 11:00:03,XAUUSD|H1|2026.12.03 10:00|ema-cross-v1,filled,10009,0,0.05,4210.09,.venv\Scripts\python src\check_guard_log.py data\demo_guard_log.csv from
C:\trade-system-lab prints:
15 lines | checked 4 | filled 2 | not_sent 1 | refused 2 | resolved_by_hand 1 | sent 4 | unknown 1
line 15: XAUUSD|H1|2026.12.03 10:00|ema-cross-v1 sent a second time
line 16: XAUUSD|H1|2026.12.03 10:00|ema-cross-v1 filled without ticket, volume and price
2 problem(s)Line 15 is the double send this whole design exists to prevent, and line 16 claims a fill with ticket 0. The unknown on line 11 is fine: nothing was sent until a person resolved it on line 12.
The tests, tests/test_check_guard_log.py:
# tests/test_check_guard_log.py: each rule on a few hand-made lines.
from src.check_guard_log import problems
def row(eid, state, ticket="0", volume="0.05", price="4200.00", reason="", retcode="0"):
return dict(event_id=eid, state=state, ticket=ticket, volume=volume, price=price, reason=reason, retcode=retcode)
def test_clean_flow_has_no_problems():
rows = [row("A", "checked"), row("A", "sent"), row("A", "filled", ticket="77", retcode="10009")]
assert problems(rows) == []
def test_checked_is_not_filled_and_sent_needs_checked():
assert problems([row("A", "sent")]) == ["line 2: A sent without a checked line before it"]
assert problems([row("A", "checked"), row("A", "filled", ticket="77")]) == ["line 3: A filled but never sent"]
def test_no_second_send_and_no_send_while_unknown():
rows = [row("A", "checked"), row("A", "sent"), row("A", "unknown", reason="No connection"),
row("B", "checked"), row("B", "sent")]
assert problems(rows) == ["line 6: B sent while A was still unknown",
"end: A is still unknown; the EA must stay blocked"]
rows = [row("A", "checked"), row("A", "sent"), row("A", "sent")]
assert problems(rows) == ["line 4: A sent a second time"]
def test_unresolved_unknown_is_reported():
rows = [row("A", "checked"), row("A", "sent"), row("A", "unknown", reason="timeout")]
assert problems(rows) == ["end: A is still unknown; the EA must stay blocked"]
def test_refusal_needs_a_reason():
assert problems([row("A", "refused")]) == ["line 2: A refused with no reason or retcode"]Run .venv\Scripts\python -m pytest -q tests; you should see 5 passed.
Try it: a demo-only EA from a spec
Create a demo-only MQL5 Expert Advisor from this spec. First read the official MetaQuotes documentation on account trade mode, OrderCheck, OrderSend, symbol volume and stop properties, and the Strategy Tester. Mandatory rules: a live account is refused; `TradingEnabled=false` by default; signals are only processed on closed bars; a valid SL and TP are required; the symbol must be on the allowlist; volume is rounded to min/max/step; at most one position per symbol; every loss threshold or limit must be configured by the user, and if one is empty no request is sent. Prevent duplicate signals with an event ID from symbol + timeframe + bar time + rule version. Call OrderCheck before OrderSend; log only states with personal details masked, the request id/retcode and the reason for any refusal. No blind retry when a result is unclear. No credentials, no Telegram API calls, no live deployment. Write a checklist of Strategy Tester test cases: account not demo, missing SL, volume off the step, high spread, duplicate event, rejection and kill switch. Explain each file and how to compile and run the tester for a student.Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.
The order to work in:
- Ask the AI only to write MQL5; no connecting to an account and no orders while it writes.
- The EA refuses an account not confirmed as demo, a missing SL or TP, a symbol off the allowlist, or a capital limit that isn’t configured.
- OrderCheck before OrderSend; log the retcode and ticket; prevent duplicates by symbol + timeframe + bar time + rule version.
Key takeaways
- XAUUSD with a 0.01-lot minimum and 0.01 step: a result of 0.009 lot is refused with a reason; never round up, never drop the SL.
- When you don’t know whether an order went out, for example after a lost connection: look the state up by ID before any retry; never send twice.
- Trading off by default, SL and TP required, symbols on an allowlist, one position per symbol; OrderCheck (checks the request without sending) before OrderSend.
Comments