Converted EA opens no trades in the Strategy Tester: checklist
Short answer
Total Trades 0 with no error means the orders were rejected or never sent; MetaTrader only writes a line to the tester's Journal. Check, in order, that trading is allowed, that the ported entry condition can be true, that the volume and stop are legal for the symbol, and how the account mode treats the order.
The Expert Advisor compiles, the Strategy Tester runs to the end, and the report says Total Trades 0. There is no error dialog, because MetaTrader 5 does not stop an EA whose orders are rejected or never sent; it writes a line to the tester's Journal and carries on. The cause is one of a short list: trading is not allowed, the entry condition is never true the way it was ported, the volume or the stop is illegal for the symbol, or the account mode treats the order differently from TradingView. This page is that list, in the order worth checking, with the line of code that settles each one.
Why it happens when converting Pine Script
A Pine strategy runs inside TradingView's broker emulator. strategy.entry cannot be rejected: there is no minimum lot, no stop level, no filling mode, no margin call unless you configure one, and the emulator evaluates the script once per closed bar and fills at the next bar's open. When an order is impossible, the emulator still fills it.
An MQL5 EA talks to a real (or simulated) trade server. OnTick runs on every tick, not every bar. Each request is checked against the symbol's volume limits and step, the minimum stop distance, the filling modes the broker allows, free margin, and whether trading is enabled at all. A request that fails any check returns a retcode and does nothing else. A ported strategy that assumed TradingView's rules produces no trades and, if it ignores the return value, no explanation.
Fix
Here is a port of a 9/21 EMA crossover that runs in the tester and opens nothing. Every line is plausible, and four of them are why:
// Port of: if ta.crossover(fast, slow) -> strategy.entry("L", strategy.long, qty = 0.001)
#include <Trade\Trade.mqh>
CTrade trade;
int fastH, slowH;
int OnInit()
{
fastH = iMA(_Symbol, _Period, 9, 0, MODE_EMA, PRICE_CLOSE);
slowH = iMA(_Symbol, _Period, 21, 0, MODE_EMA, PRICE_CLOSE);
return INIT_SUCCEEDED;
}
void OnTick()
{
double f[2], s[2];
CopyBuffer(fastH, 0, 0, 2, f); // index 0 = oldest of the two = previous bar
CopyBuffer(slowH, 0, 0, 2, s); // index 1 = the bar still forming
if(f[0] < s[0] && f[1] > s[1])
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
trade.Buy(0.001, _Symbol, ask, ask - 5 * _Point, ask + 5 * _Point);
}
}- It reads the forming bar (shift 0) on every tick. The crossover is evaluated dozens of times inside one bar, and on the first tick of a new bar the forming bar's EMA is almost equal to the previous one, so the "cross" Pine saw on a closed bar is rarely seen here.
- Volume
0.001is belowSYMBOL_VOLUME_MINon most forex symbols (usually 0.01). The server answers with retcode 10014,TRADE_RETCODE_INVALID_VOLUME. - A stop five points away is inside
SYMBOL_TRADE_STOPS_LEVELon many symbols. The answer is 10016,TRADE_RETCODE_INVALID_STOPS. - The return value of
trade.Buyis ignored, so nothing in the EA says which of these happened.
The same strategy written to survive those checks. It compiles in MetaEditor 5 (build 6140) without warnings:
// Port of: if ta.crossover(fast, slow) -> strategy.entry("L", strategy.long)
// if ta.crossunder(fast, slow) -> strategy.close("L")
#include <Trade\Trade.mqh>
input double Lots = 0.10; // requested volume, normalised to the symbol below
input int StopPoints = 300; // 0 = no stop loss
input ulong Magic = 240611;
CTrade trade;
int fastH = INVALID_HANDLE, slowH = INVALID_HANDLE;
int OnInit()
{
fastH = iMA(_Symbol, _Period, 9, 0, MODE_EMA, PRICE_CLOSE);
slowH = iMA(_Symbol, _Period, 21, 0, MODE_EMA, PRICE_CLOSE);
if(fastH == INVALID_HANDLE || slowH == INVALID_HANDLE)
return INIT_FAILED;
trade.SetExpertMagicNumber(Magic);
trade.SetTypeFillingBySymbol(_Symbol); // FOK / IOC / RETURN as the symbol allows
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
IndicatorRelease(fastH);
IndicatorRelease(slowH);
}
// Round the volume to the symbol's step and limits; 0 means "cannot trade this size".
double NormalizeLots(double lots)
{
double vmin = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double vmax = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double vstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
if(vstep <= 0.0)
return 0.0;
lots = MathFloor(lots / vstep + 1e-9) * vstep;
if(lots < vmin)
return 0.0;
return MathMin(lots, vmax);
}
// Is there a position of ours on this symbol? (works on netting and hedging accounts)
bool HasLong()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong t = PositionGetTicket(i);
if(t == 0) continue;
if(PositionGetString(POSITION_SYMBOL) == _Symbol &&
(ulong)PositionGetInteger(POSITION_MAGIC) == Magic &&
PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
return true;
}
return false;
}
void OnTick()
{
// 1. Pine decides once per closed bar: act on the first tick of a new bar only.
static datetime lastBar = 0;
datetime thisBar = iTime(_Symbol, _Period, 0);
if(thisBar == lastBar)
return;
lastBar = thisBar;
// 2. Read the two CLOSED bars (shift 1 and 2), newest first.
double f[], s[];
ArraySetAsSeries(f, true);
ArraySetAsSeries(s, true);
if(CopyBuffer(fastH, 0, 1, 2, f) != 2 || CopyBuffer(slowH, 0, 1, 2, s) != 2)
{
lastBar = 0; // data not ready: try again on the next tick
return;
}
bool crossUp = f[1] <= s[1] && f[0] > s[0]; // ta.crossover(fast, slow)
bool crossDown = f[1] >= s[1] && f[0] < s[0]; // ta.crossunder(fast, slow)
// 3. Trading allowed at all? (AutoTrading button, EA settings)
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) || !MQLInfoInteger(MQL_TRADE_ALLOWED))
{
Print("Trading is disabled in the terminal or for this EA");
return;
}
if(crossDown && HasLong())
{
if(!trade.PositionClose(_Symbol))
PrintFormat("close failed: %u %s", trade.ResultRetcode(), trade.ResultRetcodeDescription());
}
if(crossUp && !HasLong())
{
double vol = NormalizeLots(Lots);
if(vol <= 0.0)
{
PrintFormat("volume %.3f is below SYMBOL_VOLUME_MIN", Lots);
return;
}
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double sl = 0.0;
if(StopPoints > 0)
{
// The stop must be at least SYMBOL_TRADE_STOPS_LEVEL points away.
long minPts = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
int pts = (int)MathMax(StopPoints, minPts + 1);
sl = NormalizeDouble(ask - pts * _Point, _Digits);
}
if(!trade.Buy(vol, _Symbol, 0.0, sl, 0.0, "L"))
PrintFormat("buy failed: %u %s", trade.ResultRetcode(), trade.ResultRetcodeDescription());
else if(trade.ResultRetcode() != TRADE_RETCODE_DONE && trade.ResultRetcode() != TRADE_RETCODE_PLACED)
PrintFormat("buy not filled: %u %s", trade.ResultRetcode(), trade.ResultRetcodeDescription());
}
}The checklist
- Is trading allowed? On a chart, the AutoTrading button in the toolbar must be on and "Allow Algo Trading" ticked in the EA's Common tab; otherwise
TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)orMQLInfoInteger(MQL_TRADE_ALLOWED)is false and requests fail with 10027,TRADE_RETCODE_CLIENT_DISABLES_AT. The Strategy Tester allows trading regardless of the toolbar button, so if the EA trades on a chart but not in the tester, this is not the cause. - Does the signal ever fire? Print the condition once per bar before touching any order code. If it is never true, the problem is the port (forming bar vs closed bar, array direction after
CopyBuffer, a crossover written as</>instead of Pine's<=on the previous bar), not trading. - Is there new-bar detection? Pine decides on a closed bar. Gate
OnTickon a change ofiTime(_Symbol, _Period, 0)and read shift 1 and 2. Without the gate an EA can also open a position on one tick and close it on the next. - Is the volume legal? Round to
SYMBOL_VOLUME_STEPand check againstSYMBOL_VOLUME_MINandSYMBOL_VOLUME_MAX. A Pineqty = 1is one unit (one share, one coin, one contract); one lot of EURUSD is 100,000 units. Percent-of-equity sizing is covered in this guide. - Are the stops far enough? Stop loss and take profit must be at least
SYMBOL_TRADE_STOPS_LEVELpoints from the price, normalised to_Digits. A stop computed from an indicator can fall inside the level on quiet bars and reject only some trades. - Is the filling mode accepted? Some symbols allow only IOC or only Return.
CTradepicks a mode the symbol supports for market orders; a hand-builtMqlTradeRequestwith the wrongtype_fillingfails with 10030,TRADE_RETCODE_INVALID_FILL. - Netting or hedging? On a netting account a buy while short reduces the short instead of opening a long, and a second buy adds to the first. On a hedging account the same calls open separate positions. An EA that checks
PositionSelect(_Symbol)to decide "am I flat?" behaves differently on the two; loop over positions and filter by symbol and magic number as above.AccountInfoInteger(ACCOUNT_MARGIN_MODE)tells you which one the tester account is. - Is there money and is the market open? 10019 (
TRADE_RETCODE_NO_MONEY) on a small tester deposit with large lots, and 10018 (TRADE_RETCODE_MARKET_CLOSED) at session boundaries, are both reported in the Journal. - Check the retcode.
CTrade::Buyreturns false when the request did not reach the server or was rejected;trade.ResultRetcode()andtrade.ResultRetcodeDescription()say why. Atruereturn with a retcode other thanTRADE_RETCODE_DONE(10009) orTRADE_RETCODE_PLACED(10008) is also worth logging.
Other causes of the same message
- Not enough history in the tester. An EA that needs a 200-bar EMA and a date range that starts at the first available bar spends the first 200 bars with
CopyBufferreturning less than requested. If the code returns on that without resetting the bar gate, it can skip signals; the example setslastBar = 0to retry. - The wrong symbol or timeframe in the tester settings. The EA trades
_Symbolon_Period, which are what the tester dialog says, not what the Pine chart was. - A
return(INIT_FAILED)inOnInit. The tester stops immediately with a line in the Journal; the report shows zero trades. An invalid indicator handle is the usual reason. - Converted code. An EA generated by the Stratlate converter already has the bar gate:
OnTickreturns untiliTime(NULL, 0, 0)changes, then evaluates the strategy on the bar that just closed (shift 1), which is TradingView's decide-on-close, fill-at-next-open model. Orders go through the standard library'sCTradevia the runtime'sOrderSendwrapper, which letsCTradechoose a filling mode the symbol accepts and keeps one position per symbol on both netting and hedging accounts. Cash and percent-of-equity quantities are rounded toSYMBOL_VOLUME_STEPand skipped when belowSYMBOL_VOLUME_MIN, as TradingView skips an order it cannot size. A fixeddefault_qty_valueis passed through as lots unchanged, so a Pine quantity of 1 becomes 1.0 lot, and a value below the symbol's minimum is rejected by the server; set the quantity for the MT5 symbol before testing. The wrapper returns -1 on a rejected request without its own log line, andCTradeat its default log level writes the failure and retcode to the Journal, which is where to look. As with any conversion, compile it and backtest it before trading.
Pitfalls
- Testing on "Every tick" with an EA that reads shift 0. The results then depend on the tick model. With a new-bar gate and closed-bar reads, "Open prices only" and "Every tick" give the same signals and the fast mode is a valid first check.
- Comparing trade counts with TradingView without matching costs. A spread or commission in the tester can turn a TradingView winner into a loser, but it does not stop trades from opening. Zero trades is never a cost problem.
- Silencing rejections with a bigger deposit. If the fix for 10019 is a 10x deposit, the lot size is wrong, and the equity curve will not mean what you think.
- Ignoring
CopyBuffer's return value. On a failed copy the arrays hold the previous values or nothing, and the crossover test compares stale numbers. Check that it returned the count you asked for. - Reading
CopyBufferoutput in the wrong direction. WithoutArraySetAsSeries(arr, true), element 0 is the oldest copied bar. A crossover test written for newest-first data then tests a cross in the opposite direction.
FAQ
Where does the Strategy Tester show why an order was rejected?
In the Journal tab of the Strategy Tester panel, not the terminal's own Journal. CTrade at its default log level writes each failed request with its retcode there, and your own Print output appears in the same tab. Open the tester's Journal before changing any code.
Why does my EA trade on a live chart but not in the Strategy Tester?
Usually history: the tester starts with only the bars inside the date range plus a short preload, so an indicator with a long lookback returns too few values and the entry logic exits early. Start the test later or handle a short CopyBuffer return by retrying on the next tick.
Does a converted EA behave the same on netting and hedging accounts?
For a strategy with pyramiding 0, the Stratlate runtime keeps one position per symbol and closes the opposite side before reversing, so the two modes give the same trades. Pyramiding and several simultaneous entries on one symbol are not modelled and are reported by the converter rather than guessed at.
Let the converter do the mechanical part
Paste the original script and get a conversion that compiles, with every construct that could not be carried over reported instead of hidden. Review, compile and backtest the result before trading.
Open the converter