Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Common out of range error

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

    Common out of range error

    Note: Moderators I'm not expecting ya'll to chime in on this as I suspect it's out of scope for what you do. If you do, great , if not I understand...

    I found this pullback indicator code and it does a fine job. In attempting to incorporate it into a strat the following error codes are generated and it kicks out.

    (Strategy)

    1) Error on calling 'OnBarUpdate' method on bar [xxx] You are accessing an index with a value that is invalid since it is out of range I.E. accessing a series [bars ago] with a value of 5 when there are only 4 bars on the chart.

    (Indicator)

    2) Indicator NLegPullback: Error on calling 'OnBarUpdate' method on bar 21: Object reference not set to an instance of an object.

    Overall problem is [I believe] self-evident due to the swing component

    The explanation of what is going on is found here:

    https://ninjacoding.net/ninjatrader/blog/multioutofarray

    I've done my best to apply the suggested syntax in what I thought was an appropriate manner and am running into brick walls.

    The code files are attached, and displayed below here as well... Anyone ??

    ************************************************** ************************************************** ************************************************** ************************************************** ************

    namespace NinjaTrader.NinjaScript.Indicators
    {
    public class NLegPullback : Indicator
    {
    enum Side
    {
    Long,
    Short
    }

    private int updown = 0;
    private int pullbackId = 1;
    private double legCount = 0;
    private EMA ema20;
    private EMA ema50;
    private Swing swing;
    private double highest;
    private double lowest = Double.MaxValue;
    private int legStartBar = 0;
    private double legStartPrice;
    private Side side;
    private String startLegTag = "";

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Detects n-legs pullbacks either on the long or short side and visualizes the leg counts and wires them together";
    Name = "NLegPullback";
    Calculate = Calculate.OnBarClose;
    IsOverlay = true;
    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;
    Strict = true;




    }
    else if (State == State.DataLoaded)
    {
    this.ema20 = EMA(20);
    this.ema50 = EMA(50);
    this.swing = Swing(5);
    }
    }

    private void endLegLong(String reason)
    {

    if (legStartBar < CurrentBar-1 && legCount>1)
    {
    if (legCount % 2 == 1)
    {
    Draw.Text(this, "pbt" + Time[0].ToString(), "X", 0, Low[0] - TickSize * 2, ChartControl.Properties.ChartText);



    Draw.Line(this, "pbl" + pullbackId + "_" + legCount, true, CurrentBar - legStartBar, legStartPrice, 0, Low[0], Brushes.Purple, DashStyleHelper.Dot, 2);
    }
    else
    {
    Draw.Text(this, "pbt" + Time[0].ToString(), "X", 0, High[0] + TickSize * 2, ChartControl.Properties.ChartText);
    Draw.Line(this, "pbl" + pullbackId + "_" + legCount, true, CurrentBar - legStartBar, legStartPrice, 0, High[0], Brushes.Purple, DashStyleHelper.Dot, 2);
    }
    }
    else if (legCount == 1) {
    RemoveDrawObject(startLegTag);
    }
    legCount = 0;


    pullbackId++;
    }

    private void endLegShort(String reason)
    {

    if (legStartBar < CurrentBar - 1 && legCount>1)
    {
    if (legCount % 2 == 0)
    {
    Draw.Text(this, "pbt" + Time[0].ToString(), "X", 0, Low[0] - TickSize * 2, ChartControl.Properties.ChartText);
    Draw.Line(this, "pbl" + pullbackId + "_" + legCount, true, CurrentBar - legStartBar, legStartPrice, 0, Low[0], Brushes.Purple, DashStyleHelper.Dot, 2);
    }
    else
    {
    Draw.Text(this, "pbt" + Time[0].ToString(), "X", 0, High[0] + TickSize * 2, ChartControl.Properties.ChartText);
    Draw.Line(this, "pbl" + pullbackId + "_" + legCount, true, CurrentBar - legStartBar, legStartPrice, 0, High[0], Brushes.Purple, DashStyleHelper.Dot, 2);
    }
    }
    else if (legCount == 1) {
    RemoveDrawObject(startLegTag);
    }
    legCount = 0;




    pullbackId++;
    }

    protected override void OnBarUpdate()
    {
    if (CurrentBar > 20)
    {
    if (legCount == 0)
    {
    if (ema20[0] > ema50[0] && Low[0] > ema20[0])
    {
    if (High[0] > swing.SwingHigh[1])
    {
    side = Side.Long;
    updown = -1;
    int highBar = 0;
    int lowBar = 0;
    if (High[0] < High[1])
    {
    highBar = 1;
    }
    startLegTag = "pbt" + Time[highBar].ToString();
    //Draw.Diamond(this, "pbd" + pullbackId+"_"+legCount, true, Time[highBar], High[highBar] + TickSize, Brushes.Red);
    Draw.Text(this, startLegTag, "0", highBar, High[highBar] + TickSize * 2, ChartControl.Properties.ChartText);

    highest = High[highBar];
    lowest = Double.MaxValue;

    legStartBar = CurrentBar - highBar;
    legStartPrice = High[highBar];

    legCount++;


    }
    }
    else if (ema20[0] < ema50[0] && High[0] < ema20[0])
    {
    if (Low[0] < swing.SwingLow[1])
    {
    side = Side.Short;
    updown = 1;
    int highBar = 0;
    int lowBar = 0;
    if (Low[1] < Low[0])
    {
    lowBar = 0;
    }
    startLegTag = "pbt" + Time[lowBar].ToString();
    //Draw.Diamond(this, "pbd" + pullbackId+"_"+legCount, true, Time[highBar], High[highBar] + TickSize, Brushes.Red);
    Draw.Text(this, startLegTag, "0", lowBar, Low[lowBar] - TickSize * 2, ChartControl.Properties.ChartText);

    highest = 0;
    lowest = Low[lowBar];

    legStartBar = CurrentBar - lowBar;
    legStartPrice = Low[lowBar];

    legCount++;



    }
    }
    }
    else
    {

    if (side == Side.Long)
    {
    if (High[0] > highest)
    {
    endLegLong("X0");
    return;
    }
    if (updown == -1 && High[0] > High[1])
    {

    int lowBar = 1;

    if (legStartBar < CurrentBar - lowBar)
    {
    if (Low[0]>lowest && Strict)
    {
    endLegLong("X1");
    return;
    }

    updown = 1;

    //Draw.Diamond(this, "pbd" + pullbackId + "_" + legCount, true, Time[lowBar], Low[lowBar] - TickSize, Brushes.Red);
    Draw.Text(this, "pbt" + Time[lowBar].ToString(), ""+legCount, lowBar, Low[lowBar] - TickSize * 2, ChartControl.Properties.ChartText);
    lowest = Low[lowBar];

    Draw.Line(this, "pbl" + pullbackId + "_" + legCount, false, CurrentBar - legStartBar, legStartPrice, lowBar, Low[lowBar], Brushes.Purple, DashStyleHelper.Dot, 2);
    legStartBar = CurrentBar - lowBar;
    legStartPrice = Low[lowBar];

    legCount++;



    }
    }
    else if (updown == 1 && Low[0] < Low[1])
    {
    updown = -1;
    int highBar = 1;
    //Draw.Diamond(this, "pbd" + pullbackId + "_" + legCount, true, Time[highBar], High[highBar] + TickSize, Brushes.Red);
    Draw.Text(this, "pbt" + Time[highBar].ToString(), ""+legCount, highBar, High[highBar] + TickSize * 2, ChartControl.Properties.ChartText);
    highest = High[highBar];

    Draw.Line(this, "pbl" + pullbackId + "_" + legCount, false, CurrentBar - legStartBar, legStartPrice, highBar, High[highBar], Brushes.Purple, DashStyleHelper.Dot, 2);
    legStartBar = CurrentBar - highBar;
    legStartPrice = High[highBar];

    legCount++;



    }

    }
    else if (side == Side.Short)
    {
    if (Low[0] < lowest)
    {
    endLegShort("X0");
    return;
    }
    if (updown == 1 && Low[0] < Low[1])
    {

    int highBar = 1;

    if (legStartBar < CurrentBar - highBar)
    {
    updown = -1;

    if (High[0] < highest && Strict)
    {
    endLegShort("X1");
    return;
    }

    //Draw.Diamond(this, "pbd" + pullbackId + "_" + legCount, true, Time[lowBar], Low[lowBar] - TickSize, Brushes.Red);
    Draw.Text(this, "pbt" + Time[0].ToString(), "" + legCount, highBar, High[highBar] + TickSize * 2, ChartControl.Properties.ChartText);
    highest = High[highBar];

    Draw.Line(this, "pbl" + pullbackId + "_" + legCount, false, CurrentBar - legStartBar, legStartPrice, highBar, High[highBar], Brushes.Purple, DashStyleHelper.Dot, 2);
    legStartBar = CurrentBar - highBar;
    legStartPrice = High[highBar];

    legCount++;



    }
    }
    else if (updown == -1 && High[0] > High[1])
    {
    updown = 1;
    int lowBar = 1;
    //Draw.Diamond(this, "pbd" + pullbackId + "_" + legCount, true, Time[highBar], High[highBar] + TickSize, Brushes.Red);
    Draw.Text(this, "pbt" + Time[0].ToString(), "" + legCount, lowBar, Low[lowBar] - TickSize * 2, ChartControl.Properties.ChartText);
    lowest = Low[lowBar];

    Draw.Line(this, "pbl" + pullbackId + "_" + legCount, false, CurrentBar - legStartBar, legStartPrice, lowBar, Low[lowBar], Brushes.Purple, DashStyleHelper.Dot, 2);
    legStartBar = CurrentBar - lowBar;
    legStartPrice = Low[lowBar];

    legCount++;



    }

    }
    }

    }

    }

    #region Properties
    [NinjaScriptProperty]
    [Display(Name="Strict", Description="Terminate pullback as soon as low/high pivot is not adhering the Z-shape", Order=1, GroupName="Parameters")]
    public bool Strict
    { get; set; }










    #endregion

    }
    }

    Attached Files

    #2
    Hello johnMoss,

    Thank you for your inquiry.

    Not all indicators have values exposed that could be used in a strategy. This indicator does not expose any plots or variables publicly that you'd be able to access via a bars ago index. So if you tried to call it in a strategy like:

    NBarPullback(true)[0];

    You'd get a reference error because there are no plots for it to be referencing.

    You could certainly look at adding transparent plots and exposing those so they might be referenced in a strategy, though.

    Please let us know if we may be of further assistance to you.

    Comment


      #3
      Hi Kate thank you for your reply. I actually did add the plots and they work just fine, I took them out here just to simplify things for the moment. What I gather the issue is an execution error due to the swing value being called when its object value is not complete in the OnBarUpdate method used?

      Comment


        #4
        Hello johnMoss,

        Thank you for your reply.

        Without seeing the modified indicator and the strategy code I couldn't say for sure, but this is usually seen when you're checking X number of bars back for a value, but the strategy has not yet processed enough bars to look back that far.

        For example, let's say in the strategy I want to check whether the current price is greater than the Close of 5 bars ago. If I try to check that before 5 bars have processed on the chart, I will get an indexing error.

        To avoid this, I would need to avoid processing my logic until the number of bars that is equal to the longest lookback period I would need to check have been processed.

        So I would get an error if I had the following:

        protected override void OnBarUpdate()
        {

        if (Close[0] > Close[5])
        {
        // do something
        }
        }


        But if I check to ensure that CurrentBar is greater than 5, I will avoid that indexing error:

        protected override void OnBarUpdate()
        {
        if (CurrentBar < 5)
        return;

        if (Close[0] > Close[5])
        {
        // do something
        }
        }

        That's the reason we see those errors the most often. These can also be seen if there is no saved value at that bar index and you try to access it.

        Please let us know if we may be of further assistance to you.

        Comment


          #5
          Thank you... Here attached is the indicator with plots added. They shouldn't affect the bar updates; yet bottom line is all I'm really wanting to do is capture the numbers generated on the chart as strings. i.e. 1,2, 3 etc... End of trend "X" I don't really need ... All additional code is marked

          [ /// jm /// ] on beginning and end.
          Attached Files
          Last edited by johnMoss; 05-17-2022, 04:43 PM.

          Comment


            #6
            Hello johnMoss,

            Thank you for your reply.

            After taking a look at this, you only need to assign LegCounts[0] once, right at the end of OnBarUpdate. I've created a simple strategy builder strategy that calls this and prints the current LegCounts value to the lower right corner of the chart and have included the revised indicator along with that - this should get you going in the correct direction.

            Please let us know if we may be of further assistance to you.
            Attached Files

            Comment


              #7
              Kate, thank you so very much. This is extraordinarily helpful in both achieving objective and furthering an understanding of ninjascript. You rock !

              Comment


                #8
                Well Phoohey on me Kate, I still am running into the same problem. I have tried a variety of configurations to the indicator and yet still run into the same problem. When trying to call it, a strategy will kick out, and the Log will still show the initial reason at the top of this thread. I have included a stripped down strat here and hoping you might identify the issue. Driving me up the wall, just can't seem to get around the lookback. Indicator works fine on chart, Databox reports values when non-transparent, just simply won't respond properly in a working strat. Thoughts? Thanx!

                P.S. For some odd reason the strat would not load here as .CS, so I had to Zip it...
                Attached Files

                Comment


                  #9
                  Hello johnMoss,

                  Thank you for your reply.

                  The issue is that you are calling the NBarPullback indicator but you're not adding that indicator to a chart. In the indicator it references ChartControl, which would only be available if the indicator is added to the chart:

                  Draw.Text(this, startLegTag, "0", lowBar, Low[lowBar] - TickSize * 2, ChartControl.Properties.ChartText);

                  Because the indicator doesn't check that ChartControl is not null before drawing the text, this causes an error. If you're not displaying the indicator on the chart, you can check for any references to ChartControl in the script and comment those lines out, and that should take care of the error. If you want it to draw the text to the chart and display the indicator from the strategy, check the box that says "Add to Chart" in the indicator parameters when it's used in a condition. That should add the indicator and allow it access to ChartControl so you avoid the error.

                  Please let us know if we may be of further assistance to you.

                  Comment


                    #10
                    Thank you Kate, I will implement and report back...

                    Comment


                      #11
                      Thank you Kate, That worked !

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                      0 responses
                      571 views
                      0 likes
                      Last Post Geovanny Suaza  
                      Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                      0 responses
                      331 views
                      1 like
                      Last Post Geovanny Suaza  
                      Started by Mindset, 02-09-2026, 11:44 AM
                      0 responses
                      101 views
                      0 likes
                      Last Post Mindset
                      by Mindset
                       
                      Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                      0 responses
                      549 views
                      1 like
                      Last Post Geovanny Suaza  
                      Started by RFrosty, 01-28-2026, 06:49 PM
                      0 responses
                      549 views
                      1 like
                      Last Post RFrosty
                      by RFrosty
                       
                      Working...
                      X