Code Library / Risk Management
MQL5 Correlation Filter
Prevent overexposure by checking position correlation.
Language: MQL5 · Category: Risk Management · Tags: correlation, risk, MQL5, portfolio, diversification
Source code
double Correlation(string s1,string s2,int p) {
double c1[],c2[]; CopyClose(s1,PERIOD_H1,0,p,c1); CopyClose(s2,PERIOD_H1,0,p,c2);
double sx=0,sy=0,sxy=0,sx2=0,sy2=0; int n=MathMin(ArraySize(c1),ArraySize(c2));
for(int i=0;i<n;i++){sx+=c1[i];sy+=c2[i];sxy+=c1[i]*c2[i];sx2+=c1[i]*c1[i];sy2+=c2[i]*c2[i];}
double d=MathSqrt((n*sx2-sx*sx)*(n*sy2-sy*sy));
return d==0?0:(n*sxy-sx*sy)/d;
}How to use this snippet
This is a building block, not a finished trading system. Paste it into your own MQL5 project, compile it, and test it on a demo account with your broker's real spreads before relying on it. If MetaEditor reports errors, the compilation error fixer can help.