Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Short horizontal line

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

    Short horizontal line

    I have a coding question. Any moving average can be drawn as a "line" or as a horizontal line in NT. See attached image. It shows the moving average as a line (to the left), then as a horizontal line (center).

    Now my question: Can the horizontal line be cut off so it goes let's say only 5 bars back? (like to the right in the attached image). How would I need to address this coding wise?

    sandman
    Attached Files

    #2
    Hello sandman,

    To accomplish this you would want to create a modified version of the SMA indicator. To create this you would want to set the plot to transparent and draw a line at the current sma going 5 bars back.

    For example:
    Code:
    // 
    // Copyright (C) 2006, NinjaTrader LLC <www.ninjatrader.com>.
    // NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
    //
    
    #region Using declarations
    using System;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.ComponentModel;
    using System.Xml.Serialization;
    using NinjaTrader.Data;
    using NinjaTrader.Gui.Chart;
    #endregion
    
    // This namespace holds all indicators and is required. Do not change it.
    namespace NinjaTrader.Indicator
    {
    	/// <summary>
    	/// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
    	/// </summary>
    	[Description("The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.")]
    	public class HorizontalSMA : Indicator
    	{
    		#region Variables
    		private int		period	= 14;
    [B]		private int barsBack = 5;
    		private Color smaLineColor = Color.Orange;[/B]
    		#endregion
    
    		/// <summary>
    		/// This method is used to configure the indicator and is called once before any bar data is loaded.
    		/// </summary>
    		protected override void Initialize()
    		{
    			Add(new Plot([B]Color.Transparent[/B], "HorizontalSMA"));
    			Overlay = true;
    		}
    
    		/// <summary>
    		/// Called on each bar update event (incoming tick).
    		/// </summary>
    		protected override void OnBarUpdate()
    		{
    			if (CurrentBar == 0)
    				Value.Set(Input[0]);
    			else
    			{
    				double last = Value[1] * Math.Min(CurrentBar, Period);
    
    				if (CurrentBar >= Period)
    					Value.Set((last + Input[0] - Input[Period]) / Math.Min(CurrentBar, Period));
    				else
    					Value.Set((last + Input[0]) / (Math.Min(CurrentBar, Period) + 1));
    			}
    [B]			if(CurrentBar > barsBack)
    				DrawLine("HorizontalSMA", 0, Value[0], barsBack, Value[0], smaLineColor);[/B]
    		}
    		#region Properties
    		/// <summary>
    		/// </summary>
    		[Description("Numbers of bars used for calculations")]
    		[GridCategory("Parameters")]
    		public int Period
    		{
    			get { return period; }
    			set { period = Math.Max(1, value); }
    		}
    [B]		[Description("Numbers of bars back to draw the HorizontalSMA line")]
    		[GridCategory("Parameters")]
    		public int BarsBack
    		{
    			get { return barsBack; }
    			set { barsBack = Math.Max(1, value); }
    		}
    		[XmlIgnore()]
    		[Description("Color of the HorizontalSMA line")]
    		[GridCategory("Parameters")]
    		public Color SmaLineColor
    		{
    			get { return smaLineColor; }
    			set { smaLineColor = value; }
    		}
    		[Browsable(false)]
    		public string SmaLineColorSerialize
    		{
         		get { return NinjaTrader.Gui.Design.SerializableColor.ToString(smaLineColor); }
         		set { smaLineColor = NinjaTrader.Gui.Design.SerializableColor.FromString(value); }
    		}[/B]
            #endregion
    	}
    }
    
    #region NinjaScript generated code. Neither change nor remove.
    // This namespace holds all indicators and is required. Do not change it.
    namespace NinjaTrader.Indicator
    {
        public partial class Indicator : IndicatorBase
        {
            private HorizontalSMA[] cacheHorizontalSMA = null;
    
            private static HorizontalSMA checkHorizontalSMA = new HorizontalSMA();
    
            /// <summary>
            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
            /// </summary>
            /// <returns></returns>
            public HorizontalSMA HorizontalSMA(int barsBack, int period, Color smaLineColor)
            {
                return HorizontalSMA(Input, barsBack, period, smaLineColor);
            }
    
            /// <summary>
            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
            /// </summary>
            /// <returns></returns>
            public HorizontalSMA HorizontalSMA(Data.IDataSeries input, int barsBack, int period, Color smaLineColor)
            {
                if (cacheHorizontalSMA != null)
                    for (int idx = 0; idx < cacheHorizontalSMA.Length; idx++)
                        if (cacheHorizontalSMA[idx].BarsBack == barsBack && cacheHorizontalSMA[idx].Period == period && cacheHorizontalSMA[idx].SmaLineColor == smaLineColor && cacheHorizontalSMA[idx].EqualsInput(input))
                            return cacheHorizontalSMA[idx];
    
                lock (checkHorizontalSMA)
                {
                    checkHorizontalSMA.BarsBack = barsBack;
                    barsBack = checkHorizontalSMA.BarsBack;
                    checkHorizontalSMA.Period = period;
                    period = checkHorizontalSMA.Period;
                    checkHorizontalSMA.SmaLineColor = smaLineColor;
                    smaLineColor = checkHorizontalSMA.SmaLineColor;
    
                    if (cacheHorizontalSMA != null)
                        for (int idx = 0; idx < cacheHorizontalSMA.Length; idx++)
                            if (cacheHorizontalSMA[idx].BarsBack == barsBack && cacheHorizontalSMA[idx].Period == period && cacheHorizontalSMA[idx].SmaLineColor == smaLineColor && cacheHorizontalSMA[idx].EqualsInput(input))
                                return cacheHorizontalSMA[idx];
    
                    HorizontalSMA indicator = new HorizontalSMA();
                    indicator.BarsRequired = BarsRequired;
                    indicator.CalculateOnBarClose = CalculateOnBarClose;
    #if NT7
                    indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256;
                    indicator.MaximumBarsLookBack = MaximumBarsLookBack;
    #endif
                    indicator.Input = input;
                    indicator.BarsBack = barsBack;
                    indicator.Period = period;
                    indicator.SmaLineColor = smaLineColor;
                    Indicators.Add(indicator);
                    indicator.SetUp();
    
                    HorizontalSMA[] tmp = new HorizontalSMA[cacheHorizontalSMA == null ? 1 : cacheHorizontalSMA.Length + 1];
                    if (cacheHorizontalSMA != null)
                        cacheHorizontalSMA.CopyTo(tmp, 0);
                    tmp[tmp.Length - 1] = indicator;
                    cacheHorizontalSMA = tmp;
                    return indicator;
                }
            }
        }
    }
    
    // This namespace holds all market analyzer column definitions and is required. Do not change it.
    namespace NinjaTrader.MarketAnalyzer
    {
        public partial class Column : ColumnBase
        {
            /// <summary>
            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
            /// </summary>
            /// <returns></returns>
            [Gui.Design.WizardCondition("Indicator")]
            public Indicator.HorizontalSMA HorizontalSMA(int barsBack, int period, Color smaLineColor)
            {
                return _indicator.HorizontalSMA(Input, barsBack, period, smaLineColor);
            }
    
            /// <summary>
            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
            /// </summary>
            /// <returns></returns>
            public Indicator.HorizontalSMA HorizontalSMA(Data.IDataSeries input, int barsBack, int period, Color smaLineColor)
            {
                return _indicator.HorizontalSMA(input, barsBack, period, smaLineColor);
            }
        }
    }
    
    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.Strategy
    {
        public partial class Strategy : StrategyBase
        {
            /// <summary>
            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
            /// </summary>
            /// <returns></returns>
            [Gui.Design.WizardCondition("Indicator")]
            public Indicator.HorizontalSMA HorizontalSMA(int barsBack, int period, Color smaLineColor)
            {
                return _indicator.HorizontalSMA(Input, barsBack, period, smaLineColor);
            }
    
            /// <summary>
            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
            /// </summary>
            /// <returns></returns>
            public Indicator.HorizontalSMA HorizontalSMA(Data.IDataSeries input, int barsBack, int period, Color smaLineColor)
            {
                if (InInitialize && input == null)
                    throw new ArgumentException("You only can access an indicator with the default input/bar series from within the 'Initialize()' method");
    
                return _indicator.HorizontalSMA(input, barsBack, period, smaLineColor);
            }
        }
    }
    #endregion
    I have made the changes from the standard SMA indicator in bold for your convenience.

    I have attached the modified indicator to my response as a reference. You can import it by going to File -> Utilities -> Import NinjaScript
    You would then apply the HorizontalSMA indicator to your chart.
    Please let me know if you have any questions or if I may be of further assistance.
    Attached Files
    Michael M.NinjaTrader Quality Assurance

    Comment


      #3
      Michael. Thank you very much for your FULL answer. Very educational, especially for me because I do not consider myself a programmer. I have just about enough understanding so that I can combine and modify various things in the code. I was able to use the code from you to amend it for a two colored EMA and I added an adjustment possibility for the width of the line). I wonder whether you shouldn't post this in the other forum section Reference Samples so others can find it too.

      On this subject, would you mind posting something that shows how to NOT plot a full regular SMA but let's say only for the last 5 bars (similar to the horizontal indicator with "barsback").

      sandman

      Comment


        #4
        Hello sandman,
        You could use DrawHorizontalLine() to draw a line at the value of your SMA 5 bars ago. I have included an example below that draws a line at the value of an SMA 5 bars ago.


        Code:
        [COLOR=#000000][FONT=Tahoma][LEFT][LEFT] [FONT=Courier New][SIZE=2][COLOR=#0000FF]protected[/SIZE][FONT=Courier New][SIZE=2][COLOR=#0000FF]override[/COLOR][/SIZE][/FONT] [FONT=Courier New][SIZE=2][COLOR=#0000FF]void[/COLOR][/SIZE][/FONT] [FONT=Courier New][SIZE=2]OnBarUpdate()[/SIZE][/FONT]
        [FONT=Courier New][SIZE=2]        {[/SIZE][/FONT]
         [FONT=Courier New][SIZE=2][COLOR=#0000FF]if[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2] (CurrentBar > [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]14[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2]){[/SIZE][/FONT]
        [FONT=Courier New][SIZE=2]            DrawHorizontalLine([/SIZE][/FONT] [FONT=Courier New][SIZE=2][COLOR=#800000]"5BaragoSMALine"[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2] , SMA([/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]14[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2])[[/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]5[/COLOR][/SIZE][/FONT] [FONT=Courier New][SIZE=2]], Color.Black);     [/SIZE][/FONT]
        [FONT=Courier New][SIZE=2]            }[/SIZE][/FONT]
        [FONT=Courier New][SIZE=2]        }[/SIZE][/FONT][/LEFT]
        [/FONT][/COLOR]
        [/LEFT]
        [/FONT][/COLOR]
        Shawn B.NinjaTrader Customer Service

        Comment


          #5
          No ShawnB, that's not it. What you laid out is what MichaelM already provided. My question now was/is for some code that shows "how to NOT plot a full regular SMA but let's say only for the last 5 bars".

          sandman

          Comment


            #6
            Hello sandman,
            You could use DrawLine() to draw a line at the value of your SMA only to 5 bars ago. I have included an example below that draws a line at the value of an SMA 5 bars ago


            Code:
            [COLOR=#000000][FONT=Tahoma][LEFT][LEFT][LEFT][LEFT][LEFT][FONT=Courier New][SIZE=2]            [/SIZE] [FONT=Courier New][SIZE=2][COLOR=#0000FF]protected[/SIZE][/FONT][FONT=Courier New][SIZE=2] [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000FF]override[/COLOR][/SIZE][/FONT] [FONT=Courier New][SIZE=2][COLOR=#0000FF]void[/COLOR][/SIZE][/FONT] [FONT=Courier New][SIZE=2]OnBarUpdate()[/SIZE][/FONT]
            [FONT=Courier New][SIZE=2]        {[/SIZE][/FONT]
            [FONT=Courier New][SIZE=2]             [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000FF]if[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2] (CurrentBar > [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]14[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2]){[/SIZE][/FONT]
            [FONT=Courier New][SIZE=2]             [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000FF]for[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2] ([/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000FF]int[/COLOR][/SIZE][/FONT] [FONT=Courier New][SIZE=2]i = [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]0[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2]; i < [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]5[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2]; i++)[/SIZE][/FONT]
            [FONT=Courier New][SIZE=2]{[/SIZE][/FONT]
            [FONT=Courier New][SIZE=2]DrawLine( [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800000]"SMA"[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2] + i.ToString(), [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000FF]false[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2] , i + [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]1[/COLOR][/SIZE][/FONT] [FONT=Courier New][SIZE=2], SMA( [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]14[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2])[i + [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]1[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2]], i, SMA( [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]14[/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2] )[i], Color.Black, DashStyle.Solid, [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#800080]1[/COLOR][/SIZE][/FONT] [FONT=Courier New][SIZE=2]);}[/SIZE][/FONT]
            [FONT=Courier New][SIZE=2]}     }[/SIZE][/FONT][/LEFT]
            [/FONT][/COLOR]
            [/LEFT]
            [/LEFT]
            [/LEFT]
            [/LEFT]
            [/FONT][/COLOR]
            Shawn B.NinjaTrader Customer Service

            Comment


              #7
              Shawn. Thanks very much. That is it. I applied this for a LinReg and added the possibilities to chose the number of bars to go back ("BarsBack") and width of the line ("wline"). See attached "LinRegShort" image. Output is what was intended.

              Then I tried to apply this to a Colored LinReg (meaning different colors for rising and falling). But here I ran into problems. Though it does compile, the result does not match: the line is colored wrongly (it should be blue for rising but is red and it goes back more bars as it should). See attached image ColoredLinRegShort which shows the code I used, chart and indicator menu box.

              Any idea what I did wrong or what I need to change in the code so it outputs what is intended.

              sandman
              Attached Files

              Comment


                #8
                Hello,
                We have reviewed the screenshots and have created an example of how you would get this working.


                In Initialize() we removed the additional Rising and Falling plots as they were not being set and did not change. We also changed the Neutral plot to simply a data series as it was not actually being plotted.

                In OnBarUpdate we made quite a few changes and will be breakign those up.

                We left the for loop the same but put the if & else statements in it as they need to run in the loop.

                We change the if statement for if(Falling(Neutral)) to if(Netrual)[i] < Netutral[i+1]).
                The reasoning for this is Falling looks at the last bar and compares it to the previous bar of the data series. When this occurred though it change the color for the entire line instead of having one color of rising and one color for falling.
                Then we made the tag for both DrawLine methods the same as we only want it to appear there to be one line instead of two lines. Making it so that they have a tag of ""Line " + i"" makes it so that there is never a blue line and a red line for the same instance of i. For example there would not be a red Line+3 and a Blue Line + 3 it will be just one or the other.
                We changed the else if to just an else as well as if it was an else if there may be a gap that appears.

                I have provided the full code below as well.
                Code:
                #region Variables
                        // Wizard generated variables
                            private int period = 10; // Default setting for Period
                            private int barsBack = 7; // Default setting for BarsBack
                            private int wline = 3; // Default setting for Wline
                			private Color downColor = Color.Red;
                			private Color upColor   = Color.Blue;
                			private DataSeries Neutral;
                        // User defined variables (add any user defined variables below)
                        #endregion
                
                        /// <summary>
                        /// This method is used to configure the indicator and is called once before any bar data is loaded.
                        /// </summary>
                        protected override void Initialize()
                        {
                            Neutral = new DataSeries(this);
                			Overlay				= true;
                        }
                
                        /// <summary>
                        /// Called on each bar update event (incoming tick)
                        /// </summary>
                        protected override void OnBarUpdate()
                        {
                            // Use this method for calculating your indicator values. Assign a value to each
                            // plot below by replacing 'Close[0]' with your own formula.
                			if(CurrentBar < period)
                				return;
                			
                			Neutral.Set(LinReg(period)[0]);
                			
                			if(CurrentBar > period)
                			{
                				for (int i = 0; i < barsBack; i++)
                				{
                					DrawDot("string" , true, barsBack, Close[barsBack], Color.Black);
                					if(Neutral[i] < Neutral[i+1])
                					{
                						DrawLine("Line" + i, false, i + 1, LinReg(period)[i + 1], i, LinReg(period)[i], downColor, DashStyle.Solid, wline);
                					}
                					else
                					{
                						DrawLine("Line" + i, false, i + 1, LinReg(period)[i + 1], i, LinReg(period)[i], upColor, DashStyle.Solid, wline);
                					}
                					
                				}
                			}
                        }
                Please let me know if you have any questions.
                Cody B.NinjaTrader Customer Service

                Comment


                  #9
                  CodyB, Thank you VERY much, that works nicely. And thank you for the explanations which I partly understand and which are partly way over my head. (I am not a programmer). Allow me to ask a few questions:

                  a. You added a "DrawDot" command which I could of course delete if I wanted to. What was your reasoning to add this?

                  b. There is this "line":
                  (int i = 0; i < barsBack; i++)

                  Could you explain to me in layman's terms what the "i" and "i++" are or refer me to where I could read about it in simple terms?

                  sandman

                  Comment


                    #10
                    Helllo,
                    My apologies I did not realize I left the DrawDot method in my example, you can delete this. I used the DrawDot method for assistance for debugging. I prefer to use drawing tools for debugging, this is a persondal preference for everyone. For more information on Alert and Debug methods please see the following link, http://ninjatrader.com/support/helpG...ug_methods.htm

                    The line for(int i = 0; i < barsBack; i++) is a for loop. The integer i that is created is a variable to tell the the loop how many times to run. The loop starts i at 0 and then the i++ makes it so that i is added by 1 each time it runs through the loop. The loop will run only as long as it is less than barsBack. For more information on for looping commands please see the following link, http://ninjatrader.com/support/helpG...g_commands.htm
                    The ++ operator is called and increment and adds 1 to a variable. For more information on the increment operator please see the following link,
                    If we can be of any other assistance please let us know.
                    Cody B.NinjaTrader Customer Service

                    Comment


                      #11
                      Hi, Do you have this for NinjaTrader 8.... (HorizontalSMA.zip)? Thank you!​

                      Comment


                        #12
                        Hello ldanenberg,

                        Welcome to the NinjaTrader forums!

                        Here is how this code would look for NinjaTrader 8.

                        Code:
                        private int period = 10; // Default setting for Period
                        private int barsBack = 7; // Default setting for BarsBack
                        private int wline = 3; // Default setting for Wline
                        private Brush downColor = Color.Red;
                        private Brush upColor = Color.Blue;
                        private DataSeries Neutral;
                        
                        protected override void OnStateChange()
                        {
                        if (State == State.SetDefaults)
                        {
                        Name = "MyScript";
                        IsOverlay = true;
                        }
                        else if (State == State.DataLoaded)
                        {
                        period = 10; // Default setting for Period
                        barsBack = 7; // Default setting for BarsBack
                        wline = 3; // Default setting for Wline
                        downColor = Color.Red;
                        upColor = Color.Blue;
                        Neutral = new Series<double>(this);
                        }
                        }
                        
                        protected override void OnBarUpdate()
                        {
                        if(CurrentBar < period)
                        return;
                        
                        Neutral[0] = LinReg(period)[0];
                        
                        if(CurrentBar > period)
                        {
                        for (int i = 0; i < barsBack; i++)
                        {
                        Draw.Dot(this, "string" , true, barsBack, Close[barsBack], Brushes.Black);
                        if(Neutral[i] < Neutral[i+1])
                        {
                        Draw.Line(this, "Line" + i, false, i + 1, LinReg(period)[i + 1], i, LinReg(period)[i], downColor, DashStyleHelper.Solid, wline);
                        }
                        else
                        {
                        Draw.Line(this, "Line" + i, false, i + 1, LinReg(period)[i + 1], i, LinReg(period)[i], upColor, DashStyleHelper.Solid, wline);
                        }
                        
                        }
                        }
                        }​
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Hi Chelsea, actually I was asking for the NT8 conversion for Michael’s "HorizontalSMA" code (written for NT7, see second post).



                          thanks!
                          Last edited by ldanenberg; 04-09-2024, 06:12 PM.

                          Comment


                            #14
                            Code:
                            //
                            // Copyright (C) 2006, NinjaTrader LLC <www.ninjatrader.com>.
                            // NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
                            //
                            
                            [HASHTAG="t3322"]region[/HASHTAG] Using declarations
                            using System;
                            using System.Diagnostics;
                            using System.Drawing;
                            using System.Drawing.Drawing2D;
                            using System.ComponentModel;
                            using System.Xml.Serialization;
                            using NinjaTrader.Data;
                            using NinjaTrader.Gui.Chart;
                            #endregion
                            
                            // This namespace holds all indicators and is required. Do not change it.
                            namespace NinjaTrader.Indicator
                            {
                            /// <summary>
                            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
                            /// </summary>
                            [Description("The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.")]
                            public class HorizontalSMA : Indicator
                            {
                            [HASHTAG="t3322"]region[/HASHTAG] Variables
                            private int period = 14;
                            [B]private int barsBack = 5;
                            private Color smaLineColor = Color.Orange;[/B]
                            #endregion
                            
                            /// <summary>
                            /// This method is used to configure the indicator and is called once before any bar data is loaded.
                            /// </summary>
                            protected override void Initialize()
                            {
                            Add(new Plot([B]Color.Transparent[/B], "HorizontalSMA"));
                            Overlay = true;
                            }
                            
                            /// <summary>
                            /// Called on each bar update event (incoming tick).
                            /// </summary>
                            protected override void OnBarUpdate()
                            {
                            if (CurrentBar == 0)
                            Value.Set(Input[0]);
                            else
                            {
                            double last = Value[1] * Math.Min(CurrentBar, Period);
                            
                            if (CurrentBar >= Period)
                            Value.Set((last + Input[0] - Input[Period]) / Math.Min(CurrentBar, Period));
                            else
                            Value.Set((last + Input[0]) / (Math.Min(CurrentBar, Period) + 1));
                            }
                            [B]if(CurrentBar > barsBack)
                            DrawLine("HorizontalSMA", 0, Value[0], barsBack, Value[0], smaLineColor);[/B]
                            }
                            [HASHTAG="t3322"]region[/HASHTAG] Properties
                            /// <summary>
                            /// </summary>
                            [Description("Numbers of bars used for calculations")]
                            [GridCategory("Parameters")]
                            public int Period
                            {
                            get { return period; }
                            set { period = Math.Max(1, value); }
                            }
                            [B][Description("Numbers of bars back to draw the HorizontalSMA line")]
                            [GridCategory("Parameters")]
                            public int BarsBack
                            {
                            get { return barsBack; }
                            set { barsBack = Math.Max(1, value); }
                            }
                            [XmlIgnore()]
                            [Description("Color of the HorizontalSMA line")]
                            [GridCategory("Parameters")]
                            public Color SmaLineColor
                            {
                            get { return smaLineColor; }
                            set { smaLineColor = value; }
                            }
                            [Browsable(false)]
                            public string SmaLineColorSerialize
                            {
                            get { return NinjaTrader.Gui.Design.SerializableColor.ToString( smaLineColor); }
                            set { smaLineColor = NinjaTrader.Gui.Design.SerializableColor.FromStrin g(value); }
                            }[/B]
                            #endregion
                            }
                            }
                            
                            [HASHTAG="t3322"]region[/HASHTAG] NinjaScript generated code. Neither change nor remove.
                            // This namespace holds all indicators and is required. Do not change it.
                            namespace NinjaTrader.Indicator
                            {
                            public partial class Indicator : IndicatorBase
                            {
                            private HorizontalSMA[] cacheHorizontalSMA = null;
                            
                            private static HorizontalSMA checkHorizontalSMA = new HorizontalSMA();
                            
                            /// <summary>
                            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
                            /// </summary>
                            /// <returns></returns>
                            public HorizontalSMA HorizontalSMA(int barsBack, int period, Color smaLineColor)
                            {
                            return HorizontalSMA(Input, barsBack, period, smaLineColor);
                            }
                            
                            /// <summary>
                            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
                            /// </summary>
                            /// <returns></returns>
                            public HorizontalSMA HorizontalSMA(Data.IDataSeries input, int barsBack, int period, Color smaLineColor)
                            {
                            if (cacheHorizontalSMA != null)
                            for (int idx = 0; idx < cacheHorizontalSMA.Length; idx++)
                            if (cacheHorizontalSMA[idx].BarsBack == barsBack && cacheHorizontalSMA[idx].Period == period && cacheHorizontalSMA[idx].SmaLineColor == smaLineColor && cacheHorizontalSMA[idx].EqualsInput(input))
                            return cacheHorizontalSMA[idx];
                            
                            lock (checkHorizontalSMA)
                            {
                            checkHorizontalSMA.BarsBack = barsBack;
                            barsBack = checkHorizontalSMA.BarsBack;
                            checkHorizontalSMA.Period = period;
                            period = checkHorizontalSMA.Period;
                            checkHorizontalSMA.SmaLineColor = smaLineColor;
                            smaLineColor = checkHorizontalSMA.SmaLineColor;
                            
                            if (cacheHorizontalSMA != null)
                            for (int idx = 0; idx < cacheHorizontalSMA.Length; idx++)
                            if (cacheHorizontalSMA[idx].BarsBack == barsBack && cacheHorizontalSMA[idx].Period == period && cacheHorizontalSMA[idx].SmaLineColor == smaLineColor && cacheHorizontalSMA[idx].EqualsInput(input))
                            return cacheHorizontalSMA[idx];
                            
                            HorizontalSMA indicator = new HorizontalSMA();
                            indicator.BarsRequired = BarsRequired;
                            indicator.CalculateOnBarClose = CalculateOnBarClose;
                            #if NT7
                            indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256;
                            indicator.MaximumBarsLookBack = MaximumBarsLookBack;
                            #endif
                            indicator.Input = input;
                            indicator.BarsBack = barsBack;
                            indicator.Period = period;
                            indicator.SmaLineColor = smaLineColor;
                            Indicators.Add(indicator);
                            indicator.SetUp();
                            
                            HorizontalSMA[] tmp = new HorizontalSMA[cacheHorizontalSMA == null ? 1 : cacheHorizontalSMA.Length + 1];
                            if (cacheHorizontalSMA != null)
                            cacheHorizontalSMA.CopyTo(tmp, 0);
                            tmp[tmp.Length - 1] = indicator;
                            cacheHorizontalSMA = tmp;
                            return indicator;
                            }
                            }
                            }
                            }
                            
                            // This namespace holds all market analyzer column definitions and is required. Do not change it.
                            namespace NinjaTrader.MarketAnalyzer
                            {
                            public partial class Column : ColumnBase
                            {
                            /// <summary>
                            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
                            /// </summary>
                            /// <returns></returns>
                            [Gui.Design.WizardCondition("Indicator")]
                            public Indicator.HorizontalSMA HorizontalSMA(int barsBack, int period, Color smaLineColor)
                            {
                            return _indicator.HorizontalSMA(Input, barsBack, period, smaLineColor);
                            }
                            
                            /// <summary>
                            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
                            /// </summary>
                            /// <returns></returns>
                            public Indicator.HorizontalSMA HorizontalSMA(Data.IDataSeries input, int barsBack, int period, Color smaLineColor)
                            {
                            return _indicator.HorizontalSMA(input, barsBack, period, smaLineColor);
                            }
                            }
                            }
                            
                            // This namespace holds all strategies and is required. Do not change it.
                            namespace NinjaTrader.Strategy
                            {
                            public partial class Strategy : StrategyBase
                            {
                            /// <summary>
                            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
                            /// </summary>
                            /// <returns></returns>
                            [Gui.Design.WizardCondition("Indicator")]
                            public Indicator.HorizontalSMA HorizontalSMA(int barsBack, int period, Color smaLineColor)
                            {
                            return _indicator.HorizontalSMA(Input, barsBack, period, smaLineColor);
                            }
                            
                            /// <summary>
                            /// The HorizontalSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
                            /// </summary>
                            /// <returns></returns>
                            public Indicator.HorizontalSMA HorizontalSMA(Data.IDataSeries input, int barsBack, int period, Color smaLineColor)
                            {
                            if (InInitialize && input == null)
                            throw new ArgumentException("You only can access an indicator with the default input/bar series from within the 'Initialize()' method");
                            
                            return _indicator.HorizontalSMA(input, barsBack, period, smaLineColor);
                            }
                            }
                            }
                            #endregion

                            -> From Michael at Ninja customer service..... :

                            "I have made the changes from the standard SMA indicator in bold for your convenience.

                            I have attached the modified indicator to my response as a reference. You can import it by going to File -> Utilities -> Import NinjaScript
                            You would then apply the HorizontalSMA indicator to your chart.
                            Please let me know if you have any questions or if I may be of further assistance.​"

                            Thank you, in advance, for converting this to NT 8 for me!
                            Last edited by ldanenberg; 04-09-2024, 06:11 PM.

                            Comment


                              #15
                              Click image for larger version  Name:	Screen Shot 2024-04-09 at 8.08.56 PM.png Views:	0 Size:	596.2 KB ID:	1299064Hi, I may have gotten HorizontalSMA to work in NT8, however, I am not able to drag and drop it from one panel to another (I want the HorizontalSMA(15-min), to drag over to the top (1-min) panel.. i.e. panel=1).

                              I think maybe because its a "draw.line" it won't let me drag it to the other panel?.. Also, when I tried to assign the HorizontalSMA to a different Panel in Properties, it doesn't move out of the current panel (panel=3) to the top panel.. (panel=1). Even when I go to properties and "unlock" the line, it still won't move to the top panel!!

                              I can drag the "regular" SMA indicator (15-min) to another panel (with different time frame), but I can't get it to work with this modified version.

                              **** If you could show me how to modify the HorizontalSMA so that it calculates on the 15-min time frame (inside the 1-min chart) that would be ideal!!! *****

                              Let me know your thoughts! thanks

                              Code:
                              //
                              // Copyright (C) 2023, NinjaTrader LLC <www.ninjatrader.com>.
                              // NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
                              //
                              #region Using declarations
                              using System;
                              using System.Collections.Generic;
                              using System.ComponentModel;
                              using System.ComponentModel.DataAnnotations;
                              using System.Linq;
                              using System.Text;
                              using System.Threading.Tasks;
                              using System.Windows;
                              using System.Windows.Input;
                              using System.Windows.Media;
                              using System.Xml.Serialization;
                              using NinjaTrader.Cbi;
                              using NinjaTrader.Gui;
                              using NinjaTrader.Gui.Chart;
                              using NinjaTrader.Gui.SuperDom;
                              using NinjaTrader.Data;
                              using NinjaTrader.NinjaScript;
                              using NinjaTrader.Core.FloatingPoint;
                              using NinjaTrader.NinjaScript.DrawingTools;
                              #endregion
                               
                              // This namespace holds indicators in this folder and is required. Do not change it.
                              namespace NinjaTrader.NinjaScript.Indicators
                              {
                                          /// <summary>
                                          /// The HORIZONTALSMA (Simple Moving Average) is an indicator that shows the average value of a security's price over a period of time.
                                          /// </summary>
                                          public class HORIZONTALSMA : Indicator
                                          {
                                                      private double priorSum;
                                                      private double sum;
                                                      private int barsBack = 5;
                                                      private Brush smaLineColor = Brushes.HotPink;
                                                           private int wline = 2;
                               
                                                      protected override void OnStateChange()
                                                      {
                                                                  if (State == State.SetDefaults)
                                                                  {
                                                                              
                                                                              Description = "my horizontalSMA description";
                              Name = "HorizontalSMA";
                                                                  
                                                                  
                                                                              IsOverlay                                                        = true;
                                                                              IsSuspendedWhileInactive     = true;
                                                                              Period                                                              = 14;
                               
                               
                                                                              AddPlot(Brushes.Transparent, "HorizontalSMA");
                                                                  }
                                                                  else if (State == State.Configure)
                                                                  {
                                                                              priorSum         = 0;
                                                                              sum                             = 0;
                                                                  }
                                                      }
                               
                                                      protected override void OnBarUpdate()
                                                      {
                                                                  if (BarsArray[0].BarsType.IsRemoveLastBarSupported)
                                                                  {
                                                                              if (CurrentBar == 0)
                                                                                          Value[0] = Input[0];
                                                                              else
                                                                              {
                                                                                          double last = Value[1] * Math.Min(CurrentBar, Period);
                               
                                                                                          if (CurrentBar >= Period)
                                                                                                      Value[0] = (last + Input[0] - Input[Period]) / Math.Min(CurrentBar, Period);
                                                                                          else
                                                                                                      Value[0] = ((last + Input[0]) / (Math.Min(CurrentBar, Period) + 1));
                                                                              }
                                                                  }
                                                                  else
                                                                  {
                                                                              if (IsFirstTickOfBar)
                                                                                          priorSum = sum;
                               
                                                                              sum = priorSum + Input[0] - (CurrentBar >= Period ? Input[Period] : 0);
                                                                              Value[0] = sum / (CurrentBar < Period ? CurrentBar + 1 : Period);
                                                                  }
                                                             if(CurrentBar > barsBack)
                                                                   Draw.Line(this, "HorizontalSMA", false, 0, Value[0], barsBack, Value[0], smaLineColor, DashStyleHelper.Dash, wline);    
                                                      }
                               
                                                      #region Properties
                                                      [Range(1, int.MaxValue), NinjaScriptProperty]
                                                      [Display(ResourceType = typeof(Custom.Resource), Name = "Period", GroupName = "NinjaScriptParameters", Order = 0)]
                                                      public int Period
                                                      { get; set;
                              }
                               
                              [XmlIgnore()]
                              [Display(Name = "smaLineColor", GroupName = "NinjaScriptParameters", Order = 0)]
                              public Brush SmaLineColor
                              {
                               get; set;
                              }
                              [Browsable(false)]
                              public string SmaLineColorSerialize
                              {
                              get { return Serialize.BrushToString(smaLineColor); }
                              set { smaLineColor = Serialize.StringToBrush(value); }
                              }
                               
                                                      #endregion
                                          }
                              }
                               
                              #region NinjaScript generated code. Neither change nor remove.
                               
                              namespace NinjaTrader.NinjaScript.Indicators
                              {
                                          public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
                                          {
                                                      private HORIZONTALSMA[] cacheHORIZONTALSMA;
                                                      public HORIZONTALSMA HORIZONTALSMA(int period)
                                                      {
                                                                  return HORIZONTALSMA(Input, period);
                                                      }
                               
                                                      public HORIZONTALSMA HORIZONTALSMA(ISeries<double> input, int period)
                                                      {
                                                                  if (cacheHORIZONTALSMA != null)
                                                                              for (int idx = 0; idx < cacheHORIZONTALSMA.Length; idx++)
                                                                                          if (cacheHORIZONTALSMA[idx] != null && cacheHORIZONTALSMA[idx].Period == period && cacheHORIZONTALSMA[idx].EqualsInput(input))
                                                                                                      return cacheHORIZONTALSMA[idx];
                                                                  return CacheIndicator<HORIZONTALSMA>(new HORIZONTALSMA(){ Period = period }, input, ref cacheHORIZONTALSMA);
                                                      }
                                          }
                              }
                               
                              namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
                              {
                                          public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
                                          {
                                                      public Indicators.HORIZONTALSMA HORIZONTALSMA(int period)
                                                      {
                                                                  return indicator.HORIZONTALSMA(Input, period);
                                                      }
                               
                                                      public Indicators.HORIZONTALSMA HORIZONTALSMA(ISeries<double> input , int period)
                                                      {
                                                                  return indicator.HORIZONTALSMA(input, period);
                                                      }
                                          }
                              }
                               
                              namespace NinjaTrader.NinjaScript.Strategies
                              {
                                          public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
                                          {
                                                      public Indicators.HORIZONTALSMA HORIZONTALSMA(int period)
                                                      {
                                                                  return indicator.HORIZONTALSMA(Input, period);
                                                      }
                               
                                                      public Indicators.HORIZONTALSMA HORIZONTALSMA(ISeries<double> input , int period)
                                                      {
                                                                  return indicator.HORIZONTALSMA(input, period);
                                                      }
                                          }
                              }
                               
                              #endregion
                               
                              ​
                              Last edited by ldanenberg; 04-09-2024, 11:31 PM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by aa731, Today, 02:54 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post aa731
                              by aa731
                               
                              Started by thanajo, 05-04-2021, 02:11 AM
                              3 responses
                              469 views
                              0 likes
                              Last Post tradingnasdaqprueba  
                              Started by Christopher_R, Today, 12:29 AM
                              0 responses
                              10 views
                              0 likes
                              Last Post Christopher_R  
                              Started by sidlercom80, 10-28-2023, 08:49 AM
                              166 responses
                              2,237 views
                              0 likes
                              Last Post sidlercom80  
                              Started by thread, Yesterday, 11:58 PM
                              0 responses
                              4 views
                              0 likes
                              Last Post thread
                              by thread
                               
                              Working...
                              X