Announcement

Collapse
No announcement yet.

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;
    		private int barsBack = 5;
    		private Color smaLineColor = Color.Orange;
    		#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(Color.Transparent, "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));
    			}
    			if(CurrentBar > barsBack)
    				DrawLine("HorizontalSMA", 0, Value[0], barsBack, Value[0], smaLineColor);
    		}
    		#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); }
    		}
    		[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); }
    		}
            #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:
        protectedoverride void OnBarUpdate() { if (CurrentBar > 14){ DrawHorizontalLine( "5BaragoSMALine" , SMA(14)[5 ], Color.Black); } }
        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:
            protectedoverride void OnBarUpdate() { if (CurrentBar > 14){ for (int i = 0; i < 5; i++) { DrawLine( "SMA" + i.ToString(), false , i + 1 , SMA( 14)[i + 1], i, SMA( 14 )[i], Color.Black, DashStyle.Solid, 1 );} } }
            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

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by twitch251, Today, 05:14 PM
                    0 responses
                    1 view
                    0 likes
                    Last Post twitch251  
                    Started by robforee2, Today, 05:07 PM
                    0 responses
                    1 view
                    0 likes
                    Last Post robforee2  
                    Started by blar58, Today, 03:16 PM
                    1 response
                    6 views
                    0 likes
                    Last Post NinjaTrader_Melissa  
                    Started by alcorr247, Today, 02:52 PM
                    2 responses
                    7 views
                    0 likes
                    Last Post robforee2  
                    Started by Radano, Today, 02:30 PM
                    1 response
                    4 views
                    0 likes
                    Last Post NinjaTrader_ChrisL  
                    Working...
                    X