Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

"Error on calling 'OnStateChange' method: you are accessing an index

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

    "Error on calling 'OnStateChange' method: you are accessing an index

    Below is my code so far. If i change the buy order to just buy long, then i have no issues. If i have the buy order as market or limit or stop, then i get this same error.


    Error on calling 'OnStateChange' method: 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.



    Code:

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class Futures : Strategy
    {
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "Futures";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.UniqueEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    }
    else if (State == State.Configure)
    {
    SetStopLoss(@"", CalculationMode.Ticks, (Close[0] - 12) , false);
    SetProfitTarget("", CalculationMode.Ticks, (Close[0] + 4) );
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 2)
    return;

    // Set 1
    if ((Close[2] < Open[2])
    && (Close[1] > Open[1])
    && (Close[0] > Open[0]))
    {
    EnterLongStopMarket(Convert.ToInt32(DefaultQuantit y), 0, "");
    }

    }
    }
    }

    #2
    Did you create this in the strategy builder? It doesn't look like you set a stop price, or named the entry signal?
    Code:
    EnterLongStopMarket(Convert.ToInt32(DefaultQuantity), Close[0], @"EnterLong");
    That's what I created in strategy builder, similar to yours but put in Close[0] and @"EnterLong"

    Comment


      #3
      Hello tylermskala,

      Thanks for your post and welcome to the NinjaTrader forums!

      It appears you are using the Strategy Builder.

      In the Strategy Builder, you can only use the set method with a static value, for example SetStopLoss(CalculationMode.Ticks, 10); // 10 tick stop loss on every entry, regardless of direction.

      If you want to create a dynamic stop or profit, then as member MisterGee posted you would need to use other entry/exit methods, however, to use these other methods you need to know that they will be automatically canceled if not filled on the same bar they are entered on so you would need to create conditions that allow these orders to be resubmitted on each bar until they are filled or no longer needed.

      If you have not already reviewed the Strategy Builder resources:
      Free live webinar every other Thursday at 4:00 PM EST, through this link to all webinars: https://ninjatrader.com/PlatformTraining
      Previous recording of the Strategy Builder 301 webinar: https://youtu.be/HCyt90GAs9k?list=PL...auWXkWe0Nf&t=2
      Help guide for the strategy builder: https://ninjatrader.com/support/help...gy_builder.htm


      Alternately, to use the set method dynamically, you can unlock the strategy and work directly in Ninjascript to create what you wish. for example:

      if ((Close[2] < Open[2])
      && (Close[1] > Open[1])
      && (Close[0] > Open[0]))
      {
      SetStopLoss(@"", CalculationMode.Ticks, (Close[0] - 12) , false); // Must be set prior to the entry
      SetProfitTarget("", CalculationMode.Ticks, (Close[0] + 4) ); // Must be set prior to the entry
      EnterLongStopMarket(Convert.ToInt32(DefaultQuantit y), 0, "");
      }


      Comment


        #4
        Originally posted by tylermskala View Post
        else if (State == State.Configure)
        {
        SetStopLoss(@"", CalculationMode.Ticks, (Close[0] - 12) , false);
        SetProfitTarget("", CalculationMode.Ticks, (Close[0] + 4) );
        }
        I don't think any bars data is available yet, thus the Close data series is empty, so
        accessing the most recently closed bar (which doesn't exist yet) via index 0 produces
        the error you see.

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by NullPointStrategies, Today, 05:17 AM
        0 responses
        49 views
        0 likes
        Last Post NullPointStrategies  
        Started by argusthome, 03-08-2026, 10:06 AM
        0 responses
        126 views
        0 likes
        Last Post argusthome  
        Started by NabilKhattabi, 03-06-2026, 11:18 AM
        0 responses
        67 views
        0 likes
        Last Post NabilKhattabi  
        Started by Deep42, 03-06-2026, 12:28 AM
        0 responses
        42 views
        0 likes
        Last Post Deep42
        by Deep42
         
        Started by TheRealMorford, 03-05-2026, 06:15 PM
        0 responses
        46 views
        0 likes
        Last Post TheRealMorford  
        Working...
        X