Error: Object reference not set to an instance of an object. - futures io
futures io futures trading



Error: Object reference not set to an instance of an object.


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one gomad with 5 posts (0 thanks)
    2. looks_two Zondor with 2 posts (5 thanks)
    3. looks_3 stearno with 2 posts (0 thanks)
    4. looks_4 devdas with 1 posts (1 thanks)
    1. trending_up 8,253 views
    2. thumb_up 10 thanks given
    3. group 3 followers
    1. forum 11 posts
    2. attach_file 4 attachments




Welcome to futures io: the largest futures trading community on the planet, with well over 125,000 members
  • Genuine reviews from real traders, not fake reviews from stealth vendors
  • Quality education from leading professional traders
  • We are a friendly, helpful, and positive community
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts
  • We are here to help, just let us know what you need
You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

(If you already have an account, login at the top of the page)

 
Search this Thread
 

Error: Object reference not set to an instance of an object.

(login for full post details)
  #1 (permalink)
Tirgu Mures, Romania
 
Experience: Intermediate
Platform: Ninja
Broker: ZenFire
Trading: CL, GC
 
Posts: 36 since Sep 2010
Thanks: 42 given, 6 received

I have read all threads that I found about this problem, but I didn't find any solution for my particular situation.

I'm trying to find some significant statistical correlations on market (using GraphPad) and for this I use many custom indicators (to get data out of the market).

Here is an indicator which I've coded this days, but when I use it on Market Replay or Sim I get the following error (in Log tab):


Quoting 
Error on calling 'OnBarUpdate' method for indicator 'aTrendEnter' on bar 56 (this error is repetitive, not just on this bar): Object reference not set to an instance of an object.

Using try-catch I have the following text in my Output Window:


Quoting 
3/23/2011 8:36:54 AM System.NullReferenceException: Object reference not set to an instance of an object.
at NinjaTrader.Data.MemBars.GetOpen(Int32 index)
at NinjaTrader.Data.Bars.GetOpen(Int32 index)
at NinjaTrader.Indicator.DataSeriesHelper.get_Item(In t32 barsAgo)
at NinjaTrader.Indicator.aTrend2.OnBarUpdate()

The lines isolated in "try" are as follows:

 
Code
for (int i = 0;  i < Period; i++)
				
				
				
        	{
				try {
					if (Close[i] > Open[i-2] && High[i-2] < Close[i-8])
						var2 = var2 + 1;
				}
				
				catch (Exception e)
						
			
			{
				/* With our caught exception we are able to generate log entries that go to the Control Center logs and also print more detailed information
				about the error to the Output Window. */
				
				// Submits an entry into the Control Center logs to inform the user of an error
				Log("SampleTryCatch Error: Please check your indicator for errors.", LogLevel.Error);
				
				// Prints the caught exception in the Output Window
				Print(Time[0] + " " + e.ToString());
			}
								
			}
			
			Short.Set(var2);
When Market Replay is playing or market is moving on sim, my chart is going crazy. Look at this 8 Range Chart on CL:





And here is the indicator attached:

aTrend2.zip

Can someone help me with this problem?

Thank you.

Started this thread Reply With Quote

Can you help answer these questions
from other members on futures io?
EL/PL for FOPs?
EasyLanguage Programming
COTbase for quant trading?
Elite Algorithmic NinjaTrader Trading
What blockvolume is visible? - order processing
NinjaTrader
Short Interest Ratio indicator?
ThinkOrSwim
ZigZag with Depth and Backstep
EasyLanguage Programming
 
Best Threads (Most Thanked)
in the last 7 days on futures io
Battlestations: Show us your trading desks!
124 thanks
Big Mike in Ecuador
61 thanks
Want your NinjaTrader indicator created, free?
28 thanks
If you needed one-on-one help with any trading issue, ho …
26 thanks
Selling Options on Futures?
21 thanks
 
(login for full post details)
  #3 (permalink)
Portland Oregon, United States
 
Experience: Beginner
Platform: Ninjatrader®
Broker: CQG, Kinetick
Trading: Gameplay Klownbine® Trading of Globex
 
Zondor's Avatar
 
Posts: 1,347 since Jul 2009
Thanks: 1,245 given, 2,721 received


It is good that you are using try{ }catch blocks for debugging.

In the OnStartUp method try doing a one time assignment of arbitrary values to the Open, Close and High data series to force them to be created.

In the OnBarUpdate method try testing for null values of the data series before attempting to access or manipulate them:

 
Code
If (Close==null || Open==null || High ==null) return:

Follow me on Twitter Visit my futures io Trade Journal Reply With Quote
The following 3 users say Thank You to Zondor for this post:
 
(login for full post details)
  #4 (permalink)
Tirgu Mures, Romania
 
Experience: Intermediate
Platform: Ninja
Broker: ZenFire
Trading: CL, GC
 
Posts: 36 since Sep 2010
Thanks: 42 given, 6 received


Zondor View Post

In the OnStartUp method try doing a one time assignment of arbitrary values to the Open, Close and High data series to force them to be created.

Zondor,

Thank you for your reply.

Can you help me with an example of "one time assignment of arbitrary values to the Open, Close and High data series to force them to be created"?

Started this thread Reply With Quote
 
(login for full post details)
  #5 (permalink)
Tirgu Mures, Romania
 
Experience: Intermediate
Platform: Ninja
Broker: ZenFire
Trading: CL, GC
 
Posts: 36 since Sep 2010
Thanks: 42 given, 6 received


gomad View Post
Zondor,

Thank you for your reply.

Can you help me with an example of "one time assignment of arbitrary values to the Open, Close and High data series to force them to be created"?

Becouse it is true that the indicator is deactivated when I use the code you suggested above:


Quoting 
if (Close==null || Open==null || High ==null) return;


Started this thread Reply With Quote
 
(login for full post details)
  #6 (permalink)
Al,India
 
Experience: Advanced
Platform: NinjaTrader
Broker: RKG
Trading: NiftyFuture
 
devdas's Avatar
 
Posts: 1,562 since Feb 2010
Thanks: 1,504 given, 1,701 received


gomad View Post

Error on calling 'OnBarUpdate' method for indicator 'aTrendEnter' on bar 56 (this error is repetitive, not just on this bar): Object reference not set to an instance of an object.

from this i guess its a logical error in indicator construction than usual Initialization or OnStartUp error.
This type had happened with me in past , throwing error on different bars..some time indic working and some time shewed error. In end , in my case it turned out logical error in indicator.

Harvest The Moon
Nest The Market
Follow me on Twitter Visit my futures io Trade Journal Reply With Quote
The following user says Thank You to devdas for this post:
 
(login for full post details)
  #7 (permalink)
Tirgu Mures, Romania
 
Experience: Intermediate
Platform: Ninja
Broker: ZenFire
Trading: CL, GC
 
Posts: 36 since Sep 2010
Thanks: 42 given, 6 received


devdas View Post
from this i guess its a logical error in indicator construction than usual Initialization or OnStartUp error.
This type had happened with me in past , throwing error on different bars..some time indic working and some time shewed error. In end , in my case it turned out logical error in indicator.

Yes, but the only condition the indicator have is this:

 
Code
for (int i = 0;  i < Period; i++)
				
				
				
        	{
				try {
					if (Close[i] > Open[i-2] && High[i-2] < Close[i-8])
						var2 = var2 + 1;
				}
				
				catch (Exception e)
						
			
			{
				/* With our caught exception we are able to generate log entries that go to the Control Center logs and also print more detailed information
				about the error to the Output Window. */
				
				// Submits an entry into the Control Center logs to inform the user of an error
				Log("SampleTryCatch Error: Please check your indicator for errors.", LogLevel.Error);
				
				// Prints the caught exception in the Output Window
				Print(Time[0] + " " + e.ToString());
			}
								
			}
			
			Short.Set(var2);
I don't see where the error can be in this condition:

 
Code
if (Close[i] > Open[i-2] && High[i-2] < Close[i-8])

Started this thread Reply With Quote
 
(login for full post details)
  #8 (permalink)
Portland Oregon, United States
 
Experience: Beginner
Platform: Ninjatrader®
Broker: CQG, Kinetick
Trading: Gameplay Klownbine® Trading of Globex
 
Zondor's Avatar
 
Posts: 1,347 since Jul 2009
Thanks: 1,245 given, 2,721 received


Quoting 
Can you help me with an example of "one time assignment of arbitrary values to the Open, Close and High data series to force them to be created"?

in OnStartUp maybe this will help:

 
Code
double dummy;
dummy=Close[0];
dummy=Open[0];
dummy=High{0];
How are your dataeries declared? Are they public or private?

Follow me on Twitter Visit my futures io Trade Journal Reply With Quote
The following 2 users say Thank You to Zondor for this post:
 
(login for full post details)
  #9 (permalink)
Tirgu Mures, Romania
 
Experience: Intermediate
Platform: Ninja
Broker: ZenFire
Trading: CL, GC
 
Posts: 36 since Sep 2010
Thanks: 42 given, 6 received


Zondor View Post
in OnStartUp maybe this will help:

 
Code
double dummy;
dummy=Close[0];
dummy=Open[0];
dummy=High{0];

Unfortunately it is not working. The same error.


Quoting 
How are your dataeries declared? Are they public or private?

Where I find this information?

Is there some "default" for this?

All my code is written in "protected override void On bar update" and "protected override void Initialize".

Started this thread Reply With Quote
 
(login for full post details)
  #10 (permalink)
Site Sponsor

Web: Jigsaw Trading
AMA: Ask Me Anything
Webinars: Jigsaw Trading Webinars
Elite offer: Click here
 
 
Jigsaw Trading's Avatar
 
Posts: 2,977 since Nov 2010
Thanks: 823 given, 10,316 received


Uggghhh - this error... seriously - in the year 2011, is this the best we can get.

I have 2 bug bears with this type of error. First - it gets reported as an error in "OnBarUpdate" event but it could actually be in any method called from within OnBarUpdate - which in most cases can be pretty much anywhere.

The other thing is it's a generic message - .NET must know the object in question but doesn't tell us what it is...

ugghhh...

Anyway - I think you are looking for past values on the high, open & close, right:

if (Close[i] > Open[i-2] && High[i-2] < Close[i-8])

Shouldn't this be:

if (Close[i] > Open[i+2] && High[i+2] < Close[i+8]) ????

If i = 0, then your Close[i-8] is going to be resolve to Close[-8] - is that looking for 8 bars in the future ???? To look 8 bars back, you would do Close[8]. So - if you look further back, you need to add to i.

Hope this helps

Pete

Visit my futures io Trade Journal Reply With Quote
The following 4 users say Thank You to Jigsaw Trading for this post:
 
(login for full post details)
  #11 (permalink)
Muscat, Oman
 
Experience: Intermediate
Platform: Ninja and MT4
Trading: Forex
 
Posts: 15 since Apr 2012
Thanks: 4 given, 3 received

I get the following error messages in the Output Window when I use this indicator with Market Analyzer.

"Sell set value[2] loc=2 the low being set:0.9676
01/12/2014 03:36:00 System.NullReferenceException: Object reference not set to an instance of an object.
at NinjaTrader.Indicator.KnoxvilleDivergence4M2.RSISellCheck(Int32 loc)
at NinjaTrader.Indicator.KnoxvilleDivergence4M2.OnBarUpdate()"

I put Print() throughout my code and was able to 'track down' which line of code is causing the error.

Code Excerpt:
 
Code
Values[2].Set(loc, Low[loc]); 
Print("Sell set value[2]" + " " + "loc="+loc+ " " + "the low being set:"+ Low[loc] );
So three questions:
1. I tried to use Try and Catch, but it did not seem to work on my custom methods (in this case: RSISellCheck(2) & RSIBuyCheck(2). Does Try and Catch work in only the standard methods (like OnBarUpdate) or does it also work in custom methods?
2. Why is this error coming and why is it only happening occassionally and not every bar. The value is always 2. So sometimes it assigns the Low[2] okay and sometimes it gives this error.
3. Why is it giving an error when it shows in the Print the actual Low price value?

Thank you for your help!

-Stearno

 
Code
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
#endregion

// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    [Description("Enter the description of your new custom indicator here")]
    public class KnoxvilleDivergence4M2 : Indicator
    {
        #region Variables
        
		private int candlesBack = 150; // Default setting for CandlesBack
        private int rSIPeriod = 21; // Default setting for RSIPeriod
        private int momentumPeriod = 20; // Default setting for MomentumPeriod
		
        private int validBars=4;
				int lastBarDivB=10000;
				int lastBarDivS=10000;
		
		private RSI rsi;
		private KnoxvilleMomentum mom;
		private DataSeries mydivergence;
		
        #endregion
//_______________________________________________________________________________________________________________________________________________________________
        protected override void Initialize()
        {
			Add(new Plot(Color.Yellow, "Momentum"));
			Add(new Plot(Color.Green, "DivBuy"));
			Add(new Plot(Color.Red, "DivSell"));
			Add(new Plot(Color.Blue, "Div"));
			Add(new Plot(Color.Blue, "AuxB"));
            Add(new Plot(Color.Blue, "AuxS"));
            Overlay				= false;
        }
//_______________________________________________________________________________________________________________________________________________________________
		protected override void OnStartUp()
		{
			rsi=RSI(rSIPeriod,1);
			mom=KnoxvilleMomentum(momentumPeriod);
		}
//_______________________________________________________________________________________________________________________________________________________________
        protected override void OnBarUpdate()
        {
			try
			{
			if (CurrentBar<candlesBack)return;
			if (CurrentBar<10)return;
			
			
			//BarsNew();
			Mom.Set(mom[0]);

			Values[1].Set(0.00);   // divBuy
			Values[2].Set(0.00);   // divSell
			
			//Print(Time[0]+"    "+Values[4][0]+"  "+Values[5][0]+"      "+Values[4][1]+"  "+Values[5][1]);
			if(CurrentBar>=lastBarDivB && CurrentBar-lastBarDivB<=validBars)Values[4].Set(1); else Values[4].Set(0.00);  
			if(CurrentBar>=lastBarDivS && CurrentBar-lastBarDivS<=validBars)Values[5].Set(1); else Values[5].Set(0.00);  
			//BarsNew();

			RSISellCheck(2);
			
			RSIBuyCheck(2);
			}
			catch (Exception e)
			{
				/* With our caught exception we are able to generate log entries that go to the Control Center logs and also print more detailed information
				about the error to the Output Window. */
				
				// Submits an entry into the Control Center logs to inform the user of an error
				Log("SampleTryCatch Error: Please check your indicator for errors.", LogLevel.Error);
				
				// Prints the caught exception in the Output Window
				Print(Time[0] + " " + e.ToString());
			}
				//Print(Time[0]+"... "+AuxB[0]+"  "+AuxS[0]+"      "+Values[1][0]+"  "+Values[2][0]);
			BarsNew();
			if(CurrentBar>=lastBarDivB && CurrentBar-lastBarDivB<=validBars)Values[4].Set(1); else Values[4].Set(0.00);  
			if(CurrentBar>=lastBarDivS && CurrentBar-lastBarDivS<=validBars)Values[5].Set(1); else Values[5].Set(0.00);  
        }

//_______________________________________________________________________________________________________________________________________________________________
	void BarsNew(){ int N=0, n=0;
		for(N=0;N<candlesBack;N++){
			if(Values[1][N]>0){for(n=N;n>N-validBars;n--){ if(n>=0)Values[4].Set(n, 1); } }
			if(Values[2][N]>0){for(n=N;n>N-validBars;n--){ if(n>=0)Values[5].Set(n, 1); } }
		}
				
	}
//_______________________________________________________________________________________________________________________________________________________________
		// FormatPriceMarker method of a custom indicator
 		public override string FormatPriceMarker(double price)
		{
    		// Formats price values to 4 decimal places
    		return price.ToString("N4");
		}
//_______________________________________________________________________________________________________________________________________________________________
		private void RSISellCheck(int loc)
		{
			double rsiMain = rsi[loc];
			if (rsiMain<50)
				return;
			for (int x=loc-1;x<=loc+2;x++)
			{
				if (High[x]>High[loc])
					return;
			}
	
			for (int y=loc+4;y<(loc+candlesBack);y++)
			{
				if (High[y]>High[loc])
					break;
				int s=y;
	
				for (int z=y-2;z<=y+2;z++)
				{
					if (High[z]>High[y])
					{
						y++;
						break;
					}
				}
				if (s!=y)
				{
					y--;
					continue;
				}
				bool ob = false;
		
				for (int k=loc-1;k<=y;k++)
				{
					double rsiob = rsi[k];
					if (rsiob>70)
					{
						ob=true;
						break;
					}
				}
				if (!ob)
					continue;

				double mom1 = mom[loc];
				double mom2 = mom[y];
				
				if (mom1>mom2)
					continue;
	
				Print("Sell set value[2]" + " " + "loc="+loc+ " " + "the low being set:"+ Low[loc] );
				Values[2].Set(loc, Low[loc]);  
				lastBarDivS=CurrentBar;       //Print(Time[0]+"B   lastB:"+lastBarDivB+" lastS:"+lastBarDivS);
				
				ChartObjectCollection coc = ChartControl.ChartObjects;  
				for (int x=0;x<coc.Count;x++)
				{
					ChartObject c = coc[x];
					if (c.DrawType==DrawType.Line)
					{
						ILine line = (ILine)c;
						if (line.StartBarsAgo==y)
							RemoveDrawObject(line);
					}
				}
				
				DrawLine(Time[loc].ToString()+"High",y,High[y],loc,High[loc],Color.Red);
				DrawOnPricePanel=false;
				DrawLine(Time[loc].ToString()+"MomHigh",y,mom2,loc,mom1,Color.Red);
				DrawOnPricePanel=true;
			}
		}
//_______________________________________________________________________________________________________________________________________________________________		
		private void RSIBuyCheck(int loc)
		{
			double rsiMain = rsi[loc];
			if (rsiMain>50)
				return;

			for (int x=loc-1;x<=loc+2;x++)
			{
				if (Low[x]<Low[loc])
					return;
			}

			for (int y=loc+4;y<(loc+candlesBack);y++)
			{
				if (Low[y]<Low[loc])
					break;
				int s=y;

				for (int z=y-2;z<=y+2;z++)
				{
					if (Low[z]<Low[y])
					{
						y++;
						break;
					}
				}
				if (s!=y)
				{
					y--;
					continue;
				}
				bool ob = false;

				for (int k=loc-1;k<=y;k++)
				{
					double rsiob = rsi[k];
					if (rsiob<30)
					{
						ob=true;
						break;
					}
				}
				if (!ob)
					continue;

				double mom1 = mom[loc];
				double mom2 = mom[y];
				if (mom1<mom2)
					continue;
	
				Print("Buy set value[2]" + " " + "loc="+loc+ " " + "the high being set:"+ High[loc] );
				Values[1].Set(loc, High[loc]);  
				lastBarDivB=CurrentBar;  //Print(Time[0]+"B   lastB:"+lastBarDivB+" lastS:"+lastBarDivS);
				
				
				ChartObjectCollection coc = ChartControl.ChartObjects;
				for (int x=0;x<coc.Count;x++)
				{
					ChartObject c = coc[x];
					if (c.DrawType==DrawType.Line)
					{
						ILine line = (ILine)c;
						if (line.StartBarsAgo==y)
							RemoveDrawObject(line);
					}
				}
				
				DrawLine(Time[loc].ToString()+"Low",y,Low[y],loc,Low[loc],Color.Red);
				DrawOnPricePanel=false;
				DrawLine(Time[loc].ToString()+"MomLow",y,mom2,loc,mom1,Color.Red);
				DrawOnPricePanel=true;
			}
		}
//_______________________________________________________________________________________________________________________________________________________________

        #region Properties
		
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries Mom
		{
			get { return Values[0]; }
		}
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries DivBuy
		{
			get { return Values[1]; }
		}		
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries DivSell
		{
			get { return Values[2]; }
		}
		
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries Div
		{
			get { return Values[3]; }
		}
		
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries AuxB
		{
			get { return Values[4]; }
		}
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries AuxS
		{
			get { return Values[5]; }
		}

        [Description("")]
        [GridCategory("Parameters")]
        public int CandlesBack
        {
            get { return candlesBack; }
            set { candlesBack = Math.Max(1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int RSIPeriod
        {
            get { return rSIPeriod; }
            set { rSIPeriod = Math.Max(1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int MomentumPeriod
        {
            get { return momentumPeriod; }
            set { momentumPeriod = Math.Max(1, value); }
        }
		
		[Description("")]
        [GridCategory("Parameters")]
        public int ValidBars
        {
            get { return validBars; }
            set { validBars = Math.Max(1, value); }
        }
		
        #endregion
    }
}

#region NinjaScript generated code. Neither change nor remove.
// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    public partial class Indicator : IndicatorBase
    {
        private KnoxvilleDivergence4M2[] cacheKnoxvilleDivergence4M2 = null;

        private static KnoxvilleDivergence4M2 checkKnoxvilleDivergence4M2 = new KnoxvilleDivergence4M2();

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            return KnoxvilleDivergence4M2(Input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(Data.IDataSeries input, int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            if (cacheKnoxvilleDivergence4M2 != null)
                for (int idx = 0; idx < cacheKnoxvilleDivergence4M2.Length; idx++)
                    if (cacheKnoxvilleDivergence4M2[idx].CandlesBack == candlesBack && cacheKnoxvilleDivergence4M2[idx].MomentumPeriod == momentumPeriod && cacheKnoxvilleDivergence4M2[idx].RSIPeriod == rSIPeriod && cacheKnoxvilleDivergence4M2[idx].ValidBars == validBars && cacheKnoxvilleDivergence4M2[idx].EqualsInput(input))
                        return cacheKnoxvilleDivergence4M2[idx];

            lock (checkKnoxvilleDivergence4M2)
            {
                checkKnoxvilleDivergence4M2.CandlesBack = candlesBack;
                candlesBack = checkKnoxvilleDivergence4M2.CandlesBack;
                checkKnoxvilleDivergence4M2.MomentumPeriod = momentumPeriod;
                momentumPeriod = checkKnoxvilleDivergence4M2.MomentumPeriod;
                checkKnoxvilleDivergence4M2.RSIPeriod = rSIPeriod;
                rSIPeriod = checkKnoxvilleDivergence4M2.RSIPeriod;
                checkKnoxvilleDivergence4M2.ValidBars = validBars;
                validBars = checkKnoxvilleDivergence4M2.ValidBars;

                if (cacheKnoxvilleDivergence4M2 != null)
                    for (int idx = 0; idx < cacheKnoxvilleDivergence4M2.Length; idx++)
                        if (cacheKnoxvilleDivergence4M2[idx].CandlesBack == candlesBack && cacheKnoxvilleDivergence4M2[idx].MomentumPeriod == momentumPeriod && cacheKnoxvilleDivergence4M2[idx].RSIPeriod == rSIPeriod && cacheKnoxvilleDivergence4M2[idx].ValidBars == validBars && cacheKnoxvilleDivergence4M2[idx].EqualsInput(input))
                            return cacheKnoxvilleDivergence4M2[idx];

                KnoxvilleDivergence4M2 indicator = new KnoxvilleDivergence4M2();
                indicator.BarsRequired = BarsRequired;
                indicator.CalculateOnBarClose = CalculateOnBarClose;
#if NT7
                indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256;
                indicator.MaximumBarsLookBack = MaximumBarsLookBack;
#endif
                indicator.Input = input;
                indicator.CandlesBack = candlesBack;
                indicator.MomentumPeriod = momentumPeriod;
                indicator.RSIPeriod = rSIPeriod;
                indicator.ValidBars = validBars;
                Indicators.Add(indicator);
                indicator.SetUp();

                KnoxvilleDivergence4M2[] tmp = new KnoxvilleDivergence4M2[cacheKnoxvilleDivergence4M2 == null ? 1 : cacheKnoxvilleDivergence4M2.Length + 1];
                if (cacheKnoxvilleDivergence4M2 != null)
                    cacheKnoxvilleDivergence4M2.CopyTo(tmp, 0);
                tmp[tmp.Length - 1] = indicator;
                cacheKnoxvilleDivergence4M2 = tmp;
                return indicator;
            }
        }
    }
}

// This namespace holds all market analyzer column definitions and is required. Do not change it.
namespace NinjaTrader.MarketAnalyzer
{
    public partial class Column : ColumnBase
    {
        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        [Gui.Design.WizardCondition("Indicator")]
        public Indicator.KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            return _indicator.KnoxvilleDivergence4M2(Input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public Indicator.KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(Data.IDataSeries input, int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            return _indicator.KnoxvilleDivergence4M2(input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }
    }
}

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    public partial class Strategy : StrategyBase
    {
        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        [Gui.Design.WizardCondition("Indicator")]
        public Indicator.KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            return _indicator.KnoxvilleDivergence4M2(Input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public Indicator.KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(Data.IDataSeries input, int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            if (InInitialize && input == null)
                throw new ArgumentException("You only can access an indicator with the default input/bar series from within the 'Initialize()' method");

            return _indicator.KnoxvilleDivergence4M2(input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }
    }
}
#endregion

Attached Files
Register to download File Type: cs KnoxvilleDivergence4M2.cs (15.5 KB, 14 views)
Reply With Quote
 
(login for full post details)
  #12 (permalink)
Muscat, Oman
 
Experience: Intermediate
Platform: Ninja and MT4
Trading: Forex
 
Posts: 15 since Apr 2012
Thanks: 4 given, 3 received

I figured out that the problem was I was calling this indicator either in strategy or in Market Anlayzer, and it had drawing functions in the indicator. For some reason, that piece of code works fine on a chart, but breaks when calling it in the other two ways. So I just made two indicators and deleted the drawing functions in one. Now no errors when using MA and Strategies.

-Stearno



stearno View Post
I get the following error messages in the Output Window when I use this indicator with Market Analyzer.

"Sell set value[2] loc=2 the low being set:0.9676
01/12/2014 03:36:00 System.NullReferenceException: Object reference not set to an instance of an object.
at NinjaTrader.Indicator.KnoxvilleDivergence4M2.RSISellCheck(Int32 loc)
at NinjaTrader.Indicator.KnoxvilleDivergence4M2.OnBarUpdate()"

I put Print() throughout my code and was able to 'track down' which line of code is causing the error.

Code Excerpt:
 
Code
Values[2].Set(loc, Low[loc]); 
Print("Sell set value[2]" + " " + "loc="+loc+ " " + "the low being set:"+ Low[loc] );
So three questions:
1. I tried to use Try and Catch, but it did not seem to work on my custom methods (in this case: RSISellCheck(2) & RSIBuyCheck(2). Does Try and Catch work in only the standard methods (like OnBarUpdate) or does it also work in custom methods?
2. Why is this error coming and why is it only happening occassionally and not every bar. The value is always 2. So sometimes it assigns the Low[2] okay and sometimes it gives this error.
3. Why is it giving an error when it shows in the Print the actual Low price value?

Thank you for your help!

-Stearno

 
Code
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
#endregion

// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    [Description("Enter the description of your new custom indicator here")]
    public class KnoxvilleDivergence4M2 : Indicator
    {
        #region Variables
        
		private int candlesBack = 150; // Default setting for CandlesBack
        private int rSIPeriod = 21; // Default setting for RSIPeriod
        private int momentumPeriod = 20; // Default setting for MomentumPeriod
		
        private int validBars=4;
				int lastBarDivB=10000;
				int lastBarDivS=10000;
		
		private RSI rsi;
		private KnoxvilleMomentum mom;
		private DataSeries mydivergence;
		
        #endregion
//_______________________________________________________________________________________________________________________________________________________________
        protected override void Initialize()
        {
			Add(new Plot(Color.Yellow, "Momentum"));
			Add(new Plot(Color.Green, "DivBuy"));
			Add(new Plot(Color.Red, "DivSell"));
			Add(new Plot(Color.Blue, "Div"));
			Add(new Plot(Color.Blue, "AuxB"));
            Add(new Plot(Color.Blue, "AuxS"));
            Overlay				= false;
        }
//_______________________________________________________________________________________________________________________________________________________________
		protected override void OnStartUp()
		{
			rsi=RSI(rSIPeriod,1);
			mom=KnoxvilleMomentum(momentumPeriod);
		}
//_______________________________________________________________________________________________________________________________________________________________
        protected override void OnBarUpdate()
        {
			try
			{
			if (CurrentBar<candlesBack)return;
			if (CurrentBar<10)return;
			
			
			//BarsNew();
			Mom.Set(mom[0]);

			Values[1].Set(0.00);   // divBuy
			Values[2].Set(0.00);   // divSell
			
			//Print(Time[0]+"    "+Values[4][0]+"  "+Values[5][0]+"      "+Values[4][1]+"  "+Values[5][1]);
			if(CurrentBar>=lastBarDivB && CurrentBar-lastBarDivB<=validBars)Values[4].Set(1); else Values[4].Set(0.00);  
			if(CurrentBar>=lastBarDivS && CurrentBar-lastBarDivS<=validBars)Values[5].Set(1); else Values[5].Set(0.00);  
			//BarsNew();

			RSISellCheck(2);
			
			RSIBuyCheck(2);
			}
			catch (Exception e)
			{
				/* With our caught exception we are able to generate log entries that go to the Control Center logs and also print more detailed information
				about the error to the Output Window. */
				
				// Submits an entry into the Control Center logs to inform the user of an error
				Log("SampleTryCatch Error: Please check your indicator for errors.", LogLevel.Error);
				
				// Prints the caught exception in the Output Window
				Print(Time[0] + " " + e.ToString());
			}
				//Print(Time[0]+"... "+AuxB[0]+"  "+AuxS[0]+"      "+Values[1][0]+"  "+Values[2][0]);
			BarsNew();
			if(CurrentBar>=lastBarDivB && CurrentBar-lastBarDivB<=validBars)Values[4].Set(1); else Values[4].Set(0.00);  
			if(CurrentBar>=lastBarDivS && CurrentBar-lastBarDivS<=validBars)Values[5].Set(1); else Values[5].Set(0.00);  
        }

//_______________________________________________________________________________________________________________________________________________________________
	void BarsNew(){ int N=0, n=0;
		for(N=0;N<candlesBack;N++){
			if(Values[1][N]>0){for(n=N;n>N-validBars;n--){ if(n>=0)Values[4].Set(n, 1); } }
			if(Values[2][N]>0){for(n=N;n>N-validBars;n--){ if(n>=0)Values[5].Set(n, 1); } }
		}
				
	}
//_______________________________________________________________________________________________________________________________________________________________
		// FormatPriceMarker method of a custom indicator
 		public override string FormatPriceMarker(double price)
		{
    		// Formats price values to 4 decimal places
    		return price.ToString("N4");
		}
//_______________________________________________________________________________________________________________________________________________________________
		private void RSISellCheck(int loc)
		{
			double rsiMain = rsi[loc];
			if (rsiMain<50)
				return;
			for (int x=loc-1;x<=loc+2;x++)
			{
				if (High[x]>High[loc])
					return;
			}
	
			for (int y=loc+4;y<(loc+candlesBack);y++)
			{
				if (High[y]>High[loc])
					break;
				int s=y;
	
				for (int z=y-2;z<=y+2;z++)
				{
					if (High[z]>High[y])
					{
						y++;
						break;
					}
				}
				if (s!=y)
				{
					y--;
					continue;
				}
				bool ob = false;
		
				for (int k=loc-1;k<=y;k++)
				{
					double rsiob = rsi[k];
					if (rsiob>70)
					{
						ob=true;
						break;
					}
				}
				if (!ob)
					continue;

				double mom1 = mom[loc];
				double mom2 = mom[y];
				
				if (mom1>mom2)
					continue;
	
				Print("Sell set value[2]" + " " + "loc="+loc+ " " + "the low being set:"+ Low[loc] );
				Values[2].Set(loc, Low[loc]);  
				lastBarDivS=CurrentBar;       //Print(Time[0]+"B   lastB:"+lastBarDivB+" lastS:"+lastBarDivS);
				
				ChartObjectCollection coc = ChartControl.ChartObjects;  
				for (int x=0;x<coc.Count;x++)
				{
					ChartObject c = coc[x];
					if (c.DrawType==DrawType.Line)
					{
						ILine line = (ILine)c;
						if (line.StartBarsAgo==y)
							RemoveDrawObject(line);
					}
				}
				
				DrawLine(Time[loc].ToString()+"High",y,High[y],loc,High[loc],Color.Red);
				DrawOnPricePanel=false;
				DrawLine(Time[loc].ToString()+"MomHigh",y,mom2,loc,mom1,Color.Red);
				DrawOnPricePanel=true;
			}
		}
//_______________________________________________________________________________________________________________________________________________________________		
		private void RSIBuyCheck(int loc)
		{
			double rsiMain = rsi[loc];
			if (rsiMain>50)
				return;

			for (int x=loc-1;x<=loc+2;x++)
			{
				if (Low[x]<Low[loc])
					return;
			}

			for (int y=loc+4;y<(loc+candlesBack);y++)
			{
				if (Low[y]<Low[loc])
					break;
				int s=y;

				for (int z=y-2;z<=y+2;z++)
				{
					if (Low[z]<Low[y])
					{
						y++;
						break;
					}
				}
				if (s!=y)
				{
					y--;
					continue;
				}
				bool ob = false;

				for (int k=loc-1;k<=y;k++)
				{
					double rsiob = rsi[k];
					if (rsiob<30)
					{
						ob=true;
						break;
					}
				}
				if (!ob)
					continue;

				double mom1 = mom[loc];
				double mom2 = mom[y];
				if (mom1<mom2)
					continue;
	
				Print("Buy set value[2]" + " " + "loc="+loc+ " " + "the high being set:"+ High[loc] );
				Values[1].Set(loc, High[loc]);  
				lastBarDivB=CurrentBar;  //Print(Time[0]+"B   lastB:"+lastBarDivB+" lastS:"+lastBarDivS);
				
				
				ChartObjectCollection coc = ChartControl.ChartObjects;
				for (int x=0;x<coc.Count;x++)
				{
					ChartObject c = coc[x];
					if (c.DrawType==DrawType.Line)
					{
						ILine line = (ILine)c;
						if (line.StartBarsAgo==y)
							RemoveDrawObject(line);
					}
				}
				
				DrawLine(Time[loc].ToString()+"Low",y,Low[y],loc,Low[loc],Color.Red);
				DrawOnPricePanel=false;
				DrawLine(Time[loc].ToString()+"MomLow",y,mom2,loc,mom1,Color.Red);
				DrawOnPricePanel=true;
			}
		}
//_______________________________________________________________________________________________________________________________________________________________

        #region Properties
		
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries Mom
		{
			get { return Values[0]; }
		}
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries DivBuy
		{
			get { return Values[1]; }
		}		
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries DivSell
		{
			get { return Values[2]; }
		}
		
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries Div
		{
			get { return Values[3]; }
		}
		
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries AuxB
		{
			get { return Values[4]; }
		}
		[Browsable(false)]
		[XmlIgnore()]
		public DataSeries AuxS
		{
			get { return Values[5]; }
		}

        [Description("")]
        [GridCategory("Parameters")]
        public int CandlesBack
        {
            get { return candlesBack; }
            set { candlesBack = Math.Max(1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int RSIPeriod
        {
            get { return rSIPeriod; }
            set { rSIPeriod = Math.Max(1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int MomentumPeriod
        {
            get { return momentumPeriod; }
            set { momentumPeriod = Math.Max(1, value); }
        }
		
		[Description("")]
        [GridCategory("Parameters")]
        public int ValidBars
        {
            get { return validBars; }
            set { validBars = Math.Max(1, value); }
        }
		
        #endregion
    }
}

#region NinjaScript generated code. Neither change nor remove.
// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    public partial class Indicator : IndicatorBase
    {
        private KnoxvilleDivergence4M2[] cacheKnoxvilleDivergence4M2 = null;

        private static KnoxvilleDivergence4M2 checkKnoxvilleDivergence4M2 = new KnoxvilleDivergence4M2();

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            return KnoxvilleDivergence4M2(Input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(Data.IDataSeries input, int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            if (cacheKnoxvilleDivergence4M2 != null)
                for (int idx = 0; idx < cacheKnoxvilleDivergence4M2.Length; idx++)
                    if (cacheKnoxvilleDivergence4M2[idx].CandlesBack == candlesBack && cacheKnoxvilleDivergence4M2[idx].MomentumPeriod == momentumPeriod && cacheKnoxvilleDivergence4M2[idx].RSIPeriod == rSIPeriod && cacheKnoxvilleDivergence4M2[idx].ValidBars == validBars && cacheKnoxvilleDivergence4M2[idx].EqualsInput(input))
                        return cacheKnoxvilleDivergence4M2[idx];

            lock (checkKnoxvilleDivergence4M2)
            {
                checkKnoxvilleDivergence4M2.CandlesBack = candlesBack;
                candlesBack = checkKnoxvilleDivergence4M2.CandlesBack;
                checkKnoxvilleDivergence4M2.MomentumPeriod = momentumPeriod;
                momentumPeriod = checkKnoxvilleDivergence4M2.MomentumPeriod;
                checkKnoxvilleDivergence4M2.RSIPeriod = rSIPeriod;
                rSIPeriod = checkKnoxvilleDivergence4M2.RSIPeriod;
                checkKnoxvilleDivergence4M2.ValidBars = validBars;
                validBars = checkKnoxvilleDivergence4M2.ValidBars;

                if (cacheKnoxvilleDivergence4M2 != null)
                    for (int idx = 0; idx < cacheKnoxvilleDivergence4M2.Length; idx++)
                        if (cacheKnoxvilleDivergence4M2[idx].CandlesBack == candlesBack && cacheKnoxvilleDivergence4M2[idx].MomentumPeriod == momentumPeriod && cacheKnoxvilleDivergence4M2[idx].RSIPeriod == rSIPeriod && cacheKnoxvilleDivergence4M2[idx].ValidBars == validBars && cacheKnoxvilleDivergence4M2[idx].EqualsInput(input))
                            return cacheKnoxvilleDivergence4M2[idx];

                KnoxvilleDivergence4M2 indicator = new KnoxvilleDivergence4M2();
                indicator.BarsRequired = BarsRequired;
                indicator.CalculateOnBarClose = CalculateOnBarClose;
#if NT7
                indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256;
                indicator.MaximumBarsLookBack = MaximumBarsLookBack;
#endif
                indicator.Input = input;
                indicator.CandlesBack = candlesBack;
                indicator.MomentumPeriod = momentumPeriod;
                indicator.RSIPeriod = rSIPeriod;
                indicator.ValidBars = validBars;
                Indicators.Add(indicator);
                indicator.SetUp();

                KnoxvilleDivergence4M2[] tmp = new KnoxvilleDivergence4M2[cacheKnoxvilleDivergence4M2 == null ? 1 : cacheKnoxvilleDivergence4M2.Length + 1];
                if (cacheKnoxvilleDivergence4M2 != null)
                    cacheKnoxvilleDivergence4M2.CopyTo(tmp, 0);
                tmp[tmp.Length - 1] = indicator;
                cacheKnoxvilleDivergence4M2 = tmp;
                return indicator;
            }
        }
    }
}

// This namespace holds all market analyzer column definitions and is required. Do not change it.
namespace NinjaTrader.MarketAnalyzer
{
    public partial class Column : ColumnBase
    {
        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        [Gui.Design.WizardCondition("Indicator")]
        public Indicator.KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            return _indicator.KnoxvilleDivergence4M2(Input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public Indicator.KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(Data.IDataSeries input, int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            return _indicator.KnoxvilleDivergence4M2(input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }
    }
}

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    public partial class Strategy : StrategyBase
    {
        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        [Gui.Design.WizardCondition("Indicator")]
        public Indicator.KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            return _indicator.KnoxvilleDivergence4M2(Input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public Indicator.KnoxvilleDivergence4M2 KnoxvilleDivergence4M2(Data.IDataSeries input, int candlesBack, int momentumPeriod, int rSIPeriod, int validBars)
        {
            if (InInitialize && input == null)
                throw new ArgumentException("You only can access an indicator with the default input/bar series from within the 'Initialize()' method");

            return _indicator.KnoxvilleDivergence4M2(input, candlesBack, momentumPeriod, rSIPeriod, validBars);
        }
    }
}
#endregion


Reply With Quote


futures io Trading Community Platforms and Indicators NinjaTrader > Error: Object reference not set to an instance of an object.


Last Updated on December 22, 2014


Upcoming Webinars and Events
 

NinjaTrader Indicator Challenge!

Ongoing
 

Battlestations! Show us your trading desk - $1,500 in prizes!

March
 

Importance of Finding Your Own Way w/Adam Grimes

Elite only
 

Journal Challenge w/Jigsaw

April
     



Copyright © 2021 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
All information is for educational use only and is not investment advice.
There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
no new posts