MT5 Arbitrage EA Guide: Pairs Signals and Execution Limits
Audit the gap between a statistical pairs signal and an executable MT5 arbitrage EA. The included signal-only Expert Advisor aligns completed H1 bars and calculates a log-price-ratio z-score. It does not place trades, implement latency arbitrage, or establish that the spread will converge.
Implementation details & mechanics
Core implementation pattern
For distinct symbols, copy one evaluated H1 close and an older lookback window with matching timestamps. Calculate log(price1) minus log(price2), then its historical sample mean and standard deviation. A z-score beyond the chosen threshold logs a candidate direction. The coefficient of one is an illustrative assumption, not an estimated hedge ratio or validated trading model.
Error handling & safety rules
A z-score near the mean prints a research observation only. There are no positions, orders, stop losses, time exits or cash-profit estimates in this example. Before adding execution, define quote freshness, currency and contract exposure, both-leg failure handling, costs, state recovery and broker-specific order constraints. A statistical spread is not a locked-in arbitrage profit.
MQL5 Code Implementation
#property strict
// Signal-only Expert Advisor: no orders, positions or profit calculation.
input string Symbol2="EURUSD";
input int SpreadLookback=100;
input double EntryZScore=2.0;
input double ExitZScore=0.5;
datetime lastBar=0;
int OnInit()
{
if(Symbol2==_Symbol || SpreadLookback<2 || SpreadLookback>10000
|| EntryZScore<=0 || ExitZScore<0 || ExitZScore>=EntryZScore)
return INIT_PARAMETERS_INCORRECT;
if(!SymbolSelect(Symbol2,true)) return INIT_FAILED;
return INIT_SUCCEEDED;
}
void OnTick()
{
datetime current=iTime(_Symbol,PERIOD_H1,0);
if(current<=0 || current==lastBar) return;
MqlRates a[],b[];
ArraySetAsSeries(a,true); ArraySetAsSeries(b,true);
int count=SpreadLookback+1;
// shift=1 excludes the forming bar. Index zero is the newest completed bar.
if(CopyRates(_Symbol,PERIOD_H1,1,count,a)!=count
|| CopyRates(Symbol2,PERIOD_H1,1,count,b)!=count) return;
if(iTime(Symbol2,PERIOD_H1,0)!=current) return;
double spreads[]; ArrayResize(spreads,count);
for(int i=0;i<count;i++)
{
// Reject mismatched timestamps; do not pair unrelated bars by index.
if(a[i].time!=b[i].time || a[i].close<=0 || b[i].close<=0) return;
spreads[i]=MathLog(a[i].close)-MathLog(b[i].close);
}
double mean=0;
for(int i=1;i<count;i++) mean+=spreads[i];
mean/=SpreadLookback; // Historical window excludes the evaluated observation.
double sum=0;
for(int i=1;i<count;i++) sum+=MathPow(spreads[i]-mean,2);
double sd=MathSqrt(sum/(SpreadLookback-1));
if(sd<=1e-10) { lastBar=current; Print("No usable spread variation"); return; }
double z=(spreads[0]-mean)/sd;
lastBar=current;
string signal="inside thresholds";
if(z>EntryZScore) signal="candidate: short first / long second";
else if(z<-EntryZScore) signal="candidate: long first / short second";
else if(MathAbs(z)<ExitZScore) signal="near historical mean (not a position exit)";
Print(TimeToString(a[0].time)," ",_Symbol," / ",Symbol2,
" z=",DoubleToString(z,4)," ",signal);
}Copy this code into MetaEditor, save it in your MQL5 folder (Experts, Scripts, or Include), and compile with F7.
Generate custom MQL5 code with Pineify AI
Describe the trade execution, indicator calculations, risk management, or data processing logic you need. Pineify generates editable MQL5 source code. Review its logic, request a syntax check, and compile and test the final file in MetaEditor.
Pine Script vs MQL5: Same Strategy, Different Platforms
| Aspect | Pine Script (TradingView) | MQL5 (MetaTrader 5) |
|---|---|---|
| Execution | Series evaluated on chart updates | Event handlers with explicit buffers |
| Deployment | Runs in TradingView with alerts | Runs in the MT5 terminal or on a VPS |
| Broker access | Strategy orders are simulated; live automation needs a separate integration | Direct broker connectivity |
| Backtesting | Strategy Tester for strategy scripts | Strategy Tester for Expert Advisors |
| Code complexity | Simpler, functional syntax | C++-like, more powerful |
The calculation can be implemented on either platform, but the runtime model and buffer APIs differ.
Frequently Asked Questions
Related MQL5 pages
Risk and testing note
These educational examples require independent compilation and testing. A compile pass or an illustrative setting does not establish execution correctness or profitability. Any reported performance must be supported by reproducible data and test settings; past results do not predict future returns. Trading involves significant risk of loss. This content is not financial advice.