MT5 Closed-Bar Signal Audit: Log EMA Crosses to CSV Without Repainting
Trading Tips · Practical MQL5 debugging utility
An indicator can draw convincing historical arrows yet remain impossible to audit in live operation. The problem is not always the moving-average formula: it is often a mismatch between an unfinished candle, a closed candle, and a file writer that records the same event more than once. This practical MT5 study shows how to separate those concerns. It plots crosses between a 9-period and a 21-period exponential moving average (EMA) on completed candles and optionally records each newly confirmed event to a common CSV file. It does not place trades.
Why the candle index matters
In MQL5 series indexing, bar 0 is still forming, bar 1 is the most recently completed candle, and bar 2 is the closed candle before it. A bullish cross is confirmed only when fast EMA[1] is greater than slow EMA[1] and fast EMA[2] was less than or equal to slow EMA[2]. The bearish condition reverses those inequalities. The moving averages are read from native indicator handles with CopyBuffer, not computed by reusing MQL4-style iMA return values.
For a reproducible schematic example, assume EMA(9) and EMA(21) at bar 2 are 1.0992 and 1.0994 respectively. At bar 1 they are 1.1001 and 1.0998. The fast EMA has crossed above the slow EMA across two completed candles, so the indicator plots an up arrow beneath bar 1. A temporary cross on bar 0 is ignored; if it disappears before close, there is no recorded event. The values are hypothetical, not market observations.

What the program actually does
The first phase creates two EMA handles in OnInit and releases them in OnDeinit. OnCalculate checks whether both handles have sufficient calculated bars, then copies their buffers. On the initial calculation it fills historical arrow buffers but deliberately does not backfill the CSV. On subsequent calls it recalculates the last two closed candles, keeps the unfinished bar empty, and records a signal only when the timestamp of bar 1 changes. The CSV stores symbol, timeframe, completed bar timestamp, direction, closing price, and both EMA values.
Parameters and trade-offs
| Input | Default | Interpretation |
|---|---|---|
| FastPeriod | 9 | Short EMA; lower values react faster and increase whipsaws |
| SlowPeriod | 21 | Long EMA; must exceed FastPeriod |
| WriteCsvAudit | true | Write live newly closed signal events to shared CSV |
| ArrowOffsetPoints | 100 | Visual offset in symbol points, not pips |
The point offset is intentionally expressed in native symbol points. For five-digit FX quotes, 100 points normally equals ten pips, but other instruments have different tick conventions. Adjust it to chart scale. A fast 9/slow 21 pair is an illustration, not a universal optimum.
Complete MQL5 custom indicator
Save the following unchanged code as PS_ClosedBarAudit.mq5 in the Indicators folder. The same source is reproduced in the Chinese edition.
// MT5 Sunday tip: closed-bar signal audit with a persistent CSV log.
// Save as MQL5/Indicators/PS_ClosedBarAudit.mq5
#property copyright "PatternSmart educational example"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 2
#property indicator_label1 "ConfirmedUp"
#property indicator_type1 DRAW_ARROW
#property indicator_color1 clrSeaGreen
#property indicator_label2 "ConfirmedDown"
#property indicator_type2 DRAW_ARROW
#property indicator_color2 clrTomato
input int FastPeriod = 9;
input int SlowPeriod = 21;
input bool WriteCsvAudit = true;
input int ArrowOffsetPoints = 100;
double UpBuffer[];
double DownBuffer[];
int fastHandle = INVALID_HANDLE;
int slowHandle = INVALID_HANDLE;
datetime lastLogged = 0;
int OnInit()
{
if(FastPeriod < 2 || SlowPeriod <= FastPeriod || ArrowOffsetPoints < 0)
return INIT_PARAMETERS_INCORRECT;
SetIndexBuffer(0, UpBuffer, INDICATOR_DATA);
SetIndexBuffer(1, DownBuffer, INDICATOR_DATA);
ArraySetAsSeries(UpBuffer, true);
ArraySetAsSeries(DownBuffer, true);
PlotIndexSetInteger(0, PLOT_ARROW, 233);
PlotIndexSetInteger(1, PLOT_ARROW, 234);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
fastHandle = iMA(_Symbol, _Period, FastPeriod, 0, MODE_EMA, PRICE_CLOSE);
slowHandle = iMA(_Symbol, _Period, SlowPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
return INIT_FAILED;
IndicatorSetString(INDICATOR_SHORTNAME, "PS Closed-Bar Audit");
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
if(fastHandle != INVALID_HANDLE) IndicatorRelease(fastHandle);
if(slowHandle != INVALID_HANDLE) IndicatorRelease(slowHandle);
}
void LogSignal(datetime barTime, string direction, double closePrice,
double fastValue, double slowValue)
{
int file = FileOpen("PS_ClosedBarAudit.csv", FILE_READ|FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_SHARE_READ, ',');
if(file == INVALID_HANDLE) { Print("CSV open failed: ", GetLastError()); return; }
if(FileSize(file) == 0)
FileWrite(file, "Symbol", "Timeframe", "ClosedBarTime", "Direction", "Close", "FastEMA", "SlowEMA");
FileSeek(file, 0, SEEK_END);
FileWrite(file, _Symbol, EnumToString(_Period), TimeToString(barTime, TIME_DATE|TIME_MINUTES),
direction, DoubleToString(closePrice, _Digits),
DoubleToString(fastValue, _Digits), DoubleToString(slowValue, _Digits));
FileClose(file);
}
int OnCalculate(const int rates_total, const int prev_calculated,
const datetime &time[], const double &open[],
const double &high[], const double &low[],
const double &close[], const long &tick_volume[],
const long &volume[], const int &spread[])
{
if(rates_total < SlowPeriod + 4) return 0;
if(BarsCalculated(fastHandle) < rates_total || BarsCalculated(slowHandle) < rates_total)
return prev_calculated;
double fast[], slow[];
ArraySetAsSeries(fast, true);
ArraySetAsSeries(slow, true);
if(CopyBuffer(fastHandle, 0, 0, rates_total, fast) != rates_total ||
CopyBuffer(slowHandle, 0, 0, rates_total, slow) != rates_total)
return prev_calculated;
ArraySetAsSeries(time, true);
ArraySetAsSeries(high, true);
ArraySetAsSeries(low, true);
ArraySetAsSeries(close, true);
int oldest = (prev_calculated == 0) ? rates_total - SlowPeriod - 2 : 2;
if(oldest > rates_total - 3) oldest = rates_total - 3;
UpBuffer[0] = EMPTY_VALUE;
DownBuffer[0] = EMPTY_VALUE;
for(int i = oldest; i >= 1; --i)
{
UpBuffer[i] = EMPTY_VALUE;
DownBuffer[i] = EMPTY_VALUE;
bool up = fast[i] > slow[i] && fast[i+1] <= slow[i+1];
bool down = fast[i] < slow[i] && fast[i+1] >= slow[i+1];
if(up) UpBuffer[i] = low[i] - ArrowOffsetPoints * _Point;
if(down) DownBuffer[i] = high[i] + ArrowOffsetPoints * _Point;
}
// Log only a newly closed bar, never an unfinished bar or historical backfill.
if(prev_calculated > 0 && time[1] != lastLogged)
{
lastLogged = time[1];
if(WriteCsvAudit && (UpBuffer[1] != EMPTY_VALUE || DownBuffer[1] != EMPTY_VALUE))
LogSignal(time[1], UpBuffer[1] != EMPTY_VALUE ? "UP" : "DOWN",
close[1], fast[1], slow[1]);
}
if(prev_calculated == 0) lastLogged = time[1];
return rates_total;
}
Installation and validation
- Open MetaEditor from MetaTrader 5, create a custom indicator, replace the template with this complete source, and compile.
- Attach the indicator to a chart with sufficient bars. Confirm arrows appear only on completed candles.
- Enable CSV logging and wait for a newly closed candle with an EMA cross. Inspect the common files folder (
Terminal → Common → Files) forPS_ClosedBarAudit.csv. - Compare the CSV timestamp with the chart's completed candle and the two EMA values; no row should be written merely because bar 0 temporarily crosses.
- Reload the indicator and observe that historical arrows can be reconstructed without duplicating old CSV entries.
Failure modes worth testing
History loading: OnCalculate may be called again after missing history is downloaded; an initial recalculation intentionally does not export old signals. File access: CSV writes can fail due to permissions or an occupied file, so check the Experts log. Multiple instances: Several charts share the same common filename, which can interleave writes; use per-symbol/timeframe filenames or a centralized writer in production. Missed sessions: The logger is not a guaranteed historical event journal; if MT5 is offline, it will not reconstruct every missed event. Intrabar behavior: plotting from closed bars avoids bar-zero signal flicker but does not eliminate losses, slippage, or ranging-market whipsaws.
The study is a diagnostic utility, not a tested trading strategy. EMA crossovers lag price and may fail repeatedly in sideways markets. Review the source and compile it on your own MT5 build before relying on it. Interested in extending this free indicator into a robust multi-symbol logger or alerting system? Explore our Custom Trading Software Development Services for tailored development.