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

Out of range exception calling EMA indicator

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

    Out of range exception calling EMA indicator

    Let me precede this by stating that I have coded in NinjaTrader for a decade and understand indexing of indicators very well. The problem I'm facing relates to a strategy that is calling an EMA and intermittently receives out or range exceptions. I kicked all the usual tires, making sure that I'm not calling it with a negative index or looking for values beyond the candle range.

    So from within my strategy I check for CurrentBars[x] for all my series and return before a safe distance.

    I also added the following to my strategy:

    if (CurrentBar < BarsRequiredToTrade { return; };

    Nevertheless I kept getting range exceptions and eventually made a copy of your EMA which I called EMA2 and added some debugging statements to it. This allows me to print more detailed debug information if there was an exception being thrown in onBarUpdate():

    Time Category Message 1/8/2021 12:30:09 PM NinjaScript
    "12/28/2020 6:02:00 PM: EMA2 during OnBarUpdate(): Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.ThrowHelper.ThrowArgumentOutOfRangeExceptio n(ExceptionArgument argument, ExceptionResource resource) at NinjaTrader.NinjaScript.Series`1.get_Item(Int32 barsAgo) at NinjaTrader.NinjaScript.Indicators.EMA2.OnBarUpdat e() in c:\Users\michael\Documents\NinjaTrader 8\bin\Custom\Indicators\EMA2.cs:line 80
    Bars period parsed during error: 2
    CurrentBar]: 5336
    Value[0] = 3808.17520499579
    Value[1] = 3808.22526356601

    What's really strange here is that this exception is being thrown intermittently several minutes or so after starting it. Look at the date of the exception - it's the very first bar on my chart. So it should have thrown this exception right on launch and not at some unspecified time later.

    Also see that it's happily printing Value[0] and Value[1] which I capture beforehand. So basically I have no idea WHY this is happening as it should not. The timing of the exception being thrown is wrong plus it clearly has enough bars.

    Heck I even added this to the beginning of my EMA2's onBarUpdate() method:

    if (CurrentBar < BarsRequiredToPlot { return; };

    And it's still throwing that error intermittently. Something's very screwy here and I've burned half my week on this already. Your help would be appreciated.

    Thanks,

    Michael
    Last edited by molecool; 01-08-2021, 11:53 AM.

    #2
    Hello molecool,

    Thank you for your post.

    What version of NinjaTrader are you currently running? You can find this under Help > About. The current version is 8.0.23.2 - if you're not on that version, please update and test:
    • First, copy your license key from NinjaTrader under Help> License Key then exit NinjaTrader
    • Click on the link: https://ninjatrader.com/PlatformDirect
    • Enter your license key and press Submit
    • Select 'NinjaTrader 8'
    • Select 'Download'
    • Critical: Before running the installer, ensure NinjaTrader is closed.

    To clarify, do you see this occur only on one particular instrument, or on all instruments?

    Are you using one of the built in bar types, or a custom bar type? What bar type and interval is this occurring on?

    Does this error occur when manually placing the built in EMA from the chart, or only when calling it from the strategy?

    Thanks in advance; I look forward to assisting you further.
    Kate W.NinjaTrader Customer Service

    Comment


      #3
      Hi Kate - that is the version I am running. Updated it in late December 2020.

      I am only testing with a 2-min chart of the ES 03-21.

      Comment


        #4
        Also internally I am using a 5-min and a 10-min series which call that EMA2. However the debug output suggests that this is happening with the 2-min chart per this print:

        Bars period parsed during error: 2

        Trust me I thought of that ;-)

        Finally it occurs when I use the indicator inside the strategy. Remember this all started with the original EMA indicator which is your code. The EMA2 is only a copy that adds additional debug routines, the formula in onBarUpdate() is the same.

        This is very confusing to me...

        Comment


          #5
          Hello molecool,

          Thank you for your replies.

          So that I can best attempt to reproduce, what are the parameters for the EMA you're calling in the strategy? Is it being calculated on the primary series or one of the secondary series? If you can provide a simplified example strategy that reproduces the error, that would be vey helpful.

          Thanks in advance; I look forward to assisting you further.
          Kate W.NinjaTrader Customer Service

          Comment


            #6
            Boy that would be very tough. It's a very complex strategy with over 9000 lines of code - and the EMA routines are buried somewhere in there. Let me work on that over the weekend and try to reproduce the issue with a test strategy on Monday. It only happens during live tape, so this will have to wait until the market opens on Sunday night.

            Comment


              #7
              Okay, so in leu of extracting the necessary routines into their own strategy I have added a bit more debugging code to my EMA2 indicator. Here's the current code which should give you an idea what I'm doing:

              Code:
              protected override void OnBarUpdate()
              
              {
              
              base.OnBarUpdate();
              
              
              
              if (IsFirstTickOfBar) clearPrintedList();
              
              StringBuilder info = new StringBuilder();
              
              try {
              
              if (CurrentBar < 2) {
              
              Value[0] = Input[0];
              
              } else {
              
              info.Append(Time[0] + " - CurrentBar]: " + CurrentBar).Append("\n");
              
              info.Append(Time[0] + "Input[0] = " + Input[0]).Append("\n"); // added this weekend
              
              info.Append(Time[0] + "Value[0] = " + Value[0]).Append("\n");
              
              info.Append(Time[1] + "Input[1] = " + Input[1]).Append("\n"); // added this weekend
              
              info.Append(Time[1] + "Value[1] = " + Value[1]).Append("\n");
              
              //PrintOnce(info.ToString());
              
              if (CurrentBar == 0) {
              
              Value[0] = Input[0];
              
              } else {
              
              double firstHalf = Input[0] * constant1;
              
              double secondHalf =  constant2 * Value[1];
              
              Value[0] = firstHalf + secondHalf;
              
              }
              
              //Value[0] = (CurrentBar == 0 ? Input[0] : Input[0] * constant1 + constant2 * Value[1]);
              
              }
              
              }  catch (Exception e) {
              
              StringBuilder error = new StringBuilder(Time[0] + ": EMA2 during OnBarUpdate():\n " + FlattenException(e));
              
              error.Append(String.Format("Bars period parsed during error: {0}-{0}", BarsPeriod.Value,  BarsPeriod.Value)).Append("\n");
              
              error.Append(info).Append("\n");
              
              Print(error.ToString(), PrintLevel.ERROR);
              
              Log(error.ToString(), LogLevel.Error);
              
              }
              
              }
              Everything else is the same as your EMA indicator, except that it inherits from an 'in between' parent class which in turn inherits from Indicator. Recall that the problem originated with EMA and not with EMA2, so it's that's not the issue here.

              Anyway, after reviewing some of the live debug output (I keep local log files that record all Exceptions in my indicators) something becomes apparent:

              12/28/2020 6:02:00 PM: EMA2 during OnBarUpdate(): Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.ThrowHelper.ThrowArgumentOutOfRangeExceptio n(ExceptionArgument argument, ExceptionResource resource) at NinjaTrader.NinjaScript.Series`1.get_Item(Int32 barsAgo) at NinjaTrader.NinjaScript.Indicators.EMA2.OnBarUpdat e() in c:\Users\michael\Documents\NinjaTrader 8\bin\Custom\Indicators\EMA2.cs:line 78 Bars period parsed during error: 2 1/8/2021 2:40:00 PM - CurrentBar]: 5400 1/8/2021 2:40:00 PMValue[0] = 3797.85610104169
              If you look at the code above you see that the debug output is supposed to print Value[0] and Value[1]. I have in interim added Input[0] and Input[1] as well and we'll get to that. Anyway, as you can see the output stops at Value[0] which is strange as I am checking for CurrentBars in there.

              Again, recall that I am using the EMA (and right now the EMA2) with three different input series:
              • 2-min (the one throwing the error)
              • 5-min
              • 10-min

              For some reason however it's always the 2-min that's causing this issue, which has the most data. It's possible that NinjaTrader gets confused somehow if there are several series involved in a strategy. After all EMA works fine just running in a regular chart.

              So, how to fix this?! As you can also see from the code - I have explicitly separated the calculation into several baby steps in order to capture the exact line number where this exception occurs, but I am willing to bet good money that it's at this one:

              double secondHalf = constant2 * Value[1];

              Since I don't want to spend any more time on this (it's already been days) can you perhaps help me find some way of duct taping this so that the error won't be thrown? The EMA seems to be working fine most of the time so if it skips a historic calculation I frankly do not care. So if we can check either the length of the input series or Value series I hope to be able to avoid this.

              Unfortunately it appears that Value.Length and Value.GetLength(0) are not working. Which is a bit strange as I assumed we're dealing with arrays.

              Anyway, I hope this makes sense and that you are able to suggest a way to fix this or at least a workaround.

              Thanks!
              Last edited by molecool; 01-10-2021, 11:48 AM.

              Comment


                #8
                Quick update - the market just opened on Sunday and the strategy threw the exception on the 2-min series (index 0):
                1/10/2021 6:00:15 PM NinjaScript 12/30/2020 6:02:00 PM: EMA2 during OnBarUpdate(): Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.ThrowHelper.ThrowArgumentOutOfRangeExceptio n(ExceptionArgument argument, ExceptionResource resource) at NinjaTrader.NinjaScript.Series`1.get_Item(Int32 barsAgo) at NinjaTrader.NinjaScript.Indicators.EMA2.OnBarUpdat e() in c:\Users\michael\Documents\NinjaTrader 8\bin\Custom\Indicators\EMA2.cs:line 82
                Bars period parsed during error: 2-2 12/30/2020 6:02:00 PM -
                CurrentBar]: 4098 12/30/2020 6:02:00 PM
                Input[0] = 3724.75 12/30/2020 6:02:00 PM
                Value[0] = 3724.75 12/30/2020 4:41:00 PM
                Input[1] = 3723.75
                So apparently both inputs are present but Value[1] is not.
                Last edited by molecool; 01-11-2021, 09:36 AM.

                Comment


                  #9
                  Hello molecool,

                  Thank you for your reply.

                  I haven't been able to reproduce the error on my end by just calling the built in EMA indicator from a basic strategy. Could you provide a simplified strategy that reproduces? Please export the simplified version from Export > NinjaScript Add-on. Do not check the box to export as a compiled assembly or we will be unable to review the code. Please attach the resulting .Zip file to your reply.

                  Thanks in advance; I look forward to assisting you further.
                  Kate W.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Kate - it's going to be a bit of work on my end to do that but I'll try to come up with something over the coming days.

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by WHICKED, Today, 12:56 PM
                    0 responses
                    2 views
                    0 likes
                    Last Post WHICKED
                    by WHICKED
                     
                    Started by Spiderbird, Today, 12:15 PM
                    2 responses
                    10 views
                    0 likes
                    Last Post Spiderbird  
                    Started by WHICKED, Today, 12:45 PM
                    0 responses
                    7 views
                    0 likes
                    Last Post WHICKED
                    by WHICKED
                     
                    Started by FrazMann, Today, 11:21 AM
                    2 responses
                    6 views
                    0 likes
                    Last Post NinjaTrader_ChristopherJ  
                    Started by rjbtrade1, 11-30-2023, 04:38 PM
                    2 responses
                    80 views
                    0 likes
                    Last Post DavidHP
                    by DavidHP
                     
                    Working...
                    X