Entering Calculation Logic

NinjaScript > Educational Resources > Tutorials > Indicators > Intermediate - Historical Custom Data Series >

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 do our calculations.

 

Creating DataSeries Object

1. Declare a variable ("myDataSeries" used in this example) of type DataSeries that will hold a DataSeries object within the region "Variables"

2. Create a new DataSeries object and assigning it to the DataSeries variable within the Initialize() method

 

 

#region Variables
    private DataSeries myDataSeries; // Declare a DataSeries variable
#endregion

 

protected override void Initialize()
{
    myDataSeries = new DataSeries(this); // this refers to the indicator/strategy itself
                                        // and syncs the DataSeries object to historical
                                        // data bars
}

 

 

Storing calculations in the DataSeries object
Now that we have our DataSeries object we can store double values into it. For this example we will store a simple Close minus Open calculation.

Enter the following code into the OnBarUpdate() method:

 

// Calculate the range of the current bar and set the value
myDataSeries.Set(Close[0] - Open[0]);

 

The value of a DataSeries object will be aligned with the current bar. This means that all DataSeries objects will be synced with the CurrentBar index. It allows you to store a double value that corresponds with every bar.

 

 

Using DataSeries values
With our new DataSeries object we can continue with further calculations easily. We can now use our DataSeries object as input to an indicator method such as SMA or instead of always writing Close[0] - Open[0] we can substitute our DataSeries object instead as per the example below.

 

To plot our final calculation we will store the calculation in our Plot0.

1. Remove the wizard generated code in the OnBarUpdate() of “Plot0.Set(Close[0]);”

2. In the OnBarUpdate() method add the following code snippet

 

// Add the bar's range to the SMA value
Plot0.Set(SMA(SMAPeriod)[0] + myDataSeries[0]);

 
Here we assign the SMA + DataSeries value to the property that represents the plot data using its "Set()" method. We have just finished coding our DataSeries example. The code in your editor should look identical to the image below.

 

Tutorials_Indicators_30