Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

ATR indicator calculated using SMA instead of EMA(Wilder's)

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    ATR indicator calculated using SMA instead of EMA(Wilder's)

    As far as I know, ATR value in Ninjatrader is calculated using EMA. (more precisely, Wilder's method)

    Instead of that, how can I use SMA when calculating ATR value?



    #2
    Hello,

    In NinjaTrader, the default ATR (Average True Range) indicator uses Wilder's smoothing method (an EMA) to calculate the ATR. To use a simple moving average (SMA) instead, you'll need to create a custom ATR indicator.

    Here's how you can create a custom ATR indicator that uses an SMA: Step-by-Step Example:
    1. Create a New Custom Indicator:
      • Open NinjaTrader.
      • Go to New > NinjaScript Editor.
      • In the NinjaScript Editor, right-click and select New Indicator.
      • Name the indicator (e.g., CustomATR).
    2. Modify the Generated Code to Use SMA:

    Replace the generated code with the following:
    Code:
    #region Using declarations
    using System;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript.StrategyAnalyzerColumns;
    using NinjaTrader.NinjaScript.Strategies;
    using NinjaTrader.NinjaScript.Indicators;
    #endregion
    
    namespace NinjaTrader.NinjaScript.Indicators
    {
        public class CustomATR : Indicator
        {
            private int period = 14;
            private SMA smaTrueRange;
            private Series<double> trueRange;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description = @"Custom ATR using SMA instead of EMA.";
                    Name = "CustomATR";
                    Calculate = Calculate.OnEachTick;
                    IsOverlay = false;
                    AddPlot(Brushes.Orange, "CustomATR");
                }
                else if (State == State.DataLoaded)
                {
                    trueRange = new Series<double>(this);
                    smaTrueRange = SMA(trueRange, period);
                }
            }
    
            protected override void OnBarUpdate()
            {
                // Calculate True Range
                if (CurrentBar == 0)
                {
                    trueRange[0] = High[0] - Low[0];
                }
                else
                {
                    double trueHigh = Math.Max(High[0], Close[1]);
                    double trueLow = Math.Min(Low[0], Close[1]);
                    trueRange[0] = trueHigh - trueLow;
                }
    
                // Set the ATR value to the SMA of the True Range
                Value[0] = smaTrueRange[0];
            }
    
            #region Properties
            [Range(1, int.MaxValue), NinjaScriptProperty]
            [Display(Name = "Period", Description = "Number of bars used for the ATR calculation", Order = 1, GroupName = "Parameters")]
            public int Period
            {
                get { return period; }
                set { period = value; }
            }
            #endregion
        }
    }
    ​
    Explanation:
    1. True Range Calculation:
      • The trueRange series is calculated based on the highest of the current high and the previous close, and the lowest of the current low and the previous close.
    2. SMA Calculation:
      • The SMA of the trueRange series is calculated using the specified period.
    3. Indicator Value:
      • The Value[0] is set to the current value of the smaTrueRange, effectively creating an ATR that uses an SMA for its smoothing.
    Adding the Custom ATR to Your Chart:
    1. Compile the script by clicking the Compile button in the NinjaScript Editor.
    2. Add the custom indicator to your chart:
      • Right-click on the chart.
      • Select Indicators.
      • Find and add CustomATR.
      • Configure the Period if needed.

    This custom indicator will calculate the ATR using a simple moving average instead of Wilder's method (EMA). Adjust the parameters and logic as necessary to fit your specific requirements.

    Comment


      #3
      I copy pasted it and clicked compile button, but error occurred.

      Comment


        #4
        Hello,

        there are a few potential issues that might cause the script not to compile:
        1. Series Initialization: Ensure the Series<double> is initialized properly.
        2. Referencing SMA: Make sure the SMA calculation is correctly referenced.
        3. Check for Null References: Ensure that all series and indicators are properly initialized before accessing them.

        Here is a corrected version of the script with a few adjustments:
        Code:
        #region Using declarations
        using System;
        using NinjaTrader.Cbi;
        using NinjaTrader.Gui.Tools;
        using NinjaTrader.NinjaScript;
        using NinjaTrader.Data;
        using NinjaTrader.NinjaScript.StrategyAnalyzerColumns;
        using NinjaTrader.NinjaScript.Strategies;
        using NinjaTrader.NinjaScript.Indicators;
        #endregion
        
        namespace NinjaTrader.NinjaScript.Indicators
        {
            public class CustomATR : Indicator
            {
                private int period = 14;
                private SMA smaTrueRange;
                private Series<double> trueRange;
        
                protected override void OnStateChange()
                {
                    if (State == State.SetDefaults)
                    {
                        Description = @"Custom ATR using SMA instead of EMA.";
                        Name = "CustomATR";
                        Calculate = Calculate.OnEachTick;
                        IsOverlay = false;
                        AddPlot(Brushes.Orange, "CustomATR");
                    }
                    else if (State == State.DataLoaded)
                    {
                        trueRange = new Series<double>(this);
                        smaTrueRange = SMA(trueRange, period);
                    }
                }
        
                protected override void OnBarUpdate()
                {
                    if (CurrentBar < period)
                        return;
        
                    // Calculate True Range
                    if (CurrentBar == 0)
                    {
                        trueRange[0] = High[0] - Low[0];
                    }
                    else
                    {
                        double trueHigh = Math.Max(High[0], Close[1]);
                        double trueLow = Math.Min(Low[0], Close[1]);
                        trueRange[0] = trueHigh - trueLow;
                    }
        
                    // Ensure the SMA is ready
                    if (CurrentBar >= period)
                    {
                        // Set the ATR value to the SMA of the True Range
                        Value[0] = smaTrueRange[0];
                    }
                }
        
                #region Properties
                [Range(1, int.MaxValue), NinjaScriptProperty]
                [Display(Name = "Period", Description = "Number of bars used for the ATR calculation", Order = 1, GroupName = "Parameters")]
                public int Period
                {
                    get { return period; }
                    set { period = value; }
                }
                #endregion
            }
        }
        ​
        Explanation of Adjustments:
        1. Check CurrentBar Before Calculating:
          • Ensure there are enough bars before calculating (if (CurrentBar < period) return.
        2. Ensure SMA is Ready:
          • Check that the SMA series has enough data before accessing it (if (CurrentBar >= period)).
        3. Initialization:
          • Properly initialize trueRange and smaTrueRange in State.DataLoaded.

        By ensuring these steps, the script should compile and work as expected. This script calculates the ATR using an SMA of the true range values and plots it on the chart.

        Comment


          #5
          Still same error occurs when compile. It says

          The type or namespace name 'StrategyAnalyzerColumns' does not exist in the namespace 'NinjaTrader.....
          'Range' is not an attribute class.
          The type or namespace name 'DisplayAttribute' could not be...
          The name 'Brushes'does not exist.....
          (Check captured picture)

          Click image for larger version  Name:	image.png Views:	0 Size:	106.4 KB ID:	1306053Click image for larger version  Name:	image.png Views:	0 Size:	245.6 KB ID:	1306054Click image for larger version  Name:	image.png Views:	0 Size:	207.5 KB ID:	1306055

          Comment


            #6
            Hello,

            It looks like this was copy/pasted to a blank script, can you clarify if you are adding this logic to a script you initially created or do not have an original script to import to?

            Comment


              #7
              Do I need an original script (of 'CustomATR')?
              1. Create a New Custom Indicator:
                • Open NinjaTrader.
                • Go to New > NinjaScript Editor.
                • In the NinjaScript Editor, right-click and select New Indicator.
                • Name the indicator (e.g., CustomATR).
              2. Modify the Generated Code to Use SMA:
                Replace the generated code with the following:
              ​I just followed these steps and there is nothing else I did.

              Comment


                #8
                Hello,

                You will need to have your own custom indicator that exists that you are looking to add this functionality to. If you have not created a script yet, you can create one within the NS editor using NinjaScript and then you can add in the demonstrated logic where it makes sense in the existing script.

                Comment


                  #9
                  >You will need to have your own custom indicator that exists that you are looking to add this functionality to. If you have not created a script yet, you can create one within the NS editor using NinjaScript

                  Isn't the procedure you described the same as the one I followed (below)?
                  1. Create a New Custom Indicator:
                    • Open NinjaTrader.
                    • Go to New > NinjaScript Editor.
                    • In the NinjaScript Editor, right-click and select New Indicator.
                    • Name the indicator (e.g., CustomATR)
                  > and then you can add in the demonstrated logic where it makes sense in the existing script.

                  and this is same with (below)

                  2. Modify the Generated Code to Use SMA:
                  Replace the generated code with the following:

                  These are what I did. I didn't understand what the difference is.
                  ​​

                  Comment


                    #10
                    Hello,

                    Please note the example provided was simply an example of how this logic can be accessed/programmed in NinjaScript, and not a 'plug and play' type of solution. Are you experienced with NinjaScript or C# programming?

                    If not, you may want to consult some of the educational links on our help center regarding this topic. The errors seen are general programming errors that have to do with the setup of the script/file structure. You can also consult a NinjaScript consultant on our ecosystem for another option.

                    I apologize if I was misleading that this could simply be copy/pasted into a file and run without issue.

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                    0 responses
                    576 views
                    0 likes
                    Last Post Geovanny Suaza  
                    Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                    0 responses
                    334 views
                    1 like
                    Last Post Geovanny Suaza  
                    Started by Mindset, 02-09-2026, 11:44 AM
                    0 responses
                    101 views
                    0 likes
                    Last Post Mindset
                    by Mindset
                     
                    Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                    0 responses
                    553 views
                    1 like
                    Last Post Geovanny Suaza  
                    Started by RFrosty, 01-28-2026, 06:49 PM
                    0 responses
                    551 views
                    1 like
                    Last Post RFrosty
                    by RFrosty
                     
                    Working...
                    X