Module 01 · How an EA works · Lesson 03
Ticks vs bars: decide on closed bars
The current bar is still changing. Rules that read it will see conditions flicker on and off — and backtest far better than they trade.
5 minute read
Bar 0 is a moving target
In MQL5, index 0 is the bar that is still forming; index 1 is the last fully closed bar. A moving-average cross on bar 0 can appear and disappear several times before the bar closes. An EA that acts on it will enter trades whose reason has vanished a minute later.
The closed-bar pattern
Check once per new bar, and read indicator values from shifts 1 and 2. This is what the MarketPanda builder generates, and it is what the Backtest Lab simulates: the condition is judged on the closed bar, and the trade is opened on the next bar.
datetime lastBar = 0;
bool IsNewBar()
{
datetime t = iTime(_Symbol, _Period, 0); // open time of the forming bar
if(t == lastBar) return(false);
lastBar = t;
return(true);
}
double Value(int handle, int shift)
{
double v[1];
if(CopyBuffer(handle, 0, shift, 1, v) != 1) return(EMPTY_VALUE);
return(v[0]); // shift 1 = last closed bar
}
Look-ahead bias
A backtest that uses a bar's close to decide a trade at that same bar's open is reading the future. It is the most common reason a test looks brilliant and the live account does not. Always ask: at the moment of this decision, could the program actually have known this number?
Takeaways
- Shift 0 is still forming; shift 1 is the last closed bar.
- Decide once per new bar, act on the next bar.
- Any test that uses information from later than the decision is fiction.
Primary references
Your rules, our teaching. MarketPanda provides no strategy, no settings that “work” and no signals. Everything here is education; nothing is a recommendation to trade.
Content source: Bundled MarketPanda content.