Correlation Coefficient

#region Namespaces
using System;
#endregion

namespace ScriptCode {
	/// <summary>
	/// Indicator scripts are used for calculating a series of numerical values.
	/// 
	/// This script can be used in several ways:
	/// (1) It can be used on a chart.
	/// (2) It can be used from another script.
	/// (3) It can be used as a script column in a watchlist.
	/// </summary>
	public partial class MyIndicator : IndicatorScriptBase // NEVER CHANGE THE CLASS NAME
	{
#region Variables
		// The indicator of the first underlying indicator.
		private Indicator _indicator1;
		// The indicator of the second underlying indicator.
		private Indicator _indicator2;
		// The number of periods to include in the indicator script calculation.
		private int _periods;
#endregion

#region OnInitialize
		/// <summary>
		/// This function accepts the user parameters for the script and is called when a new indicator instance is created. 
		/// One of the parameters accepted by it must be that of a symbol or another script that is
		/// based on a symbol (drawing, indicator, pattern or signal). This symbol will be used as the underlying symbol for the indicator.
		/// 
		/// The parameter values can be specified from the user interface (UI) or from another script, depending on usage.
		/// </summary>
		/// --------------------------------------------------------------------------------------------------
		/// PLEASE USE THE SCRIPT WIZARD (CTRL+W) TO ADD, EDIT AND REMOVE THE SCRIPT PARAMETERS
		/// --------------------------------------------------------------------------------------------------
		/// YOU MUST SET A PARAM TAG FOR EACH PARAMETER ACCEPTED BY THIS FUNCTION.
		/// ALL PARAM TAGS SHOULD BE SET IN THE 'OnInitialize' REGION, RIGHT ABOVE THE 'OnInitialize' FUNCTION.
		/// THE ORDER OF THE TAGS MUST MATCH THE ORDER OF THE ACTUAL PARAMETERS.

		/// REQUIRED ATTRIBUTES:
		/// (1) name: The exact parameter name.
		/// (2) type: The type of data to collect from the user: 
		/// Set to "Integer" when the data type is 'int'
		/// Set to "IntegerArray" when the data type is 'int[]'
		/// Set to "DateTime" when the data type is 'long'  
		/// Set to "DateTimeArray" when the data type is 'long[]'  
		/// Set to "Boolean" when the data type is 'bool'
		/// Set to "BooleanArray" when the data type is 'bool[]'
		/// Set to "Double" when the data type is 'double'
		/// Set to "DoubleArray" when the data type is 'double[]'
		/// Set to "String" when the data type is 'string'
		/// Set to "StringArray" when the data type is 'string[]'
		/// Set to "Indicator" when the data type is 'Indicator'
		/// Set to "Pattern" when the data type is 'Pattern'
		/// Set to "Signal" when the data type is 'Signal'
		/// Set to "Drawing" when the data type is 'Drawing'
		/// Set to "Symbol" when the data type is 'int' representing a symbol index.

		/// OPTIONAL ATTRIBUTES:
		/// (3) default: The default parameter value is only valid when the type is Integer, Boolean, Double or String. 
		/// (4) min: The minimum parameter value is only valid when the type is Integer or Double.
		/// (5) max: The maximum parameter value is only valid when the type is Integer or Double.

		/// EXAMPLE: <param name="" type="" default="" min="" max="">Enter the parameter description here.</param> 
		/// --------------------------------------------------------------------------------------------------
		/// <param name="indicator1" type="Indicator">The underlying indicator of the first indicator.</param>
		/// <param name="indicator2" type="Indicator">The underlying indicator of the second indicator.</param>
		/// <param name="periods" type="Integer" default="10" min="1">The number of periods to include in the Correlation Coefficient calculation. </param>
		public void OnInitialize(Indicator indicator1, Indicator indicator2, int periods) {
			// Set the first indicator.
			_indicator1 = indicator1;
			// Set the second indicator.
			_indicator2 = indicator2;
			// Set the number of periods.
			_periods = periods;
		}
#endregion

#region OnBarUpdate
		/// <summary>
		/// This function is used for calculating the indicator value for the latest bar (see the Indicator functions).
		/// </summary>
		/// <returns>The indicator value for the latest bar.</returns>
		public override double OnBarUpdate() {
			// Check whether the number of indicator values is lower than the number of values needed.
			if (IndicatorValueCount() < _periods)
				return 0;

			// The indicators covariance, means and standard deviations. 
			double COV = 0;
			double mean1 = 0;
			double mean2 = 0;
			double SD1 = 0;
			double SD2 = 0;
			// Calculate the indicator's means.
			for (int i = _periods - 1; i >= 0; i--) {
				mean1 += _indicator1[i];
				mean2 += _indicator2[i];
			}
			// Set the mean for indicator 1.
			mean1 = mean1 / _periods;
			// Set the mean for indicator 2,
			mean2 = mean2 / _periods;
			// Iterate over the periods while calculating the STDev.
			for (int i = _periods - 1; i >= 0; i--) {
				COV += ((_indicator1[i] - mean1) * (_indicator2[i] - mean2)) / _periods;
				SD1 += Math.Pow(_indicator1[i] - mean1, 2);
				SD2 += Math.Pow(_indicator2[i] - mean2, 2);
			}
			// Set the STDEV for indicator 1.
			SD1 = Math.Sqrt(SD1 / _periods);
			// Set the STDEV for indicator 2.
			SD2 = Math.Sqrt(SD2 / _periods);
			return COV / (SD1 * SD2);
		}
#endregion

#region OnChartSetup
		/// <summary>
		/// This function is used for setting up the indicator on the chart and registering its pens (see the IndicatorChartRegisterPenRGB function).
		/// </summary>
		public override void OnChartSetup() {
			// Register a pen.
			IndicatorChartRegisterPenRGB(0, "Pen", new int[] { 22 ,81, 238, 255 }, C_DashStyle.SOLID, 2);
			// Set the indicator in a new chart panel.
			IndicatorChartSetNewPanel(true);
			// Set the indicator plot style.
			IndicatorChartSetPlotStyle(C_PlotStyle.CROSS);
			// Set the indicator range.
			IndicatorChartSetRange(-1, 1);
			// Set the negative range.
			IndicatorChartSetColorZone(-1, 0, new int[] { 255, 75, 75, 50 }, new int[] { 255, 75, 75, 255 }, C_DashStyle.SOLID, 2);
			// Set the positive range.
			IndicatorChartSetColorZone(0, 1, new int[] { 0, 160, 120, 50 }, new int[] { 0, 160, 120, 255 }, C_DashStyle.SOLID, 2);
		}
#endregion

#region OnSelectPen
		/// <summary>
		/// This function is used for selecting a registered indicator pen with which to color the latest indicator value.
		/// Call the IndicatorChartRegisterPenRGB function from the OnChartSetup function in order to register an indicator pen.
		/// </summary>
		/// <returns>The indicator pen index to use for coloring the latest indicator value.</returns>
		public override byte OnSelectPen() {
			// Color the indicator value with the zero pen.
			return 0;
		}
#endregion
	}
}