Using the Initialize() Method to Configure the Strategy
The Initialize() method is called once prior to running a strategy and can be used to set properties or call methods in preparation for running a strategy.
Enter the code contained within the Initialize() method in the image below into the Initialize() method in the NinjaScript Editor.
CalculateOnBarClose is set to true and sets the strategy to call the OnBarUpdate() method below on the close of each bar instead of each incoming tick.
The method signature for the RSI() indicator is:
RSI(int period, int smooth)
It is valid to have used the Add() method in the following manner:
Allows us to change the period and smooth parameters of the embedded RSI indicator in the strategy at run time. This gives us a higher level of flexibility when working with our strategy.
SetStopLoss() and SetProfitTarget() are called with CalculationMode.Ticks. This means that when a position is opened, the strategy will immediately submit a stop and target order with a price that is calculated based on the StopLoss and ProfitTarget parameters passed in offset from the positions average entry price.
Using the OnBarUpdate() Method for the Core Strategy Logic
The OnBarUpdate() method is called for each incoming tick or on the close of a bar (user defined) when performing real-time calculations. Therefore, this is the main method called for strategy calculation and we will use this method to enter the script that check for entry and exit conditions.
Enter the code contained within the OnBarUpdate() method in the image below into the OnBarUpdate() method in the NinjaScript Editor:
Since our strategy exit logic has already been set up in the Initialize() method above, we only need to focus on expressing our entry logic. The strategy entry logic is very straight forward and can be translated to English:
if we have not seen the number of bars specified by the user defined input "RSIPeriod" then do not go any further
if RSI crosses above a value of 20 within the last bar, go long
To accomplish this we used the following methods and properties:
CurrentBar - A value representing the current bar being processed (think of a chart where the left most bar would be equal to one)