Indicator with inputs of different periods
Overview
The following example demonstrates the use of multiple periods in a single indicator. It's a simple indicator that draws lines over the close prices of three different periods: one minute, five minutes and ten minutes. Note that the indicator will not work with periods greater than 1 minute (greater than the smallest period of indicator inputs).
Method onStart
public void onStart(IIndicatorContext context) {
indicatorInfo = new IndicatorInfo("MULTIPLEPERIODS", "Multiple period indicator", "",
false, false, false, 4, 0, 3);
//indicator looks way better with setSparceIndicator property set to true
indicatorInfo.setSparceIndicator(true);
inputParameterInfos = new InputParameterInfo[] {
//main input from chart
new InputParameterInfo("Main", InputParameterInfo.Type.BAR),
//additional inputs
new InputParameterInfo("FirstPeriod", InputParameterInfo.Type.BAR){{
setPeriod(Period.ONE_MIN);}},
new InputParameterInfo("SecondPeriod", InputParameterInfo.Type.BAR){{
setPeriod(Period.FIVE_MINS);}},
new InputParameterInfo("ThirdPeriod", InputParameterInfo.Type.BAR){{
setPeriod(Period.TEN_MINS);}}};
outputParameterInfos = new OutputParameterInfo[] {
new OutputParameterInfo("First",
OutputParameterInfo.Type.DOUBLE,
OutputParameterInfo.DrawingStyle.LINE),
new OutputParameterInfo("Second",
OutputParameterInfo.Type.DOUBLE,
OutputParameterInfo.DrawingStyle.LINE),
new OutputParameterInfo("Third",
OutputParameterInfo.Type.DOUBLE,
OutputParameterInfo.DrawingStyle.LINE)};
}
Method calculate
public IndicatorResult calculate(int startIndex, int endIndex) {
//default values for indicator outputs
Arrays.fill(outputs[0], Double.NaN);
Arrays.fill(outputs[1], Double.NaN);
Arrays.fill(outputs[2], Double.NaN);
int i;
for (i = 1; i < inputs.length; i++){
calculateOutput(i, endIndex - startIndex + 1);
}
return new IndicatorResult(startIndex, outputs[0].length);
}
Method calculateOutput
private void calculateOutput(int inputIndex, int elements){
double[] input = new double[inputs[inputIndex].length];
for (int i = 0; i < inputs[inputIndex].length; i++) {
IBar bar = inputs[inputIndex][i];
input[i] = bar.getClose();
}
int j = 0;
//synchronize additional input with the main input
for (int i = 0; i < elements; i++) {
IBar bar = inputs[0][i];
long barTime = bar.getTime();
while (j < inputs[inputIndex].length && inputs[inputIndex][j].getTime() < barTime) {
j++;
}
if (j >= inputs[inputIndex].length || inputs[inputIndex][j].getTime() != barTime) {
outputs[inputIndex - 1][i] = Double.NaN;
} else {
//bar located, set up output
outputs[inputIndex - 1][i] = inputs[inputIndex][j].getClose();
}
}
}
Download
The information on this web site is provided only as general information, which may be incomplete or outdated. Click here for full disclaimer.