ChatGPT wrote my EA and it doesn't trade: 9 common bugs and fixes
ChatGPT wrote it. It compiles. It never places a trade.
This is not an argument against using AI to write code. A language model writes plausible code quickly. What it does not have is your broker's symbol settings, your account type, the compiler output, or the Experts log from your terminal. Most of the bugs below come from exactly that gap.
Here are nine common bugs in AI-written MetaTrader EAs, what each one leaves in the log, and how to fix it.
First: read the two tabs nobody reads
Before changing any code, open the Toolbox in MT5 (Ctrl+T) and check two tabs:
- Experts: anything the EA prints, including errors it reports.
- Journal: messages from the terminal itself, such as automated trading being disabled.
If both are empty while the EA "does nothing", that is a finding too: the EA is failing silently. Bug 4 explains why.
Bug 1: MQL4 and MQL5 mixed in one file
MQL4 (MetaTrader 4) and MQL5 (MetaTrader 5) look similar and are not the same language. Models trained on both mix them. Typical MQL4 lines that appear in .mq5 files:
OrderSend(Symbol(), OP_BUY, 0.1, Ask, 3, 0, 0); // MQL4 order call
double c = Close[0]; // MQL4 predefined array
In MQL5, OP_BUY, Ask, Bid and Close[] do not exist, and OrderSend() takes a request structure instead of a list of values. The file does not compile. The quickest way to make the errors go away is to delete or comment out the lines that fail, and sometimes that includes the order call itself.
Fix: decide the platform first, then use that platform's API throughout. For MQL5, the standard CTrade class (#include <Trade/Trade.mqh>) or a properly filled MqlTradeRequest. For MQL4, OrderSend() returns a ticket number or -1, and GetLastError() tells you why.
Bug 2: an indicator handle treated as a price
This one compiles cleanly in MQL5, which is why it survives:
double fast = iMA(_Symbol, PERIOD_CURRENT, 20, 0, MODE_EMA, PRICE_CLOSE);
double slow = iMA(_Symbol, PERIOD_CURRENT, 50, 0, MODE_EMA, PRICE_CLOSE);
if(fast > slow) { /* buy */ }
In MQL4, iMA() returns a value. In MQL5 it returns a handle, a small integer that identifies the indicator. The code above compares two ID numbers. The result never changes, so the EA either never enters or fires on the same condition forever.
Fix: create handles once in OnInit(), read values with CopyBuffer():
int g_hFast = INVALID_HANDLE;
int OnInit()
{
g_hFast = iMA(_Symbol, PERIOD_CURRENT, 20, 0, MODE_EMA, PRICE_CLOSE);
return(g_hFast == INVALID_HANDLE ? INIT_FAILED : INIT_SUCCEEDED);
}
void OnTick()
{
double fast[];
ArraySetAsSeries(fast, true); // index 0 = newest bar
if(CopyBuffer(g_hFast, 0, 0, 3, fast) < 3)
return; // data not ready yet
// fast[1] = last closed bar, fast[2] = the bar before it
}
Bug 3: buffer data read the wrong way, or before it exists
Two quieter problems sit in the same place.
Direction. Without ArraySetAsSeries(array, true), the array that CopyBuffer() fills runs from oldest to newest. Code that reads [0] as "current" is reading the oldest value it copied. A crossover check then looks at the bars in reverse and fires on the wrong condition, or on none.
Timing. Right after an indicator is created, its data may not be calculated yet. CopyBuffer() then returns -1 (often with error 4806, requested data not found). Code that ignores the return value works with an empty or stale array.
Fix: set arrays as series, check that CopyBuffer() returned the number of values you asked for, and skip the tick if it didn't.
Bug 4: the order result is never checked
In MQL5, OrderSend() returning true only means the request passed basic checks and was sent. The trade server's answer is in MqlTradeResult.retcode. AI-written code often checks neither, so a rejected order disappears without a trace.
MqlTradeRequest req;
MqlTradeResult res;
ZeroMemory(req);
ZeroMemory(res);
// ... fill req ...
if(!OrderSend(req, res) ||
(res.retcode != TRADE_RETCODE_DONE && res.retcode != TRADE_RETCODE_PLACED))
PrintFormat("Order failed: retcode=%u (%s) error=%d", res.retcode, res.comment, GetLastError());
Not zeroing the request structure is part of the same bug: fields you didn't set contain leftover values.
Fix: zero the structures, check the retcode, and print every failure. With CTrade, check ResultRetcode() after each call. Once failures are printed, the other bugs on this list identify themselves.
Bug 5: unsupported filling mode (retcode 10030)
Each MT5 symbol allows specific filling policies: Fill or Kill, Immediate or Cancel, or Return. They vary by broker and account type. Code that hard-codes one of them is rejected with 10030 (TRADE_RETCODE_INVALID_FILL) wherever that policy isn't allowed.
Fix: read SYMBOL_FILLING_MODE and choose an allowed policy, or with CTrade call trade.SetTypeFillingBySymbol(_Symbol) in OnInit().
Bug 6: prices, stops and volumes not normalised
The trade server rejects numbers that don't fit the symbol:
- Price not rounded to the symbol's digits or tick size: 10015 invalid price.
- Stop loss or take profit closer than the broker's stops level, or on the wrong side of the price (a sell with its stop below entry): 10016 invalid stops.
- Volume not a multiple of the volume step, or outside min/max: 10014 invalid volume.
A related favourite: points versus pips. On a 5-digit symbol, 20 * _Point is 2 pips, not 20. A stop that the author meant as 20 pips may be inside the stops level and rejected on every trade.
Fix: round prices with NormalizeDouble(price, _Digits) (and to the tick size on symbols where it differs from the point), check SYMBOL_TRADE_STOPS_LEVEL before sending, and round volume down to SYMBOL_VOLUME_STEP. If the result is below SYMBOL_VOLUME_MIN, skip and log; never round risk up silently. Our sample EA logs that case like this: [R5] below min volume: calculated 0.0008 < min 0.01 ... trade skipped.
Bug 7: magic number and position counting
A common pattern in generated EAs is to check "am I already in a trade?" by counting all open positions. A manual trade, or another EA on the same account, makes the answer "yes" forever, and the EA never enters. The reverse also happens: without a magic number filter, an EA closes or modifies trades that are not its own.
On hedging accounts, PositionSelect(_Symbol) only selects one position for the symbol, so it can't answer "how many are mine?".
Fix: set a magic number on every order (trade.SetExpertMagicNumber()), and count positions by magic and symbol:
int CountMyPositions(const ulong magic)
{
int n = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i); // also selects the position
if(ticket == 0)
continue;
if(PositionGetInteger(POSITION_MAGIC) == (long)magic &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
n++;
}
return(n);
}
Bug 8: conditions that can never be true
Some entry conditions look fine and are mathematically impossible, or always zero:
- Exact equality of doubles.
if(fast[1] == slow[1])is almost never true for two moving averages. Use a crossover: one was below on bar 2 and above on bar 1. - Integer division.
double risk = 1/100;is 0, because both numbers are integers. So isRiskPercent/100whenRiskPercentis anintinput below 100. A zero risk gives a zero lot, and the EA never trades. Write1.0/100.0. - Signals on the forming bar. A cross checked on bar 0 on every tick can appear and vanish within the same bar, so the EA either misses it or enters several times. Evaluate on the last closed bar, once per new bar, unless your rules say intrabar.
Bug 9: the environment says no
Sometimes the code is fine and the terminal or account blocks trading:
- The Algo Trading button in the toolbar is off, or "Allow Algo Trading" is unchecked in the EA's properties. Orders are refused with 10027 (
TRADE_RETCODE_CLIENT_DISABLES_AT). - The account was opened with the investor (read-only) password, or the account doesn't allow expert trading.
- The market is closed for that symbol (10018) or there is not enough margin (10019).
Fix: check permissions in OnInit() and print what you find, so the log tells you on the first run:
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
Print("Algo Trading is switched off in the terminal");
if(!MQLInfoInteger(MQL_TRADE_ALLOWED))
Print("Algo trading is not allowed for this EA (check its properties)");
if(!AccountInfoInteger(ACCOUNT_TRADE_EXPERT))
Print("This account does not allow trading by Expert Advisors");
Quick reference: what the log is telling you
| Retcode | Meaning | Usual cause in AI-written EAs |
|---|---|---|
| 10014 | Invalid volume | Volume not rounded to the volume step |
| 10015 | Invalid price | Price not normalised to digits or tick size |
| 10016 | Invalid stops | Stop inside stops level, wrong side, points vs pips |
| 10018 | Market closed | Trading outside the symbol's session |
| 10019 | No money | Lot size calculated without margin check |
| 10027 | Algo trading disabled by client | Algo Trading button or EA permission off |
| 10030 | Invalid fill | Hard-coded filling mode |
Fix it or rewrite it?
If the structure is sound, these are line-level fixes.
Often, though, the real gap is the specification. The prompt was the spec, and a prompt like "buy when the trend is strong and manage risk" leaves dozens of decisions to the model. When we take over a broken EA, we first write down what it is supposed to do as numbered rules, then decide what to keep. Every rule then logs its ID when it acts or refuses to act, like these lines from our sample EA's acceptance test:
[R1] SELL opened 0.74 lots at 1.13855 SL=1.13989 TP=1.13586
[R1] EMA cross up but close is not above trend EMA - no buy
An EA that explains every skipped trade is never "doing nothing" again. You can see which rule held it back.
Get a diagnosis, then a fixed price
Mudasir, the engineer behind AlgoTailor, has finished 680 jobs on MQL5, rated 4.9 from 620 client reviews (public MQL5 profile). A Code Rescue is a 2-hour diagnosis of your EA or indicator: what is broken, why, and what it takes to fix it. If we do the fix, the diagnosis is credited. Fixes are shown working on video before final payment, and you keep the full source code.
Book a Code Rescue. Send the .mq4 or .mq5 file and a screenshot of your Experts and Journal tabs to algotailor.com. We reply within 24 hours, Monday to Saturday (PKT).
Trading involves substantial risk. AlgoTailor builds software to the client's specification and does not provide trading or investment advice or guarantee trading results. ChatGPT is a product of OpenAI; AlgoTailor is not affiliated with OpenAI or MetaQuotes.
Related: MT4 & MT5 development · EA works in backtest but not live
Send your rules. Rough notes are fine. We reply within 24 hours, Monday to Saturday (PKT), with questions, a numbered spec and a fixed quote.
Send your rules