// Downloaded From https://www.WiseStockTrader.com
// select the symbol from the active chart
EnableScript("jscript");
<%
AB = new ActiveXObject("Broker.Application");
AFL("symb")=AB.ActiveDocument.Name;
%>

// select the variables of the stock you want to correlate
xo=Foreign(symb,"Open");
xh=Foreign(symb,"High");
xl=Foreign(symb,"Low");
xc=Foreign(symb,"Close");
xv=Foreign(symb,"Volume");

// define help arrays in which to store the data you want to fit
xoh = xo; xoh = 100000;
xhh = xh; xhh = 100000;
xlh = xl; xlh = 100000;
xch = xc; xch = 100000;
xvh = xv; xvh = 100000;

// extract the period from the graph selected by using the markers
period = EndValue( BarIndex() ) - BeginValue( BarIndex() );

// store the piece of array selected by using the markers 
cnt = 0;
for( i = BeginValue( BarIndex() ); i < BeginValue( BarIndex() ) + period + 1; i++ ) {

	xoh[cnt] = xo[i];
	xhh[cnt] = xh[i];
	xlh[cnt] = xl[i];
	xch[cnt] = xc[i];
	xvh[cnt] = xv[i];
	cnt = cnt + 1;			
		
}

// define a storage array to store the fit
st = C; st = 100000;
scl = 0;

// test to avoid that marked period is out of range of the available data. 
if (period > 0 AND BeginValue( BarIndex() ) != 0 AND EndValue( BarIndex() ) != BarCount) {

	// correlate this selected piece of data with the last 
	// "period" data for each symbol in a given list
	for( i = BarCount - 1; i < BarCount; i++) {

		// calculate scale factor
		scl = xch[0] / C[i-period];

		hsum = 0;
		for( j = 0; j < period + 1; j++) {
			
			// the fit or correlation procedure
			hsum = hsum +
				((xoh[j] - O[i-period+j]*scl)/xoh[j])^2 +
				((xhh[j] - H[i-period+j]*scl)/xhh[j])^2 +
				((xlh[j] - L[i-period+j]*scl)/xlh[j])^2 +
				((xch[j] - C[i-period+j]*scl)/xch[j])^2;
				
				//AddColumn(C[i-period+j],"Clp");
				//AddColumn(xch[j],"Cfit");

		}
	
		st[i] = hsum/(period+1);

	}
}
Filter=1;
AddColumn(st,"Sum",format = 1.6);
AddColumn(period,"Period Fitted");
AddColumn(scl,"Scale Factor");
AddTextColumn(symb,"Symbol Fitted");
AddColumn(BarCount,"BarCount");