Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Position Monitor as an Indicator

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

    Position Monitor as an Indicator

    Simple indicator which works but has an object instance error that I can't work out.
    If any of you advanced programmers / support gurus can help me fix this I would be very grateful.
    And I know it's way out of the bounds of support....



    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;
    using System.Windows.Forms;
    
    #endregion
    
    namespace NinjaTrader.Indicator
    {
    
        [Description("Enter the description of your new custom indicator here")]
        public class PositionMonitor1 : Indicator
        {
            #region Variables
    		private ComboBox ctrdrAcct;
    		private Account selectedacct;	
    		
            #endregion
    
            protected override void Initialize()
            {
    		            Overlay = true;
    
            }
    		protected override void OnTermination()
    		{
    		selectedacct.PositionUpdate -= new PositionUpdateEventHandler(positionchangedHandler);
    		}
    		
    				protected override void OnStartUp()
    		{
    		
    				{
    				ctrdrAcct = (ComboBox)ChartControl.Controls["pnlChartTrader"].Controls["ctrChartTraderControl"].Controls["cboAccount"];	// object instance error correction
    				selectedacct = (Account) ctrdrAcct.SelectedItem;
                    selectedacct.PositionUpdate += new PositionUpdateEventHandler(positionchangedHandler);
    					}
    
    		}
            protected override void OnBarUpdate()
            {
    						if(Historical) return;
            }
    		private void positionchangedHandler(object sender,EventArgs e)//state-------------------------------mypositionChanged-----------------------
    		{
    		DoSomething();
    		}
    		private void DoSomething()
    		{
    		
    			try{
    				if(selectedacct.Positions.FindByInstrument(Instrument).MarketPosition == MarketPosition.Short)
    				{
    				DrawTextFixed("Tag","SHORT",TextPosition.TopRight);
    				}
    				if(selectedacct.Positions.FindByInstrument(Instrument).MarketPosition == MarketPosition.Long)
    				{
    				DrawTextFixed("Tag","LONG",TextPosition.TopRight);
    				}
    
    			}
    			catch// = FLAT
    			{
    			DrawTextFixed("Tag","FLAT",TextPosition.TopRight);
    			}
    		}
        }
    }
    
    #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 PositionMonitor1[] cachePositionMonitor1 = null;
    
            private static PositionMonitor1 checkPositionMonitor1 = new PositionMonitor1();
    
            /// <summary>
            /// Enter the description of your new custom indicator here
            /// </summary>
            /// <returns></returns>
            public PositionMonitor1 PositionMonitor1()
            {
                return PositionMonitor1(Input);
            }
    
            /// <summary>
            /// Enter the description of your new custom indicator here
            /// </summary>
            /// <returns></returns>
            public PositionMonitor1 PositionMonitor1(Data.IDataSeries input)
            {
                if (cachePositionMonitor1 != null)
                    for (int idx = 0; idx < cachePositionMonitor1.Length; idx++)
                        if (cachePositionMonitor1[idx].EqualsInput(input))
                            return cachePositionMonitor1[idx];
    
                lock (checkPositionMonitor1)
                {
                    if (cachePositionMonitor1 != null)
                        for (int idx = 0; idx < cachePositionMonitor1.Length; idx++)
                            if (cachePositionMonitor1[idx].EqualsInput(input))
                                return cachePositionMonitor1[idx];
    
                    PositionMonitor1 indicator = new PositionMonitor1();
                    indicator.BarsRequired = BarsRequired;
                    indicator.CalculateOnBarClose = CalculateOnBarClose;
    #if NT7
                    indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256;
                    indicator.MaximumBarsLookBack = MaximumBarsLookBack;
    #endif
                    indicator.Input = input;
                    Indicators.Add(indicator);
                    indicator.SetUp();
    
                    PositionMonitor1[] tmp = new PositionMonitor1[cachePositionMonitor1 == null ? 1 : cachePositionMonitor1.Length + 1];
                    if (cachePositionMonitor1 != null)
                        cachePositionMonitor1.CopyTo(tmp, 0);
                    tmp[tmp.Length - 1] = indicator;
                    cachePositionMonitor1 = 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.PositionMonitor1 PositionMonitor1()
            {
                return _indicator.PositionMonitor1(Input);
            }
    
            /// <summary>
            /// Enter the description of your new custom indicator here
            /// </summary>
            /// <returns></returns>
            public Indicator.PositionMonitor1 PositionMonitor1(Data.IDataSeries input)
            {
                return _indicator.PositionMonitor1(input);
            }
        }
    }
    
    // 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.PositionMonitor1 PositionMonitor1()
            {
                return _indicator.PositionMonitor1(Input);
            }
    
            /// <summary>
            /// Enter the description of your new custom indicator here
            /// </summary>
            /// <returns></returns>
            public Indicator.PositionMonitor1 PositionMonitor1(Data.IDataSeries input)
            {
                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.PositionMonitor1(input);
            }
        }
    }
    #endregion
    Attached Files

    #2
    Hello Mindset,

    Not sure exactly what you are trying to figure out. Are you trying to use the ComboBox or display this inside of the chart as well?
    JCNinjaTrader Customer Service

    Comment


      #3
      Just trying to grab the info from position update on the selected acct.
      ie once I have gone long - the text says long. Sounds and should be really simple.
      It's just an event firing thing which works but gives me this object instance error and hence some strange behaviour.

      Comment


        #4
        Originally posted by Mindset View Post
        Just trying to grab the info from position update on the selected acct.
        ie once I have gone long - the text says long. Sounds and should be really simple.
        It's just an event firing thing which works but gives me this object instance error and hence some strange behaviour.
        Post the error please.

        Comment


          #5
          Hello Mindset,

          Thanks for the information.

          If you can post the error message like sledge suggested this may help.
          JCNinjaTrader Customer Service

          Comment


            #6
            error

            Error on calling 'OnStartUp' method for indicator 'positionmonitorforum': Object reference not set to an instance of an object.

            Comment


              #7
              Hello Mindset,

              This is referring to a different Indicator than what you have posted.

              With that said, you may want to use a Try Catch statement around your code in OnStartUp to try to catch this error. Note when grabbing objects like this it is always a good to have a "null" check as well.

              You may try something like:

              Code:
              protected override void OnStartUp()
              {	
              	try
              	{
              		ctrdrAcct = (ComboBox)ChartControl.Controls["pnlChartTrader"].Controls["ctrChartTraderControl"].Controls["cboAccount"];	// object instance error correction
              		selectedacct = (Account) ctrdrAcct.SelectedItem;
                              selectedacct.PositionUpdate += new PositionUpdateEventHandler(positionchangedHandler);
              	}
              	catch (Exception e)
              	{		
              		// Submits an entry into the Control Center logs to inform the user of an error
              		Log("Error in "+this.Name+" : "+e.ToString(), LogLevel.Error);
              				
              		if(ctrdrAcct == null || selectedacct == null)
              			Print("its null");
              		else
              		{
              			Print(ctrdrAcct.ToString());
              			Print(selectedacct.ToString());
              		}
              	}
              }
              JCNinjaTrader Customer Service

              Comment


                #8
                Thanks for the pointers JC

                I now have a sort of beta type of code - it works fine but still produces these errors upon NT opening and connecting.

                On opening NT
                ERROR IN : System.NullReferenceException: Object reference not set to an instance of an object.
                at NinjaTrader.Indicator.positionmonitorforum.OnBarUp date()
                its null
                Error on calling 'OnBarUpdate' method for indicator 'positionmonitorforum' on bar 0: Object reference not set to an instance of an object.

                on connection

                Error on calling 'OnTermination' method for indicator 'positionmonitorforum': Object reference not set to an instance of an object.

                I know that the line

                Code:
                                selectedacct.PositionUpdate += new PositionUpdateEventHandler(positionchangedHandler);
                is producing the error in OnStartUp and obviously it's reciprocal in OnTermination

                but I don't know why

                I have adapted your log error to print as I find it easier. Here is the current code I have got to work.



                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;
                using System.Windows.Forms;
                using System.Collections.Generic;
                
                #endregion
                
                namespace NinjaTrader.Indicator
                {
                
                    [Description("Enter the description of your new custom indicator here")]
                    public class positionmonitorforum : Indicator
                    {
                		private ComboBox ctrdrAcct;
                		private Account selectedacct;	
                		bool inposition = false;
                		private List <string> acctlist = new List<string>();
                		private bool resetct = false;
                		string tradingacct = string.Empty;
                
                
                        protected override void Initialize()
                        {
                		            Overlay = true;
                					CalculateOnBarClose = false;
                        }
                		protected override void OnTermination()
                		{
                		selectedacct.PositionUpdate -= new PositionUpdateEventHandler(positionchangedHandler);
                		}
                		
                	
                        protected override void OnBarUpdate()
                        {
                			try
                			{
                				ctrdrAcct = (ComboBox)ChartControl.Controls["pnlChartTrader"].Controls["ctrChartTraderControl"].Controls["cboAccount"];	// object instance error correction
                				selectedacct = (Account) ctrdrAcct.SelectedItem;
                                selectedacct.PositionUpdate += new PositionUpdateEventHandler(positionchangedHandler);
                			}
                			catch(Exception e)
                				{
                					Print("ERROR IN "+this.Name+" : "+e.ToString());	
                					if(ctrdrAcct == null || selectedacct == null)
                					Print("its null");
                				}
                			tradingacct = ChartControl.Controls["pnlChartTrader"].Controls["ctrChartTraderControl"].Controls["cboAccount"].Name.ToString();
                			foreach (Account item in ctrdrAcct.Items)
                					{
                						acctlist.Add(item.Name);
                					}
                	if(!inposition)
                	
                		DrawTextFixed("Tag","FLAT",TextPosition.TopRight);
                				DrawTextFixed("Tag1",selectedacct.Name.ToString(),TextPosition.TopLeft);				
                				
                        }
                		private void positionchangedHandler(object sender,EventArgs e)//positionChanged
                		{
                		DoSomething();
                		}
                		private void DoSomething()
                		{
                		
                			try{
                				if(selectedacct.Positions.FindByInstrument(Instrument).MarketPosition == MarketPosition.Short)
                				{
                				DrawTextFixed("Tag","SHORT",TextPosition.TopRight);
                									inposition = true;
                									resetct = true;
                
                				}
                				if(selectedacct.Positions.FindByInstrument(Instrument).MarketPosition == MarketPosition.Long)
                				{
                				DrawTextFixed("Tag","LONG",TextPosition.TopRight);
                									inposition = true;
                									resetct = true;
                
                				}
                
                			}
                			catch// = FLAT
                			{
                			if(resetct)
                			{	
                			DrawTextFixed("Tag","FLAT",TextPosition.TopRight);
                			inposition = false;
                			resetct = false;
                
                			}
                	
                			}
                		}
                    }
                }

                Comment


                  #9
                  Oh I must be tired or useless - one or the other!
                  I am now getting multiple lists of accounts. It's too late for me I will go to bed and try again tomorrow.

                  Comment


                    #10
                    Hello Mindset,

                    You may want to put the Try Catch statement around the OnBarUpdate() to help with this. Also, include a check for "null" for ChartControl in OnBarUpdate() and selectedacct in OnTermination().
                    JCNinjaTrader Customer Service

                    Comment


                      #11
                      Thanks JC

                      Someone has kindly given me their indicator which solves the problem in a different way. Unfortunately they don't want me to share the code on a forum.

                      Thanks for the support though!!

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by traderqz, Today, 12:06 AM
                      5 responses
                      8 views
                      0 likes
                      Last Post NinjaTrader_Gaby  
                      Started by Mongo, Today, 11:05 AM
                      2 responses
                      7 views
                      0 likes
                      Last Post Mongo
                      by Mongo
                       
                      Started by guillembm, Today, 11:25 AM
                      0 responses
                      3 views
                      0 likes
                      Last Post guillembm  
                      Started by Tim-c, Today, 10:58 AM
                      1 response
                      3 views
                      0 likes
                      Last Post NinjaTrader_Jesse  
                      Started by traderqz, Yesterday, 09:06 AM
                      4 responses
                      27 views
                      0 likes
                      Last Post traderqz  
                      Working...
                      X