Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Index was outside the bounds of the array

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

    Index was outside the bounds of the array

    I understand what this error means but i cant figure out what it causes it
    Error on calling 'OnBarUpdate' method on bar 5: Index was outside the bounds of the array.
    All was working fine until i setup enum and switch in my strategy. I cant figure out why its throwing outside the bounds of array error. I added 1 tick data for more accurate backtesting

    private RiskRewardRatio riskReward = RiskRewardRatio.OneToOne;
    protected override void OnBarUpdate()
    {
    if (CurrentBars[0] <= BarsRequiredToTrade || CurrentBars[1] <= BarsRequiredToTrade )
    return;

    double longBarSizeTicks = Math.Abs(Close[1] - Low[1]) / TickSize;
    double shortBarSizeTIcks = Math.Abs(High[1] - Close[1]) / TickSize;
    double rr1to1 = longBarSizeTicks;
    double rr1to2 = longBarSizeTicks * 2;​

    switch (riskReward)
    {

    case RiskRewardRatio.OneToOne:
    {

    Value[0] = rr1to1;
    break;
    }


    case RiskRewardRatio.OneToTwo:
    {
    Value[0] = rr1to2;
    break;
    }

    }

    [NinjaScriptProperty]
    [Display(GroupName = "04. Order Management", Order = 12, Description="04. Order Management")]
    public RiskRewardRatio RiskReward
    {
    get { return riskReward; }
    set { riskReward = value; }
    }​

    public enum RiskRewardRatio
    {
    OneToOne,
    OneToTwo,

    }​​​
    Last edited by tkaboris; 07-10-2023, 06:51 AM.

    #2
    Hello tkaboris,

    Thanks for your post.

    When working with any issue, it is important to take steps to isolate the issue so that the exact line causing the behavior can be found. This is a process of elimination and a process of debugging by adding prints.

    You could start by commenting out sections of code in the script, recompiling, and testing to see if the error persists. Once you see the error stop appearing, you could debug the script further by reducing code and adding prints that print out the indexes you are accessing in the script and the CurrentBars[0]/CurrentBars[1] values to isolate the exact line of code causing the error in the strategy.

    Note that you need to make sure that any index you are accessing in the script is less than the CurrentBars[0] and CurrentBars[1] values.

    Here is a reference sample about creating a user-defined enum parameter type: https://ninjatrader.com/support/help...ned_parame.htm

    Below is a link to a forum post that demonstrates how to use prints to understand behavior.
    https://ninjatrader.com/support/foru...121#post791121
    Last edited by NinjaTrader_BrandonH; 07-09-2023, 08:24 PM.
    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment


      #3
      HI I followed an example for enum using universalmovinageaverage example and I isolated switch statement and if i comment out switch statement my strategy works. The issue is somewhere in swithch statemenet and maybe i am referencing it the wrong way somehow?

      Comment


        #4
        Hello tkaboris,

        Thanks for your notes.

        I have attached a simple example script that uses an enum and switch() that you could view to see how this would be set up in NinjaScript.

        That said, using switch() is a C# concept, not NinjaScript-specific code, and we do not provide C# education services in our support.

        You could do a quick Google search for something like 'C# switch() enum' to research the topic to understand how to use switch in C# with enums.
        Attached Files
        <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

        Comment


          #5
          can you provide a source code?

          Comment


            #6
            Hello tkaboris,

            Thanks for your note.

            You could view the RiskRewardEnumSwitchExample script attached to my previous post to see how this is done.

            I have also attached the example script to this post as well.

            Attached Files
            <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

            Comment


              #7
              Thank you, i am still getting error index out of bound,
              Error on calling 'OnBarUpdate' method on bar 21: Index was outside the bounds of the array.
              it maybe because i added 1 tick data for backtesting and there needs to be additional validations?
              BarsRequiredToTrade = 20;

              protected override void OnBarUpdate()
              {

              if (CurrentBars[0] <= BarsRequiredToTrade || CurrentBars[1] <= BarsRequiredToTrade )
              return;​

              else if (State == State.Configure)
              {
              Calculate = Calculate.OnPriceChange;
              AddDataSeries(Data.BarsPeriodType.Tick, 1);

              }​​

              Comment


                #8
                Since i am using strategy not indicactor I dont need plot
                so i commented out these lines and it gives me that out of bound error. If i keep it in the strategy it gets enabled ok but messes up my chart.
                AddPlot(Brushes.Orange, "Plot1");
                and
                [Browsable(false)]
                [XmlIgnore]
                public Series<double> Plot1
                {
                get { return Values[0]; }
                }​

                Comment


                  #9
                  Hello tkaboris,

                  Thanks for your notes.

                  Value[0] = rr1to1; and Value[0] = rr1to2; would be used to assign those values to a plot that is added in the strategy depending on which case is used in the switch(). The sample code on the AddPlot() help guide page demonstrates this.

                  AddPlot(): https://ninjatrader.com/support/help...t8/addplot.htm

                  What exactly are you trying to assign the rr1to1 and rr1to2 values to in your script if you are not plotting them?

                  You could remove those lines of code from the script and add a print to the script within those cases to test that the strategy switch() works. Prints will appear in a New > NinjaScript Output window.

                  I have attached an example strategy script demonstrating how this would look with an added data series.

                  Note that in the sample indicator script I shared, AddPlot() and the Plot1 property should not be commented out since a value is being assigned to a plot in the script. Removing these will cause a compile error.​
                  Attached Files
                  Last edited by NinjaTrader_BrandonH; 07-10-2023, 10:08 AM.
                  <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                  Comment


                    #10
                    Thank you I should have said it beforehand what i wanted to accoplish
                    With above script i am getting
                    Error on calling 'OnBarUpdate' method on bar -1: You are accessing an index with a value that is invalid since it is out-of-range.

                    I want the user to select OneToOne or OneToTwo as an exity strategy, And in my strategy have something like this

                    else if (UseRiskReward)
                    {
                    if(stopLong <= bid){
                    ExitLongStopMarket(1, true, Position.Quantity, stopLong, "SLL", "StochFL");
                    ExitLongLimit(1, true, Position.Quantity, Position.AveragePrice + OneToOne, "PTL", "StochFL");
                    }
                    }​

                    Comment


                      #11
                      Hello tkaboris,

                      Thanks for your notes.

                      The error message was being caused because you were using Value[0] in the script but there was no plot added to the script to assign a value to.

                      The RiskRewardEnumSwitchStrategy example script I shared in post # 9 demonstrates that if you remove the lines of code that calls Value[0] = rr1to1 and Value[0] = 1to2; and instead add a print, the switch() works.

                      You could consider creating bool variables and setting the bools to true or false depending on the switch() case chosen. Then, create a condition in the script that checks if the bool is true and call your Exit order methods.

                      Note that it would ultimately be up to you to come up with the custom logic to accomplish your specific goal.
                      <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                      Comment


                        #12
                        Thats the thing, I recoded your last version, without plots and with Print statements and i am getting that Error on calling 'OnBarUpdate' method on bar -1: You are accessing an index with a value that is invalid since it is out-of-range. So i am getting this message after removing plots.. I dont understand
                        Attached Files

                        Comment


                          #13
                          Hello tkaboris,

                          Thanks for your notes.

                          To clarify, are you talking about the RiskRewardEnumSwitchExample script on post # 6 or the RiskRewardEnumSwitchStrategy script on post # 9?

                          The RiskRewardEnumSwitchStrategy example script I shared in post # 9 does not contain any plots and does contain an added 1-tick data series. This script is printing to the NinjaScript Output window without errors when testing it on my end.

                          See this demonstration video: https://brandonh-ninjatrader.tinytak...OF8yMTcyMzQ4NA

                          Please test the RiskRewardEnumSwitchStrategy attached on post # 9.


                          That said, in the stockstr.cs script you shared, I see you are setting Calculate to OnPriceChange in State.SetDefaults and in State.Configure. Calculate should only be set in State.SetDefaults. Remove Calculate = Calculate.OnPriceChange from State.Configure.

                          Calculate: https://ninjatrader.com/support/help.../calculate.htm

                          Ultimately, if the error is still occurring you would need to compare the RiskRewardEnumSwitchStrategy script to your strategy to see where differences might be. And, you would need to further debug your custom strategy by reducing code and adding debugging prints to find the exact line of code in your script that is causing the error to occur.

                          Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                          https://ninjatrader.com/support/foru...121#post791121

                          Note that we do not provide debugging services in our support as is it against our policy.
                          <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                          Comment


                            #14
                            Hi I have copied your example with enum from post9 and implemented it in my strategy and it works.

                            However, i went on and added enum for period bar selection, where user can select which type higher timeframe(tick or minute) to use and now i am getting. With this ENUM does the script sees 3 or 4 dataseries? (primary, tick, tickPeriodValue, minutePeriodvalue). User selects either or, not both
                            Error on calling 'OnBarUpdate' method on bar 0: Index was outside the bounds of the array. What can i do to fix it?

                            if (CurrentBars[0] < 15 && CurrentBars[1] < 15 || CurrentBars[2] < 15)
                            return;​

                            else if (State == State.Configure)
                            {
                            AddDataSeries(Data.BarsPeriodType.Tick, 1);
                            if(HigherTimeFrame)
                            {
                            if(tick)
                            {
                            AddDataSeries(Data.BarsPeriodType.Tick, PeriodValue);
                            }
                            if(minute)
                            {
                            AddDataSeries(Data.BarsPeriodType.Minute, PeriodValue);
                            }
                            }​
                            Last edited by tkaboris; 07-17-2023, 08:21 AM.

                            Comment


                              #15
                              Hello tkaboris,

                              Thanks for your notes.

                              AddDataSeries should not be added to a script dynamically and should be hardcoded. It should not be added depending on certain conditions either.

                              From the help guide: "Arguments supplied to AddDataSeries() should be hardcoded and NOT dependent on run-time variables which cannot be reliably obtained during State.Configure (e.g., Instrument, Bars, or user input). Attempting to add a data series dynamically is NOT guaranteed and therefore should be avoided. Trying to load bars dynamically may result in an error​"

                              This means that you must hardcode the period into the AddDataSeries() method instead of using PeriodValue and you should not add one series or the other based on a variable condition.

                              See this help guide page for more information about AddDataSeries(): https://ninjatrader.com/support/help...dataseries.htm

                              Further, you should add debugging prints to the script that print out the indexes that you are accessing, such as CurrentBars[0], CurrentBars[1], and CurrentBars[2].

                              Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                              https://ninjatrader.com/support/foru...121#post791121
                              <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              81 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              150 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              79 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              52 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              59 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X