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

Error: Index was outside the bounds of the array.

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

    Error: Index was outside the bounds of the array.

    Error on calling 'OnBarUpdate' method on bar 1771: Index was outside the bounds of the array

    Hi everyone!

    I've been working at this for a couple weeks now and can't seem to figure out what the issue is. I know it is something to do with the additional data series I am trying to incorporate into my strategy, I'm just not sure how to fix the issue, or why it's happening on bar 1771. I've tried looking at Ninjatraders Multi Time Frame page (https://ninjatrader.com/support/help...dataseries.htm), but the haven't been able to find a solution in there. I've been searching through these forums too and haven't found anything relating to this problem specifically. I could definitely be wrong about that though.

    Bellow is a simplified version of my code, but all of the important pieces are copy and pasted. I'm building it to work with ES futures.

    Any help will be greatly appreciated, and I look forward to hearing from some of you!



    private Series<double> barOverlap;
    private EMA ema;
    private SMA sma;
    private RSI rsi;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    IsInstantiatedOnEachOptimizationIteration = false;
    StartBehavior = StartBehavior.WaitUntilFlat;
    Calculate = Calculate.OnEachTick;
    EntryHandling = EntryHandling.UniqueEntries;
    EntriesPerDirection = 2;
    BarsRequiredToTrade = 30;
    }
    else if (State == State.Configure)
    {
    AddDataSeries("", new BarsPeriod { BarsPeriodType = BarsPeriodType.Tick, Value = 5000 }, 10, "", true);
    AddDataSeries("", new BarsPeriod { BarsPeriodType = BarsPeriodType.Tick, Value = 10000 }, 10, "", true);
    AddDataSeries("", new BarsPeriod { BarsPeriodType = BarsPeriodType.Day, Value = 1 }, 10, "", true);
    }
    else if (State == State.DataLoaded)
    {
    ema = EMA(20);
    rsi = RSI(14, 3);
    sma = SMA(240);
    AddChartIndicator(ema);
    AddChartIndicator(sma);

    // Passing in BarsArray[0](Primary Data Series) as an argument results in an empty Series with an identical number of index slots
    // Used later on in OnBarUpdate to store % that bar 1 is overlapping with bar 2
    barOverlap = new Series<double>(this);
    }
    }

    protected override void OnBarUpdate()
    {
    // KEEP TO PREVENT INITIAL OUT OF BOUNDS ERRORS
    if (CurrentBars[0] <= BarsRequiredToTrade || CurrentBars[1] <= 4 || CurrentBars[2] <= 4 || CurrentBars[3] < 2)
    return;
    if (BarsInProgress != 0)
    return;

    if (required conditions are met)
    {
    enter order
    }


    Thank you for your time!
    Kreyenhagen
    NinjaTrader Ecosystem Vendor - Tyche Trading

    #2
    Hello Kreyenhagen, thanks for your post and welcome to the NinjaTrader forum.

    I recommend you use Visual Studio debugging to attach Visual Studio to the NinjaTrader process. Please see the full guide here:

    https://ninjatrader.com/support/help..._debugging.htm

    After Visual Studio is attached to the NinjaTrader process, run your code and make it cause the error. Visual Studio will break at the exact line causing the issue.

    Also, make sure Visual Studio is set to break on Common Language Runtime exceptions. Here is a publicly available link:
    https://christianfindlay.com/2019/07...ll-exceptions/

    Please let me know if I can assist any further.
    Last edited by NinjaTrader_ChrisL; 03-01-2021, 04:21 PM.
    Chris L.NinjaTrader Customer Service

    Comment


      #3
      Hi Chris,

      Thank you so much for the quick response. Visual Studio was able to show me the troublesome code, I am just a little lost as to why it is giving me trouble. Bellow is a shorter version of what's giving me trouble. Is the issue that I am directly comparing prices from two separate data series, or is the issue related to the way I'm getting the values for the ema and trendline indicators, or is it something else I'm not seeing?

      The idea here being the strategy can use either the 20EMA, a custom trendline indicator, or the previous days high/low, for support/resistance.

      if (((Low[1] <= ema.Value[1] || Low[0] <= ema.Value[0]) && (High[1] >= ema.Value[1]))
      || ((Low[1] == trendline.Value[1] || Low[0] == trendline.Value[0]) && High[1] > trendline.Value[1])
      || ((Low[1] <= Lows[3][1] || Low[0] <= Lows[3][1]) && (High[1] >= Highs[3][1]))
      || ((Low[1] <= Highs[3][1] || Low[0] <= Highs[3][1]) && (High[1] >= Lows[3][1]))
      && (tlpb.SignalBarLevel[0] >= SignalBarStrength))
      {
      do the thing
      }
      Last edited by Kreyenhagen; 03-01-2021, 05:06 PM.
      Kreyenhagen
      NinjaTrader Ecosystem Vendor - Tyche Trading

      Comment


        #4
        Hello Kreyenhagen, thanks for your reply.

        I can not tell what it would be from the snippet. There's nothing wrong with comparing two prices from different series. Please comment out this condition completely and use Print() on each element then you will see which element it is failing at e.g.

        Print(Low[1]);
        Print(ema.Value[1]);
        Print(Low[0]);
        Print(ema.Value[0]);
        Print(High[1]);
        //... and so on

        Please let me know if I can assist any further.
        Chris L.NinjaTrader Customer Service

        Comment


          #5
          Hi Chris,

          found the issue! it was the custom trendline indicator.
          You all are wizards!

          Thank you so much!
          Kreyenhagen
          NinjaTrader Ecosystem Vendor - Tyche Trading

          Comment


            #6
            Hello Chris,

            I thought I'd try to add to this post as it seem(s)(ed) to give all the info I was looking for.. I've been able to code and debug an indicator using Visual Studio after choosing
            Debug in NT8.. (kind of a treat) I followed the post and directions from above.. (I had to choose .Net 5.0 because that's the version of VS I had). I saved the file
            in VS and it compiled in NT8.. but it still doesn't plot.. I'm getting an 'OnBarUpdate' method error in the "output window on bar 295 :
            "Object reference not set to an instance of an object"

            I built this to use a couple of momentum based indicators I have already been using with some others based on Delta... I think putting these two together would be interesting.

            I still get one message (no errors) related to calling the indicator an indicator : in VS but the severity comes up None..

            Severity Code Description Project File Line Suppression State
            Warning CS0436 The type 'Indicator' in 'C:\Users\Chuck\Documents\NinjaTrader 8\bin\Custom\Indicators\@VOL.cs' conflicts with the imported type 'Indicator' in 'ETOFSv3NT302_64, Version=0.3.0.2, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\Users\Chuck\Documents\NinjaTrader 8\bin\Custom\Indicators\@VOL.cs'. NinjaTrader.Custom C:\Users\Chuck\Documents\NinjaTrader 8\bin\Custom\Indicators\MyCustomIndicator6.cs 27 Active

            So here's the code: The indicators used are working fine and have for days now..

            //This namespace holds Indicators in this folder and is required. Do not change it.
            namespace NinjaTrader.NinjaScript.Indicators
            {
            public class VrVVr : Indicator
            {

            private readonly Series<double> VelROC;

            // public Series<double> VVROC;
            private readonly Series<double> VrVVrPlot;

            private readonly Series<double> JMA_Series;

            protected override void OnStateChange()
            {
            if (State == State.SetDefaults)
            {
            Description = @"Combined VRVVR indicator";
            Name = "VrVVr";
            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;
            P1VV = 1;
            P2VV = 0;
            P3VV = 1;
            P1V = 2;
            P2V = 0;
            P3V = 5;
            VEL_lenVV = 9;
            VEL_lenV = 8;
            Smooth = 5;
            Phase =100;
            Lag = 0;
            DynaColor_flag = 1 ;
            JMA_UpColor = Brushes.Cyan;
            JMA_DownColor = Brushes.Red;

            AddPlot(new Stroke(new SolidColorBrush(Colors.Cyan), 1), PlotStyle.Line, "VrVVrPlot");


            AddLine(Brushes.DarkMagenta, 50,"upper flat line");
            AddLine(Brushes.DarkMagenta, -50,"lower flat line");
            }

            if (State == State.Configure)
            {


            AddDataSeries(BarsPeriodType.Tick, 10);

            }
            // else if
            // (State == State.DataLoaded)



            }
            protected override void OnBarUpdate()
            {
            if (CurrentBars[0] < 100 || CurrentBars[1] < 100)
            return;

            if (BarsInProgress != 0)
            return;

            if (Close[0] > Close[Math.Min(CurrentBar, 300)])
            VVROC[0] = VELVROC(Close, VEL_lenVV,P1VV,P2VV,P3VV)[0];
            // Print("VVROC : "+VVROC);

            if (Close[0] > Close[Math.Min(CurrentBar, 300)])
            VelROC[0] = JRC_VELROC(BarsArray[1],VEL_lenV,P1V,P2V,P3V)[0];
            // Print("VROC : " +VROC);

            if (Close[0] > Close[Math.Min(CurrentBar, 300)])
            COMB[0] = (VVROC[0] + VelROC[0]) ;
            // Print( "COMB : " +COMB);

            if (Close[0] > Close[Math.Min(CurrentBar, 300)])
            VrVVrPlot[0] = COMB[0];
            // Print( "VrVVrPlot : " +VrVVrPlot);

            if (Close[0] > Close[Math.Min(CurrentBar, 300)])
            {
            JMA_Series[0] = VrVVrPlot[0] ;
            //Print( "JMA_Series : " +JMA_Series);
            if (DynaColor_flag == 1)
            {
            if (Close[0] > Close[Math.Min(CurrentBar, 300)] & JMA_Series[Lag] > JMA_Series[Lag+1])
            PlotBrushes[0][0] = JMA_UpColor ;
            else if
            (Close[0] > Close[Math.Min(CurrentBar, 300)] & JMA_Series[Lag] < JMA_Series[Lag+1])
            PlotBrushes[0][0] = JMA_DownColor ;
            else

            PlotBrushes[0][0] = Brushes.White ;

            }
            Values[0][0] = JMA_Series[Lag];
            }


            }



            #region Input Parameters

            [Browsable(false)]
            [XmlIgnore]
            public Series<double> COMB
            {
            get { return Values[0]; }
            }

            [Browsable(false)]
            [XmlIgnore]
            public Series<double> VVROC
            {
            get { return Values[0]; }
            }

            [Display(Name="VEL lenVV", Description="VEL lengthVV, any integer >= 3", Order=1, GroupName="NinjaScriptParameters")]
            [Range(3, 300), NinjaScriptProperty]
            public int VEL_lenVV
            { get; set; }

            [Display(Name="VEL lenVV", Description="VEL lengthV, any integer >= 3", Order=2, GroupName="NinjaScriptParameters")]
            [Range(3, 300), NinjaScriptProperty]
            public int VEL_lenV
            { get; set; }

            [Display(Name="P1VV_Length", Description="Lookback PeriodsP1VV : 1 ... 300", Order=3, GroupName="NinjaScriptParameters")]
            [Range(1, 300), NinjaScriptProperty]
            public int P1VV
            { get; set; }

            [Display(Name="P2VV", Description="Lookback PeriodsP2VV : -100 ... +100", Order=4, GroupName="NinjaScriptParameters")]
            [Range(-100, 100), NinjaScriptProperty]
            public int P2VV
            { get; set; }

            [Display(Name="P3VV", Description="Lookback PeriodsP3VV : -100 ... +100", Order=5, GroupName="NinjaScriptParameters")]
            [Range(-100,100), NinjaScriptProperty]
            public int P3VV
            { get; set; }

            [Display(Name="P1V", Description="Lookback PeriodsP1V VROC: 1 ... 300", Order=6, GroupName="NinjaScriptParameters")]
            [Range(1, 300), NinjaScriptProperty]
            public int P1V
            { get; set; }

            [Display(Name="P2V", Description="Lookback PeriodsP2V : -100 ... +100", Order=7, GroupName="NinjaScriptParameters")]
            [Range(-100, 100), NinjaScriptProperty]
            public int P2V
            { get; set; }

            [Display(Name="P3V", Description="Lookback PeriodsP3V : -100 ... +100", Order=8, GroupName="NinjaScriptParameters")]
            [Range(-100,100), NinjaScriptProperty]
            public int P3V
            { get; set; }

            [Display(Name="Smooth", Description="JMA smoothness: 1 ... 300", Order=9, GroupName="NinjaScriptParameters")]
            [Range(1, 300), NinjaScriptProperty]
            public double Smooth
            { get; set; }

            [Display(Name="Phase", Description="JMA phase: -100 ... +100", Order=10, GroupName="NinjaScriptParameters")]
            [Range(-100, 100), NinjaScriptProperty]
            public double Phase
            { get; set; }

            [Display(Name="Delay", Description="Shift right. Any integer >= 0", Order=11, GroupName="NinjaScriptParameters")]
            [Range(0,200), NinjaScriptProperty]
            public int Lag

            { get; set; }
            [Display(Name="DynaColor", Description="0 = no 1 = yes", Order=12, GroupName="NinjaScriptParameters")]
            [Range(0,1)]
            public int DynaColor_flag
            { get; set; }

            [XmlIgnore()]
            [Display(Name="color_up", Description="JMA up color", Order=13, GroupName="Plots")]
            public Brush JMA_UpColor
            { get; set; }

            [XmlIgnore()]
            [Display(Name="color_down", Description="JMA down color", Order=14, GroupName="Plots")]
            public Brush JMA_DownColor
            { get; set; }

            [Browsable(false)]
            public string JMA_UpColor_Serialize
            {
            get { return Serialize.BrushToString(JMA_UpColor); }
            set { JMA_UpColor = Serialize.StringToBrush(value); }
            }

            [Browsable(false)]
            public string JMA_DownColor_Serialize
            {
            get { return Serialize.BrushToString(JMA_DownColor); }
            set { JMA_DownColor = Serialize.StringToBrush(value); }
            }





            #endregion
            }
            }



            Any help would be greatly appreciated.. I'm new to this (only my indicator #6).. I'm not having any luck at this point - even with the patient support people..
            Its been Chelsea B who has been more than patient and very helpful..

            regards,



            Last edited by Chuck_63; 04-19-2021, 05:04 PM.

            Comment


              #7
              Hi Chuck_63, thanks for your post.

              The warnings that show up will always be there since we use reflection that can not be determined at compile-time, so we suppress warnings in the regular NinjaScript Editor.

              Best regards,
              -ChrisL
              Chris L.NinjaTrader Customer Service

              Comment


                #8
                For sure, no - the editor works well.. It was nice to use Visual Studio - I hadn't had a lot of luck with it before..
                Does anything jump out as to why this "Object reference not set to an instance of an object" error comes up as I change the start point?
                I'm not seeing it..

                cheers,

                Comment


                  #9
                  Hi Chuck_63, thanks for your reply.

                  You can use Visual Studio to attach to the NinjaTrader process and see exactly what line of your code has the uninitialized object. See here for instructions:

                  https://ninjatrader.com/support/help..._debugging.htm

                  Once you have attached it to the NinjaTrader.exe process, run your code to cause the exception and Visual Studio will break at the line causing it.

                  Kind regards,
                  -ChrisL
                  Chris L.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Chris, yes I did this yesterday.. I fixed the <10 bars problem today.. I also got rid of the "close" input and used theBarsArray[1] for both indicators... It compiles with no errors - but still doesn't plot..
                    There's a couple flat lines in the code that plot.. I don't know - I can't see the issue..

                    Comment


                      #11
                      Hi Chuck_63, thanks for your reply.

                      If you use Visual Studio for debugging (not for editing) you will see the exact line that is causing the unhandled exception. Did it break on the line where the uninitialized object is?

                      Best regards,
                      -ChrisL
                      Chris L.NinjaTrader Customer Service

                      Comment


                        #12
                        Hi Chris,

                        The results of the debug are that the code runs.. there are no errors, its just that there is no values for it to pick up.. I think its a design problem.
                        I came to this conclusion (or possibility) because I'm not certain that running these indicators will return the value(s) I want to add together.. There
                        are 4 plots in each (if you count the zero lines).. I've tried to comment out everything I don't want to plot, plus the calculations I don't need but I can't
                        get it to compile..

                        Is there a way to check what value an indicator is returning when we use it in a strategy or another indicator?

                        C

                        Comment


                          #13
                          Hi Chuck_63, thanks for your reply.

                          Is the strategy having an unhandled exception that keeps it from being enabled or is there a compilation error? You can use the Print() method to print out any data coming from the strategy, see here for documentation:

                          https://ninjatrader.com/support/help...nt8/?print.htm

                          Best regards,
                          -ChrisL
                          Chris L.NinjaTrader Customer Service

                          Comment


                            #14
                            Hi Chris,

                            There's no compilation errors in the log or output..

                            if (CurrentBars[0] < 100 || CurrentBars[1] < 100)
                            return;

                            if (BarsInProgress != 0)
                            return;

                            When I comment out the ( //if (BarsInProgress != 0) return; ) lines I get an "Error on calling 'OnBarUpdate' method on bar " ". Object reference not set to an instance of an object
                            The error would be on line 101 in the above case..

                            This is what makes me think there's nothing there to add together.. I need to check what the indicators are returning when called - somehow (and I don't know how)

                            Comment


                              #15
                              Hello, thanks for your reply.

                              You are adding all of these series objects but they are not being initalized in OnStateChanged in State.DataLoaded. See here for an example:

                              https://ninjatrader.com/support/help...8/?seriest.htm



                              Chris L.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by trilliantrader, Today, 03:01 PM
                              0 responses
                              2 views
                              0 likes
                              Last Post trilliantrader  
                              Started by pechtri, 06-22-2023, 02:31 AM
                              9 responses
                              122 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by frankthearm, 04-18-2024, 09:08 AM
                              16 responses
                              67 views
                              0 likes
                              Last Post NinjaTrader_Clayton  
                              Started by habeebft, Today, 01:18 PM
                              1 response
                              7 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by benmarkal, Today, 12:52 PM
                              2 responses
                              19 views
                              0 likes
                              Last Post benmarkal  
                              Working...
                              X