This is the main callback function where all calculations for the custom study are performed and its results are updated.
calculate(beginIndex, endIndex);
beginIndex
Numeric value that indicates the beginning position of the data range for which the study needs to calculate new values.
endIndex
Numeric value that indicates the ending position of the data range for which the study needs to calculate new values.
When ActiveTick needs to update study's contents, it calls this callback function with the range for which it needs the new calculations. This usually happens in the following scenarios:
calculate() callback function should process only what is being asked of it by beginIndex and endIndex, and all appropriate StudyData should be inserted or updated.
The following example demonstrates calculate() callback function.
function init()
{
//setup study's initial settings
this.setName("cSMA");
this.addDataPlot("customSMA");
this.addParameter("Period", 10);
//set to true so that this study can use *any* data source
setAnyDataSource(true);
//moving average requires a minimum of periods to calculate one value
setMinRequiredDataValues(this.getParameter("Period"));
}
function calculate(beginIndex, endIndex)
{
//retrieve current period value
var period = parseInt(this.getParameter("Period"));
//retrieve enough data from the source to satisfy ActiveTick's request to calculate values for begin-end range
var sourceDataArray = this.getSourceData(beginIndex, endIndex);
//retrieve previously calculated data
var studyData = this.getStudyData("customSMA");
//calculate moving average array
var maArray = customSMA(sourceDataArray, period);
//populate studyData with our results
var dataIndex = maArray.length - 1;
for(var i = endIndex - 1; i >= beginIndex; i--)
{
if(dataIndex >= 0)
studyData.set(i, maArray[dataIndex--]);
else
{
//set null value for current i so that ActiveTick doesn't draw any at current i
studyData.set(i, null);
}
}
function customSMA(data, period)
{
//calculate moving average given an array of data points and Period value
var ma = new Array();
var maCount = 0;
for(var i = 0; i <= data.length - period; i++)
{
var totalPrices = 0;
var pricesCount = 0;
for(j = i; j < i + period; j++)
{
totalPrices += data[j];
pricesCount++;
}
ma[maCount] = (totalPrices / pricesCount);
maCount++;
}
return ma;
}
Copyright © 2006-2009 ActiveTick LLC