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

Higher Timeframe moving Average indicator

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

    Higher Timeframe moving Average indicator

    Hi there:

    I tried to write an indicator which plots a 25-hourly SMA and a 8-daily EMA on any lower timeframe chart. This is what I came up with, but for whatever reasons nothing is showing up on the chart

    Code:
    namespace NinjaTrader.NinjaScript.Indicators
    {
    	public class AbcMovAvg : Indicator
    	{
    		protected override void OnStateChange()
    		{
    			if (State == State.SetDefaults)
    			{
    				Description									= @"Plot the 25 hourly SMA and the 8 daily EMA on any chart";
    				Name										= "AbcMovAvg";
    				Calculate									= Calculate.OnBarClose;
    				IsOverlay									= false;
    				DisplayInDataBox							= true;
    				DrawOnPricePanel							= true;
    				DrawHorizontalGridLines						= true;
    				DrawVerticalGridLines						= true;
    				PaintPriceMarkers							= true;
    				ScaleJustification							= NinjaTrader.Gui.Chart.ScaleJustification.Right;
    				//Disable this property if your indicator requires custom values that cumulate with each new market data event. 
    				//See Help Guide for additional information.
    				IsSuspendedWhileInactive					= true;
    			}
    			else if (State == State.Configure)
    			{
    				AddDataSeries(Data.BarsPeriodType.Minute, 60);
    				AddDataSeries(Data.BarsPeriodType.Day, 1);
    				AddPlot(Brushes.HotPink, "MovAvg1");
    				AddPlot(Brushes.Blue, "MovAvg2");
    			}
    		}
    
    		protected override void OnBarUpdate()
    		{
    			// Ensures that the plot is drawn on the primary data series
                if (BarsInProgress == 0)
                {
    				double d_MA1 = SMA(BarsArray[1], 25)[0];
    				double d_MA2 = EMA(BarsArray[2],  8)[0];
    				MovAvg1[0] = d_MA1;
    				MovAvg2[0] = d_MA2;
                }
    		}
    
    		#region Properties
    
    		[Browsable(false)]
    		[XmlIgnore]
    		public Series<double> MovAvg1
    		{
    			get { return Values[0]; }
    		}
    
    		[Browsable(false)]
    		[XmlIgnore]
    		public Series<double> MovAvg2
    		{
    			get { return Values[1]; }
    		}
    		#endregion
    
    	}
    }
    If someone could help fix this - I'd appreciate it - Thanx much

    #2
    Hello abctrader,

    Thanks for your post.

    As a general guide, when an indicator is not functioning normally you should check the "log" tab of the control center for any related error messages as this would be where you find run-time type errors.

    The likely issue is that you are not waiting until enough data is loaded before trying to calculate and plot.

    For example, if your chart bars are 15-minute bars, on the first 15-minute bar loaded you are trying to calculate the moving averages on data that has not loaded for the day bars and the 60 minute bar.

    You would need to use a check of the CurrentBars[] for each added bars array to ensure that an appropriate number of bars have loaded before trying to calculate. For example you are wanting to plot an 8 day EMA, for that to happen you would need to wait until 8 day bars had loaded.

    Please see the helpguide here: https://ninjatrader.com/support/help...urrentbars.htm
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Hello sir/madame,

      I'm having a similar issue.
      My script doesn't load enough data for the 10 months moving average to be calculated.

      here a snippet:

      else if (State == State.Configure)
      {
      AddDataSeries(BarsPeriodType.Tick,1);
      AddDataSeries(BarsPeriodType.Month,1);
      }

      ​ else if (State == State.DataLoaded)
      {

      // "BarsArray[1]" refers to the first data series added to the script with AddDataSeries.
      mySecondaryDoubleSeries = new Series<double>(BarsArray[2],MaximumBarsLookBack.Infinite);

      EMA200 = EMA(mySecondaryDoubleSeries,10); // 10months moving average​

      if (CurrentBars[0] < BarsRequiredToTrade || CurrentBars[1] < BarsRequiredToTrade || CurrentBars[2] <11) return;
      Print("CurrentBars[2]"+CurrentBars[2]);​

      The Print statement is never reached.
      So the script never loads 10 months of data.

      I tried putting maximum lookback period to infinite but nothing changes.

      Thank you.

      Comment


        #4
        Hello kreztmok,

        Thank you for your note.

        When testing this, what are your data series settings on the chart? Please provide a screenshot of your data series settings.
        • To send a screenshot with Windows 10 or newer I would recommend using the Windows Snipping Tool.
        • Alternatively to send a screenshot press Alt + PRINT SCREEN to take a screenshot of the selected window. Then go to Start--> Accessories--> Paint, and press CTRL + V to paste the image. Lastly, save it as a jpeg file and send the file as an attachment.
        ​I look forward to your reply.
        Emily C.NinjaTrader Customer Service

        Comment


          #5
          Hi Emily,

          I'm testing it in the Strategy Analyzer.
          First it worked but now i'm getting this error:
          “You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.”.
          i'm not able to catch the error on VS and have no idea where it is raised.

          I'm using 20 min timeframe with tick replay.
          I also tick as secondary series.

          Comment


            #6
            Originally posted by kreztmok View Post
            Hi Emily,

            I'm testing it in the Strategy Analyzer.
            First it worked but now i'm getting this error:
            “You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.”.
            i'm not able to catch the error on VS and have no idea where it is raised.

            I'm using 20 min timeframe with tick replay.
            I also tick as secondary series.
            Thank you for clarifying that this is in the Strategy Analyzer. In that case, I have some additional questions:
            • What version of NinjaTrader are you using? Please provide the entire version number. This can be found under Help -> About (Example: 8.?.?.?)
            • Who are you connected to? This is displayed in green in the lower-left corner of the Control Center window.
            • Are you connected to your data feed provider when running this test?
            • What instrument(s) (and expiry if applicable) have you selected?
            • What Data Series Type have you selected? Example: Tick, Minute, Day
            • What From and To date is selected?
            • If you open a chart for the same instrument(s) and the same date range, then right-click the chart and select 'Reload all historical data' is the historical data showing on the chart?
            The cause and ways to prevent the "index out of range" error may be found here:


            I look forward to your reply.
            Emily C.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_Emily View Post

              Thank you for clarifying that this is in the Strategy Analyzer. In that case, I have some additional questions:
              • What version of NinjaTrader are you using? Please provide the entire version number. This can be found under Help -> About (Example: 8.?.?.?)
                8.1.2.1 64-bit
              • Who are you connected to? This is displayed in green in the lower-left corner of the Control Center window.
                My Ninjatrader
              • Are you connected to your data feed provider when running this test?
                Yes
              • What instrument(s) (and expiry if applicable) have you selected?
                ESJUN24
              • What Data Series Type have you selected? Example: Tick, Minute, Day
                Minute
              • What From and To date is selected?
                Several, it works on certain dates and other it doesn't.
              • If you open a chart for the same instrument(s) and the same date range, then right-click the chart and select 'Reload all historical data' is the historical data showing on the chart?
                Yes
              The cause and ways to prevent the "index out of range" error may be found here:



              I look forward to your reply.

              Using this date, it seems to work as i get no errors in the log and a trade is executed:
              Click image for larger version

Name:	image.png
Views:	19
Size:	274.1 KB
ID:	1297374
              When using different date, i get the index out of range error and no trades are executed:

              Click image for larger version

Name:	image.png
Views:	16
Size:	249.5 KB
ID:	1297375

              Comment


                #8
                Hello kreztmok,

                Thank you for your reply.

                It seems there are two items to address here. First:
                if (CurrentBars[0] < BarsRequiredToTrade || CurrentBars[1] < BarsRequiredToTrade || CurrentBars[2] <11) return;
                Print("CurrentBars[2]"+CurrentBars[2]);​

                The Print statement is never reached.
                So the script never loads 10 months of data.​
                The print statement would not be reached unless at least 10 months of data is loaded based on your start date and end date range. In both screenshots, it seems you are loading data within the same months of March and February 2024, so it is expected that you are not reaching the 10 month minimum for the print statement to be hit.

                As for the index out of range error, I suggest adding a print every few lines of code to narrow down which part of your logic is resulting in the error. You can then see which is the last print to appear in the Output window before the error is thrown, signaling that the offending logic is somewhere below that print statement and before the next print statement. For more information on using prints and debugging:Please let us know if we may be of further assistance.
                Emily C.NinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by NinjaTrader_Emily View Post
                  Hello kreztmok,

                  Thank you for your reply.

                  It seems there are two items to address here. First:


                  The print statement would not be reached unless at least 10 months of data is loaded based on your start date and end date range. In both screenshots, it seems you are loading data within the same months of March and February 2024, so it is expected that you are not reaching the 10 month minimum for the print statement to be hit.

                  As for the index out of range error, I suggest adding a print every few lines of code to narrow down which part of your logic is resulting in the error. You can then see which is the last print to appear in the Output window before the error is thrown, signaling that the offending logic is somewhere below that print statement and before the next print statement. For more information on using prints and debugging:Please let us know if we may be of further assistance.

                  Thank you for response.

                  Isn't the max look back period meant to cope with enough loaded data?
                  So this means i cant do a 1 month test period?

                  Comment


                    #10
                    Hello kreztmok,

                    Thank you for your reply.

                    The MaximumBarsLookback determines how many data points from Series<T> objects are stored in memory for performance purposes. Setting it to 256 does not automatically load 256 bars worth of data, and setting it to infinite does not allow you infinite historical data points to look back on. That data still needs to be loaded historically if you intend to access it programmatically, and the range of data loaded is based on the start and end dates in the Strategy Analyzer. More information on MaximumBarsLookBack may be found here:


                    You could configure your logic so that it doesn't begin to evaluate until all of the desired data is loaded, then set your start and end dates to start as far back as data is needed and end one month after that data has been loaded if you'd like to test over 1 month with all of the necessary data loaded. Ultimately, I suggest adding additional print statements to better understand what data has and has not been loaded yet. Also, for more information about multi-series scripts I suggest reviewing the Multi Time Frame and Instruments page in the help guide. Here are those relevant links:Thank you for your time and patience.
                    Emily C.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by NRITV, Today, 01:15 PM
                    2 responses
                    6 views
                    0 likes
                    Last Post NRITV
                    by NRITV
                     
                    Started by frankthearm, Today, 09:08 AM
                    7 responses
                    31 views
                    0 likes
                    Last Post NinjaTrader_Clayton  
                    Started by maybeimnotrader, Yesterday, 05:46 PM
                    5 responses
                    25 views
                    0 likes
                    Last Post NinjaTrader_ChelseaB  
                    Started by quantismo, Yesterday, 05:13 PM
                    2 responses
                    19 views
                    0 likes
                    Last Post quantismo  
                    Started by adeelshahzad, Today, 03:54 AM
                    5 responses
                    33 views
                    0 likes
                    Last Post NinjaTrader_BrandonH  
                    Working...
                    X