In all options :
[HTML
]In `OnStateChange()`
if (State == State.Configure)
{
AddDataSeries(BarsPeriodType.Day, 1);
}
[/HTML]
## Option 1: Use an SMA internally to handle drawing :
[HTML
]In `OnStateChange()`
if (State == State.DataLoaded)
{
var sma = SMA(BarsArray[1], Period);
}
[/HTML]
Result : No error in console, nothing renders.
## Option 2: Copy the `OnBarUpdate` code to the new indicator:
void OnBarUpdate() { if (BarsInProgress != 1) return; if (BarsArray[1].BarsType.IsRemoveLastBarSupported) { if (CurrentBars[1] == 0) { Value[0] = Closes[1][0]; } else { double last = Value[1] * Math.Min(CurrentBars[1], Period); if (CurrentBars[1] >= Period) { Value[0] = (last + Closes[1][0] - Closes[1][Period]) / Math.Min(CurrentBars[1], Period); } else { Value[0] = ((last + Closes[1][0]) / (Math.Min(CurrentBars[1], Period) + 1)); } } } else { if (IsFirstTickOfBar) { priorSum = sum; } sum = priorSum + Closes[1][0] - (CurrentBars[1] >= Period ? Closes[1][Period] : 0); Value[0] = sum / (CurrentBars[1] < Period ? CurrentBars[1] + 1 : Period); } Print(Value[0]); }
4437
4419.5
4410.3125
4399.9375
4394.75
- Auto Scale,
- Panel same as input
- Visible
- Plots are thick and red
I have also tried adding
```
Values[1][0] = Value[0];
```
/// <summary> /// The SMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time. /// </summary> public class DailySMA : Indicator { private double priorSum; private double sum; protected override void OnStateChange() { if (State == State.SetDefaults) { Description = NinjaTrader.Custom.Resource.NinjaScriptIndicatorDescriptionSMA; Name = "Daily SMA"; IsOverlay = true; IsSuspendedWhileInactive = true; Period = 5; AddPlot(Brushes.Red, "Daily SMA"); } else if (State == State.Configure) { AddDataSeries(BarsPeriodType.Day, 1); } } protected override void OnBarUpdate() { if (BarsInProgress != 1) return; if (BarsArray[1].BarsType.IsRemoveLastBarSupported) { if (CurrentBars[1] == 0) { Values[1][0] = Closes[1][0]; } else { double last = Values[1][1] * Math.Min(CurrentBars[1], Period); if (CurrentBars[1] >= Period) { Value[0] = (last + Closes[1][0] - Closes[1][Period]) / Math.Min(CurrentBars[1], Period); } else { Value[0] = ((last + Closes[1][0]) / (Math.Min(CurrentBars[1], Period) + 1)); } } } else { if (IsFirstTickOfBar) { priorSum = sum; } sum = priorSum + Closes[1][0] - (CurrentBars[1] >= Period ? Closes[1][Period] : 0); Value[0] = sum / (CurrentBars[1] < Period ? CurrentBars[1] + 1 : Period); } Print(Value[0]); Values[1][0] = Value[0]; } #region Properties [Range(1, int.MaxValue), NinjaScriptProperty] [Display(ResourceType = typeof(Custom.Resource), Name = "Period", GroupName = "NinjaScriptParameters", Order = 0)] public int Period { get; set; } #endregion }
Comment