NinjaScript > Educational Resources > Tutorials > Indicators > Beginner - Indicator on Indicator >

Entering Calculation Logic

Print this Topic Previous pageReturn to chapter overviewNext page

The OnBarUpdate() method is called for each incoming tick or on the close of a bar (user defined) when performing real-time calculations and is called on each bar of a data series when re-calculating the indicator. For example, an indicator would be re-calculated when adding it to an existing chart that has existing price data displayed. Therefore, this is the main method called for indicator calculation and we will use this method to enter the script that will calculate a simple moving average of volume.


Calculating the Average

NinjaTrader has built in indicators that you can reference in your calculations. Since we are calculating a simple moving average of volume it would make sense for us to use the built in SMA indicator and Volume indicators.


Replace the wizard generated code with the following code into the OnBarUpdate() method in the NinjaScript Editor:


// Calculate the volume average
double average = SMA(VOL(), Period)[0];


Here we declared the variable "average" which is of type double. This serves as the temporary storage for the current value of the simple moving average of volume. We then use the simple moving average indicator and pass in the volume indicator as its input, pass in our indicator "Period" property (a parameter we defined in the wizard) and access the current value "[0]" that we will assign to our variable "average". If we wanted to assign the value one bar ago, we could have used "[1]".



Final Assignment

Enter the following code into the OnBarUpdate() method and below the code snippet you entered above:

// Set the calculated value to the plot

Here we assign the "average" value to the property that represents the plot data using its "Set()" method. We have just finished coding our simple moving average of volume. The OnBarUpdate() method in your editor should look identical to the image below.