• If this is your first visit, you will have to register before you can post. To view messages, please scroll below and select the forum that you would like to visits. Questions? Be sure to check out the Forum FAQ.

Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Can't Access Times[1][0] in Indicator

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

    Can't Access Times[1][0] in Indicator

    Hello, I'm having some trouble developing an indicator to essentially backtest directly on the chart as an indicator and I'm having some problems with the Times[1][0] function.
    Error on calling 'OnBarUpdate' method for indicator 'ProfitLossDetector' on bar 20: Bar index needs to be greater/equal 0
    This error is thrown every time I try to call the Times function in or outside of the BarsInProgress, I need to be able to get the time for my indicator to work the way I want.

    Code:
            protected override void Initialize()
            {
                Overlay				= false;
    			Add(PeriodType.Tick, 1);
    			CalculateOnBarClose = false;
    			Add(new Plot(Color.FromKnownColor(KnownColor.Transparent), PlotStyle.Square, "EntryPrice"));
    			Add(new Plot(Color.FromKnownColor(KnownColor.Transparent), PlotStyle.Square, "ExitTime"));
    			Add(new Plot(Color.FromKnownColor(KnownColor.Red), PlotStyle.Line, "WinPercentage"));
    			addedTime = (10000 * hours) + (100 * minutes) + (1 * seconds);
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
    			if (BarsInProgress == 0)
    			{			
    				if (CurrentBar < 20) return;
    
              -------->          Print(ToTime(Times[1][0]));    <--------
    				
    				if (FirstTickOfBar
    					&& BarsInProgress == 0)
    				{
    					inTrade = false;
    					EntryPrice.Set(0);
    					ExitTime.Set(0);
    				}
    This is just a small snippet to show exactly where the problem is occurring.

    I've placed it everywhere in this program and it always throws the same exception.

    On a second note, Times[0][0] works for the primary data series, and Time[0] works for both of them if it's outside of if (BarsInProgress == 0).

    #2
    Hello,

    Thank you for the question.

    I tried the snippet you provided and received no errors.

    I wanted to confirm, can you pull up the tick chart for the instrument you are trying this on? If you see data after that try to reload the indicator to see if this was just caused by the script not having data.

    If that is not the case, can you could provide a working example that displays the error along with the instrument you are trying this on so I could re produce this?

    I look forward to being of further assistance.
    JesseNinjaTrader Customer Service

    Comment


      #3
      Thank you for the reply. It's definitely not my code. I was messing around with it trying to figure out why this was happening and went as far as deleting everything except the Times[1][0]; from a dummy program. This was the result.

      Code:
          [Description("Detect the Profits and Losses you would accumulate like with a backtest.")]
          public class TimesTest : Indicator
          {
              #region Variables
              // Wizard generated variables
              // User defined variables (add any user defined variables below)
              #endregion
      
              /// <summary>
              /// This method is used to configure the indicator and is called once before any bar data is loaded.
              /// </summary>
              protected override void Initialize()
              {
      			Add(PeriodType.Tick, 1);
      			CalculateOnBarClose = false;
              }
      
              /// <summary>
              /// Called on each bar update event (incoming tick)
              /// </summary>
              protected override void OnBarUpdate()
              {
      			if (CurrentBar < 20) return;
      			Print(Times[1][0]);
      		}
      
              #region Properties
      		
      
      
              #endregion
          }
      }
      And I received this as an error.

      Error on calling 'OnBarUpdate' method for indicator 'TimesTest' on bar 20: Bar index needs to be greater/equal 0
      I have a strategy that uses times perfectly fine, so i know it isn't that, but I don't know why this isn't working at all.

      Comment


        #4
        Hello,

        Thank you for the reply.

        What you have will work fine, you are just checking the wrong CurrentBar for the first condition you have.

        You are trying to print Times[1][0] which is the CurrentBar of the Second data series or index location 1.

        Instead of checking the CurrentBar is less than 20 you would need to check that you have at least 1 tick bar on your second series by using the following:

        Code:
        if (CurrentBars[1] < 1) return;
        http://www.ninjatrader.com/support/h...ub=CurrentBars

        You would still need these checks in a strategy, but strategies are different in the fact that they require 20 bars for all series before trading can start where indicators only do this if you check it yourself.


        I look forward to being of further assistance.
        JesseNinjaTrader Customer Service

        Comment


          #5
          What you said helped me, but now I'm struggling with something associated with Times that im storing not giving the correct data.

          ExitTime[1] is what I need to grab but I get

          Error on calling 'OnBarUpdate' method for indicator 'ProfitLossDetector' on bar 20: You are accessing an index with a value that is invalid since its out of range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.
          Also, Times[1][0] seems to be printing the time for both timeframes.


          Here is a sample code with some things changed around

          Code:
          public class ProfitLossDetector : Indicator
              {
                  #region Variables
                  // Wizard generated variables
                  // User defined variables (add any user defined variables below)
          		private int rSIPeriod = 10;
          		private int lookBackMax = 10; // Default setting for LookBackMax
                  private int lookBackMin = 1; // Default setting for LookBackMin
          		private bool inTrade = false;
          		private int overBought = 70;
          		private int hours = 0;
          		private int minutes = 1;
          		private int seconds = 0;
          		private int addedTime = 0;
          		private bool timeSet = false;
          		private bool longShort = false;
          		private double totalTrades = 1;
          		private double totalWins = 1;
                  #endregion
          
                  /// <summary>
                  /// This method is used to configure the indicator and is called once before any bar data is loaded.
                  /// </summary>
                  protected override void Initialize()
                  {
                      Overlay				= false;
          			Add(PeriodType.Tick, 1);
          			CalculateOnBarClose = false;
          			Add(new Plot(Color.FromKnownColor(KnownColor.Transparent), PlotStyle.Square, "EntryPrice"));
          			Add(new Plot(Color.FromKnownColor(KnownColor.Transparent), PlotStyle.Square, "ExitTime"));
          			Add(new Plot(Color.FromKnownColor(KnownColor.Black), PlotStyle.Line, "WinPercentage"));
          			addedTime = (10000 * hours) + (100 * minutes) + (1 * seconds);
                  }
          
                  /// <summary>
                  /// Called on each bar update event (incoming tick)
                  /// </summary>
                  protected override void OnBarUpdate()
                  {	//no out of bounds
          			if (CurrentBars[0] < 20 && CurrentBars[1] < 20) return;		
          			
          			if (FirstTickOfBar
          				&& BarsInProgress == 0)
          					inTrade = false;
          
          			if (BarsInProgress == 0)
          			{
          				//reset on first tick
          				if (FirstTickOfBar)
          				{
          					inTrade = false;
          					EntryPrice.Set(0);
          					ExitTime.Set(0);
          				}
          				
          				#region Entry
          			
          					#region Long
          					//if a long divergence is found
          					if (DivergenceLiveTestIndic(BarsArray[0],14, "Alert1.wav", Color.DarkMagenta, DashStyle.Solid, 3, 14, 5, 3, 9, "Alert2.wav", 0, 1, Color.Cyan, 12, 26, 9, 5, "Alert1.wav", D3SpotIndicatorMethod.RSI, 14, 14, 0, D3SpotPriceType.Open_Close, 14, rSIPeriod, 3, 14, lookBackMax, false, 25, lookBackMin, 13, 25, 7, 14, 3, 3, 14, 14, Color.Yellow, true).LongShort[0] == -1
          						&& inTrade == false)
          					{	//if overbought is set
          						if (overBought > 0
          							&& RSI(rSIPeriod, 5)[LowestBar(RSI(rSIPeriod, 5), lookBackMax)] < (100 - overBought))
          						{
          							EntryPrice.Set(Close[0]);
          							inTrade = true;
          							longShort = true;
          							timeSet = false;
          							ExitTime.Set(ToTime(Times[1][0]) + addedTime);
          							DrawDot("Ldot" + CurrentBar.ToString(), true, 0, Close[0], Color.Black);
          						}//if overbought isnt set
          						else if (overBought == 0)
          						{
          							EntryPrice.Set(Close[0]);
          							inTrade = true;
          							longShort = true;
          							timeSet = false;
          							ExitTime.Set(ToTime(Times[1][0]) + addedTime);
          							DrawDot("Ldot" + CurrentBar.ToString(), true, 0, Close[0], Color.Black);
          						}
          					}
          					#endregion
          				
          					#region Short
          					//if a short divergence is found
          					if (DivergenceLiveTestIndic(BarsArray[0],14, "Alert1.wav", Color.DarkMagenta, DashStyle.Solid, 3, 14, 5, 3, 9, "Alert2.wav", 0, 1, Color.Cyan, 12, 26, 9, 5, "Alert1.wav", D3SpotIndicatorMethod.RSI, 14, 14, 0, D3SpotPriceType.Open_Close, 14, rSIPeriod, 3, 14, lookBackMax, false, 25, lookBackMin, 13, 25, 7, 14, 3, 3, 14, 14, Color.Yellow, true).LongShort[0] == 1
          						&& inTrade == false)
          					{	//if overbought is set
          						if (overBought > 0
          							&& RSI(rSIPeriod, 5)[LowestBar(RSI(rSIPeriod, 5), lookBackMax)] < (100 - overBought))
          						{
          							EntryPrice.Set(Close[0]);
          							inTrade = true;
          							longShort = false;
          							ExitTime.Set(ToTime(Times[1][0]) + addedTime);
          							DrawDot("Ldot" + CurrentBar.ToString(), true, 0, Close[0], Color.Black);
          						}//if overbought isnt set
          						else
          						{
          							EntryPrice.Set(Close[0]);
          							inTrade = true;
          							longShort = false;
          							ExitTime.Set(ToTime(Times[1][0]) + addedTime);
          							DrawDot("Ldot" + CurrentBar.ToString(), true, 0, Close[0], Color.Black);
          						}
          					}
          					#endregion	
          				
          				#endregion
          		
          				#region Exit
          			
          				if (inTrade
          					&& ToTime(Times[1][0]) >= ExitTime[0])
          				{
          					DrawDot("Ldot" + CurrentBar.ToString(), true, 0, Close[0], Color.White);
          					DrawLine("Trade" + CurrentBar, 1, EntryPrice[1], 0, Close[0], Color.Crimson);
          					//if a price is above the entry on a long
          					if(longShort
          						&& Close[0] > EntryPrice[1])
          					{
          						totalTrades = (totalTrades + 1);
          						totalWins = (totalWins + 1);	
          					}
          					//if price is below entry on a short
          					else if(longShort == false
          							&& Close[0] < EntryPrice[1])
          					{
          						totalTrades = (totalTrades + 1);
          						totalWins = (totalWins + 1);	
          					}
          					//losing trade
          					else
          						totalTrades = (totalTrades + 1);
          				}
          				#endregion	
          				
          				if (totalTrades > 0)
          					WinPercentage.Set((totalWins / totalTrades) * 100);
          				
          				Print(Times[1][0] + "	" + ExitTime[0]);
          			}
          		}
          
                  #region Properties
          		
          		[Browsable(false)]	// this line prevents the data series from being displayed in the indicator properties dialog, do not remove
                  [XmlIgnore()]		// this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
                  public DataSeries EntryPrice
                  {
                      get { return Values[0]; }
                  }
          		
          		[Browsable(false)]	// this line prevents the data series from being displayed in the indicator properties dialog, do not remove
                  [XmlIgnore()]		// this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
                  public DataSeries ExitTime
                  {
                      get { return Values[1]; }
                  }
          		
          		[Browsable(false)]	// this line prevents the data series from being displayed in the indicator properties dialog, do not remove
                  [XmlIgnore()]		// this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
                  public DataSeries WinPercentage
                  {
                      get { return Values[2]; }
                  }
          		
          		[Description("")]
                  [GridCategory("Exits")]
                  public int Hours
                  {
                      get { return hours; }
                      set { hours = Math.Max(0, value);}
                  }
          		
          		[Description("")]
                  [GridCategory("Exits")]
                  public int Minutes
                  {
                      get { return minutes; }
                      set { minutes = Math.Max(0, value);}
                  }
          		
          		[Description("")]
                  [GridCategory("Exits")]
                  public int Seconds
                  {
                      get { return seconds; }
                      set { seconds = Math.Max(0, value);}
                  }
          		
          		[Description("Only works for RSI")]
                  [GridCategory("Parameters")]
                  public int OverBought
                  {
                      get { return overBought; }
                      set { overBought = Math.Max(0, value);}
                  }
          		
          		[Description("")]
                  [GridCategory("Parameters")]
                  public int RSIPeriod
                  {
                      get { return rSIPeriod; }
                      set { rSIPeriod = Math.Max(1, value); }
                  }
          		
          		        [Description("")]
                  [GridCategory("Parameters")]
                  public int LookBackMax
                  {
                      get { return lookBackMax; }
                      set { lookBackMax = Math.Max(1, value); }
                  }
          
                  [Description("")]
                  [GridCategory("Parameters")]
                  public int LookBackMin
                  {
                      get { return lookBackMin; }
                      set { lookBackMin = Math.Max(0, value); }
                  }
          
                  #endregion
              }
          }
          If you could get this running properly I could get mine running the same way if you can help me.

          Comment


            #6
            Hello,

            Unfortunately this script is referencing indicators you have but I do not have.

            If all of the references indicators have been created by yourself or they are open source, please do a File -> Utilites -> Export NinjaScript to include the references so I can import this item.

            I commented out the Entry and Exit statements because that contained the indicators I do not have and had no errors, so it may be related to these items.

            I look forward to being of further assistance.
            JesseNinjaTrader Customer Service

            Comment


              #7
              I'm sorry, I sent you the wrong thing.

              I basically need something like this to work because this is where I'm having the problem.

              Code:
                  public class TimesTest : Indicator
                  {
                      #region Variables
                      // Wizard generated variables
                      // User defined variables (add any user defined variables below)
              		private int hours = 1;
              		private int minutes = 1;
              		private int seconds = 0;
              		private int addedTime = 0;
                      #endregion
              
                      /// <summary>
                      /// This method is used to configure the indicator and is called once before any bar data is loaded.
                      /// </summary>
                      protected override void Initialize()
                      {
              			Add(PeriodType.Tick, 1);
              			CalculateOnBarClose = false;
              			Add(new Plot(Color.FromKnownColor(KnownColor.Transparent), PlotStyle.Square, "ExitTime"));
              			addedTime = (10000 * hours) + (100 * minutes) + (1 * seconds);
                      }
              
                      /// <summary>
                      /// Called on each bar update event (incoming tick)
                      /// </summary>
                      protected override void OnBarUpdate()
                      {
              			if (CurrentBars[1] < 20) return;
              			
              			if (BarsInProgress == 0)
              			{
              			
              				ExitTime.Set(ToTime(Times[1][0]) + addedTime);
              			
              				Print(Times[1][0] + "	" + ExitTime[1]);
              				
              			}
              		}
              
                      #region Properties
              		[Browsable(false)]	// this line prevents the data series from being displayed in the indicator properties dialog, do not remove
                      [XmlIgnore()]		// this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
                      public DataSeries ExitTime
                      {
                          get { return Values[0]; }
                      }
              
              
                      #endregion
                  }
              }
              And the output should be the current time (to the second) and the exit time which is the current time (to the second) + 1 hour and 1 minute.

              Thanks so much for helping to the point.

              Comment


                #8
                Hello magnatauren,

                Thank you for your response.

                You would want to sync ExitTime to the secondary series. Please take a look at our reference sample on syncing to secondary series at the following link: http://www.ninjatrader.com/support/f...ead.php?t=3572
                Patrick H.NinjaTrader Customer Service

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by lunardiplomacy, Today, 07:57 AM
                0 responses
                1 view
                0 likes
                Last Post lunardiplomacy  
                Started by Tagliareni, Yesterday, 08:10 PM
                1 response
                11 views
                0 likes
                Last Post NinjaTrader_PaulH  
                Started by SDaCosta30, Today, 04:19 AM
                1 response
                11 views
                0 likes
                Last Post NinjaTrader_PaulH  
                Started by memonolog, Today, 02:39 AM
                5 responses
                24 views
                0 likes
                Last Post memonolog  
                Started by memonolog, Today, 07:07 AM
                1 response
                5 views
                0 likes
                Last Post NinjaTrader_ChrisL  
                Working...
                X