Correlation_njel

Download script
Author: Copyright � 2007, njel [andrew opeyda]
Correlation_njel

This script is designed to provide a visual representation of the statistical relationship between two different financial assets—specifically comparing the current currency pair you are trading against a primary base pair (which defaults to EURUSD).

Core Functionality

The primary goal of this tool is to measure Correlation. In trading, correlation tells you how closely two assets move in relation to one another. If they move in perfect harmony, they have a high positive correlation; if they move in opposite directions, they have a negative correlation. This script automates the complex math required to identify these patterns over different time horizons.

How the Logic Works

The script performs several automated steps to generate its visual data:

  • Multi-Period Analysis: Instead of looking at just one timeframe, the script calculates correlations across ten different "look-back" periods (ranging from 10 bars to 250 bars). This allows you to see how the relationship between the assets changes over both short-term fluctuations and long-term trends.
  • Moving Average Baseline: To determine if the assets are moving together, the script first establishes a "baseline" for both the current symbol and the base pair using Simple Moving Averages (SMA). It focuses on how the price deviates from these averages.
  • Statistical Calculation: For every point in the chart's history, the script performs a mathematical calculation to find the correlation coefficient. It takes the variance of both assets and determines the strength of their joint movement.
  • Visual Mapping (Heatmap Style): The logic converts these complex numerical values into visual markers on your screen:
    • It creates specific objects (arrows/markers) for each period analyzed.
    • It uses a color-coding system to represent the strength and direction of the correlation. By varying the red, green, and blue channels based on the calculation results, it provides a "heatmap" effect.
    • The closer the values are to one another across the different periods, the more distinct the visual cluster will appear, helping you identify when the two assets are synchronized.

Summary for the User

Essentially, this tool acts as a Correlation Mapper. It scans the history of your current chart against a base pair and paints a visual picture of how "linked" those two markets are. By looking at the density and color of the markings, you can quickly gauge whether the asset you are currently trading is following the lead of the base currency or moving independently.

Price Data Components
Series array that contains close prices for each bar
Indicators Used
Moving average indicator
Miscellaneous
Implements a curve of type %1
14 Views
0 Downloads
0 Favorites
Correlation_njel
#property copyright "Copyright © 2007, njel [andrew opeyda]"
#property link      "www.signalslab.com [andrew.opeyda@gmail.com] %)"

#property indicator_separate_window


#property indicator_buffers 3
#property indicator_color1 Red
#property indicator_width1 1
#property indicator_color2 SkyBlue
#property indicator_width2 2
#property indicator_color3 Green
#property indicator_width3 1


#property indicator_levelwidth 1
#property indicator_levelstyle STYLE_DOT

#property indicator_maximum 1
#property indicator_minimum 0


double buff1[];
double buff2[];
double buff3[];


extern int BarsForShortTF=7; //êîëè÷åñòâî áàðîâ äëÿ ðàñ÷åòà êîððåëÿöèè íà êîðîòêîì ïåðèîäå
int SortMode=2;       // ðåæèì ñîðòèðîâêè 1- ïî âîçðàñòàíèþ, 2 - ïî óáûâàíèþ

extern int HistoryBars=200;
extern string Base="EURUSD";
string iname ="";
int win_idx;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
  
  
//---- indicators
IndicatorBuffers(8); 
	
   SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(0,buff1);
   SetIndexEmptyValue(0,0); 
   SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(1,buff2);
   SetIndexEmptyValue(1,EMPTY_VALUE); 
   SetIndexLabel(1,"Êîððåëÿöèÿ çà "+BarsForShortTF+" áàðîâ");

   SetIndexStyle(2,DRAW_HISTOGRAM);
   SetIndexBuffer(2,buff3);
   SetIndexEmptyValue(2,0); 
   iname = "Correlation "+Base;
   IndicatorShortName(iname);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   Comment("");
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   
   win_idx=WindowFind(iname);
   //Alert(win_idx+" name "+iname);
   ObjectsDeleteAll(win_idx);
   
   
   int i;
   int periods[10];
   periods[0] = 10;
   periods[1] = 15;
   periods[2] = 25;
   periods[3] = 50;
   periods[4] = 75;
   periods[5] = 100;
   periods[6] = 125;
   periods[7] = 150;
   periods[8] = 200;
   periods[9] = 250;

   
   double x = 1.0;
   for (int p = 0; p<10; p++)
   {
      for(i=HistoryBars;i>=0;i--)
      {
       double RS=Rcalc(Symbol(),periods[p],i);
       //buff2[i]=RS;
       double a = (RS+1)/2;
       AddObj(i,x,fromRGB(255-(a*255),a*255,0));
       //AddObj(i,x,fromRGB(a*255,a*255,a*255));
      }
      
      x = x-0.1;
   }


//----
   return(0);
  }
//+------------------------------------------------------------------+

double Rcalc(string symb,int Bars_,int shift)
{
         int currday=iBarShift(NULL,Period(),iTime(NULL,Period(),shift));
      double avgBase=iMA(Base,Period(),Bars_,0,MODE_SMA,PRICE_CLOSE,currday);
      double avgSmb=iMA(symb,Period(),Bars_,0,MODE_SMA,PRICE_CLOSE,currday);
      
      double E=0;
      double D=0;
      double F=0;
      
      for(int i=currday;i<=currday+Bars_;i++)
      {
       E+=((iClose(Base,Period(),i))-avgBase)*((iClose(symb,Period(),i))-avgSmb);
       D+=MathPow(((iClose(Base,Period(),i))-avgBase),2);
       F+=MathPow(((iClose(symb,Period(),i))-avgSmb),2);
      }
      D=MathSqrt(D);
      F=MathSqrt(F);
      double G=D*F;
      double R=E/G;
return(R);
}
//--------------------------------------------------------------------+
void AddObj(int t, double price, color c)
{

   //debug
   if (c==Black) return;
   string name = ObjectsTotal()+"level";
   //ObjectCreate(name,OBJ_TREND,1,Time[t],price,Time[t],price);
   ObjectCreate(name,OBJ_ARROW,win_idx,Time[t],price,Time[t],price);
   ObjectSet(name,OBJPROP_ARROWCODE,110);
   ObjectSet(name,OBJPROP_COLOR,c);
   ObjectSet(name,OBJPROP_WIDTH,0);
   ObjectSet(name,OBJPROP_RAY,false);
}
//+------------------------------------------------------------------+
color fromRGB(int R, int G, int B)
{
   return (R+(G<<8)+(B<<16));
}
//+------------------------------------------------------------------+




Comments