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

Calculculating spread between two SMA's

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

    Calculculating spread between two SMA's

    Im new to programming, and struggle to figure out the coding for this verry simple value.

    I want to get a indicator reading of the spread between a fast and a slow moving average. (FastSMA - SlowSMA).

    I realize this probably is a verry simple code, therfore I hope someone can point me in the right direction?

    #2
    Hello Europetrader,
    Thanks for your post and I am happy to assist you.
    Please use this code
    Code:
    double diff = SMA(13)[0] - SMA(34)[0];
    Please let me know if I can assist you any further.
    JoydeepNinjaTrader Customer Service

    Comment


      #3
      Thank you. I managed to render the code without getting any errors, but when I try it out in the chart it is blank (and the log doesnt show any errors)? I used the wizard to generate the SMA variables as I want to be able to change the averages easy.

      I have copied the code below. Appreciate it if you can take a look?

      Code:
      #region Using declarations
      using System;
      using System.ComponentModel;
      using System.Diagnostics;
      using System.Drawing;
      using System.Drawing.Drawing2D;
      using System.Xml.Serialization;
      using NinjaTrader.Cbi;
      using NinjaTrader.Data;
      using NinjaTrader.Gui.Chart;
      #endregion
      
      // This namespace holds all indicators and is required. Do not change it.
      namespace NinjaTrader.Indicator
      {
          /// <summary>
          /// Enter the description of your new custom indicator here
          /// </summary>
          [Description("Enter the description of your new custom indicator here")]
          public class TAZ : Indicator
          {
              #region Variables
              // Wizard generated variables
                  private int fastMA = 10; // Default setting for FastMA
                  private int slowMA = 40; // Default setting for SlowMA
              // 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()
              {
                  Add(new Plot(Color.FromKnownColor(KnownColor.Orange), PlotStyle.Line, "Plot0"));
                  Overlay				= false;
              }
      
              /// <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.
                  Double diff = (SMA(FastMA)[0] - SMA(SlowMA)[0]);
      		}
      
              #region Properties
              [Browsable(false)]	// this line prevents the data series from being displayed in the indicator properties dialog, do not remove
              [XmlIgnore()]		// this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
              public DataSeries Plot0
              {
                  get { return Values[0]; }
              }
      
              [Description("ma10")]
              [GridCategory("Parameters")]
              public int FastMA
              {
                  get { return fastMA; }
                  set { fastMA = Math.Max(1, value); }
              }
      
              [Description("ma40")]
              [GridCategory("Parameters")]
              public int SlowMA
              {
                  get { return slowMA; }
                  set { slowMA = Math.Max(1, 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 TAZ[] cacheTAZ = null;
      
              private static TAZ checkTAZ = new TAZ();
      
              /// <summary>
              /// Enter the description of your new custom indicator here
              /// </summary>
              /// <returns></returns>
              public TAZ TAZ(int fastMA, int slowMA)
              {
                  return TAZ(Input, fastMA, slowMA);
              }
      
              /// <summary>
              /// Enter the description of your new custom indicator here
              /// </summary>
              /// <returns></returns>
              public TAZ TAZ(Data.IDataSeries input, int fastMA, int slowMA)
              {
                  if (cacheTAZ != null)
                      for (int idx = 0; idx < cacheTAZ.Length; idx++)
                          if (cacheTAZ[idx].FastMA == fastMA && cacheTAZ[idx].SlowMA == slowMA && cacheTAZ[idx].EqualsInput(input))
                              return cacheTAZ[idx];
      
                  lock (checkTAZ)
                  {
                      checkTAZ.FastMA = fastMA;
                      fastMA = checkTAZ.FastMA;
                      checkTAZ.SlowMA = slowMA;
                      slowMA = checkTAZ.SlowMA;
      
                      if (cacheTAZ != null)
                          for (int idx = 0; idx < cacheTAZ.Length; idx++)
                              if (cacheTAZ[idx].FastMA == fastMA && cacheTAZ[idx].SlowMA == slowMA && cacheTAZ[idx].EqualsInput(input))
                                  return cacheTAZ[idx];
      
                      TAZ indicator = new TAZ();
                      indicator.BarsRequired = BarsRequired;
                      indicator.CalculateOnBarClose = CalculateOnBarClose;
      #if NT7
                      indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256;
                      indicator.MaximumBarsLookBack = MaximumBarsLookBack;
      #endif
                      indicator.Input = input;
                      indicator.FastMA = fastMA;
                      indicator.SlowMA = slowMA;
                      Indicators.Add(indicator);
                      indicator.SetUp();
      
                      TAZ[] tmp = new TAZ[cacheTAZ == null ? 1 : cacheTAZ.Length + 1];
                      if (cacheTAZ != null)
                          cacheTAZ.CopyTo(tmp, 0);
                      tmp[tmp.Length - 1] = indicator;
                      cacheTAZ = 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>
              /// Enter the description of your new custom indicator here
              /// </summary>
              /// <returns></returns>
              [Gui.Design.WizardCondition("Indicator")]
              public Indicator.TAZ TAZ(int fastMA, int slowMA)
              {
                  return _indicator.TAZ(Input, fastMA, slowMA);
              }
      
              /// <summary>
              /// Enter the description of your new custom indicator here
              /// </summary>
              /// <returns></returns>
              public Indicator.TAZ TAZ(Data.IDataSeries input, int fastMA, int slowMA)
              {
                  return _indicator.TAZ(input, fastMA, slowMA);
              }
          }
      }
      
      // This namespace holds all strategies and is required. Do not change it.
      namespace NinjaTrader.Strategy
      {
          public partial class Strategy : StrategyBase
          {
              /// <summary>
              /// Enter the description of your new custom indicator here
              /// </summary>
              /// <returns></returns>
              [Gui.Design.WizardCondition("Indicator")]
              public Indicator.TAZ TAZ(int fastMA, int slowMA)
              {
                  return _indicator.TAZ(Input, fastMA, slowMA);
              }
      
              /// <summary>
              /// Enter the description of your new custom indicator here
              /// </summary>
              /// <returns></returns>
              public Indicator.TAZ TAZ(Data.IDataSeries input, int fastMA, int slowMA)
              {
                  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.TAZ(input, fastMA, slowMA);
              }
          }
      }
      #endregion

      Comment


        #4
        This is your current code that handles the OnBarUpdate() event:
        Code:
                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.
                    Double diff = (SMA(FastMA)[0] - SMA(SlowMA)[0]);
                }
        It assigns your desired output to a double variable and does nothing else. To show it as a Plot, you need to set the Plot to the required value.

        Code:
        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.
                    Double diff = (SMA(FastMA)[0] - SMA(SlowMA)[0]);
                    [COLOR=Red][B]Plot0.Set(diff);[/B][/COLOR]
                }
        I would suggest that you probably want to work through the tutorials in the Help documentation. That way, you will better understand the structure and flow of coding NT indicators and strategies.

        I assure you that the piecemeal approach of trial-and-error, and asking specific questions and getting the resultant narrowly tailored answer, such as the one I give here, is much the slower process of trying to understand what is going on.

        Comment


          #5
          Thanks alot for the help. I will

          Comment


            #6
            Hello Eutopetrader,
            Please go through the Plot class to get more idea on how NinjaTrader draws a data series http://www.ninjatrader.com/support/h...plot_class.htm

            @ koganam - Thanks for the debug.
            JoydeepNinjaTrader Customer Service

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by cls71, Today, 04:45 AM
            0 responses
            1 view
            0 likes
            Last Post cls71
            by cls71
             
            Started by mjairg, 07-20-2023, 11:57 PM
            3 responses
            213 views
            1 like
            Last Post PaulMohn  
            Started by TheWhiteDragon, 01-21-2019, 12:44 PM
            4 responses
            544 views
            0 likes
            Last Post PaulMohn  
            Started by GLFX005, Today, 03:23 AM
            0 responses
            3 views
            0 likes
            Last Post GLFX005
            by GLFX005
             
            Started by XXtrader, Yesterday, 11:30 PM
            2 responses
            12 views
            0 likes
            Last Post XXtrader  
            Working...
            X