Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

errors in marketanalyser columns

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

    errors in marketanalyser columns

    I got these 2 errors that I don't understand. can you clarify? I have also attached my code

    Time Category Message
    5/13/2016 11:04:58 AM Default Market analyzer column 'MyStates': Error on calling 'OnMarketData' method on bar 49: Write lock may not be acquired with read lock held. This pattern is prone to deadlocks. Please ensure that read locks are released before taking a write lock. If an upgrade is necessary, use an upgrade lock in place of the read lock.

    Time Category Message
    5/13/2016 11:04:58 AM Default A hosted indicator tried to load additional data. All data must first be loaded by the hosting NinjaScript in its configure state.

    Code:
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    
    #endregion
    
    //This namespace holds MarketAnalyzerColumns in this folder and is required. Do not change it. 
    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
    	public class MyStates : MarketAnalyzerColumn
    	{
    		protected override void OnStateChange()
    		{
    			if (State == State.SetDefaults)
    			{
    				Description							= @"Enter the description for your new custom Market Analyzer Column here.";
    				Name								= "MyStates";
    				Calculate							= Calculate.OnEachTick;
    			}
    			else if (State == State.Configure)
    			{
    			}
    		}
    		protected override void OnMarketData(Data.MarketDataEventArgs marketDataUpdate)
    		{
    			if (marketDataUpdate.IsReset)
    				CurrentText =  "NO DATA";
    			else if (marketDataUpdate.MarketDataType == Data.MarketDataType.Ask)
    				CurrentValue = STSVer2().currentState[0];
    		}
    	}
    }
    Code:
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    //This namespace holds Indicators in this folder and is required. Do not change it. 
    namespace NinjaTrader.NinjaScript.Indicators
    {
    	static class bounceStates
          {
              public const string  wait4longpullback="wait4longpullback";
              public const string  watch4longbounce="watch4longbounce";
    		  public const string  wait4shortpullback="wait4shortpullback";
    		  public const string  watchforshortbounce="watchforshortbounce";
          }
    	  
    	public class STSVer2 : Indicator
    	{
    		private DateTime  first100barhigh,first100barlow,previouslast100barhigh,previouslast100barlow;
    		private bool firstLongBO, firstShortBO=false;
    		public string currentState="STARTED";
    		private Series<string> direction;
    		private Series<string> bouncestate;
    		private const string DIR_LONG ="LONG";
    		private const string  DIR_SHORT ="SHORT";
    		//const enum bounceStates{wait4longpullback=1,watch4longbounce=2, wait4shortpullback=3,watchforshortbounce};
    		protected override void OnStateChange()
    		{
    			if (State == State.SetDefaults)
    			{
    				Description							= @"Enter the description for your new custom Indicator here.";
    				Name								= "STSVer2";
    				Calculate							= Calculate.OnEachTick;
    				IsOverlay							= false;
    				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;
                    MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
    
                }
    			else if (State == State.Historical)
    		   {
    		       // Syncs a Series object to the primary bar object
    			  
    		       
    			   
    			   
    		   }
    			
                else if (State == State.Configure)
    			{
    				// Add a 5 minute Bars object - BarsInProgress index = 1 
             AddDataSeries(BarsPeriodType.Minute, 30);
    				        AddDataSeries(BarsPeriodType.Tick, 1);
    				direction = new Series<string>(BarsArray[0]);
    				bouncestate = new Series<string>(BarsArray[0]);
    				
    			}
    		}
    
    		 
    				
    		
    		protected override void OnBarUpdate()
    		{
    			//Add your custom indicator logic here
    			
                if (BarsInProgress > 0)
                    return;
    			if(CurrentBar<200)
    				return;
                try
                {
    				//Print("Got here1");
                    
    					if((CrossAbove(High,DonchianChannel(100).Upper[1],1))  && direction[0] !=DIR_LONG)
    					{
    						direction[0] =DIR_LONG;
    						bouncestate[0]=bounceStates.wait4longpullback;
    						Print(Instrument.FullName + "Got first Donchian high BO" + Times[0].ToString()+ CurrentBar);
    						
    					}
    					if((CrossBelow(Low,DonchianChannel(100).Lower[1],1)) && direction[0] !=DIR_SHORT)
    					{
    						direction[0] =DIR_SHORT;
    						Print(Instrument.FullName + "Got first Donchian low BO" + Times[0].ToString() + CurrentBar );
    						bouncestate[0]=bounceStates.wait4shortpullback;
    					}
    					Print(DateTime.Now + direction[0]);
    					if(IsFirstTickOfBar){
    						direction[0]=direction[1];
    						bouncestate[0]=bouncestate[1];
    						
    					}
    					
    					switch(bouncestate[0]){
    						case bounceStates.wait4longpullback:
    							
    							if(Closes[2][0]<Closes[1][1])
    							{
    								bouncestate[0]=bounceStates.watch4longbounce;
    							}
    								
    							
    						break;
    						case bounceStates.wait4shortpullback:
    						if(Closes[2][0]>Closes[1][1])
    							{
    								bouncestate[0]=bounceStates.watchforshortbounce;
    							}
    						break;
    						case bounceStates.watch4longbounce:
    //							if(Closes[2][0]>Closes[1][1])
    //							{
    //								bouncestate[0]=bounceStates.watchforshortbounce.ToString();
    //							}
    						break;
    						case bounceStates.watchforshortbounce:
    						break;
    					}
    					
    					
    						
    						
                        
                        switch (State)
                        {
                            case State.Historical:
                                break;
                            case State.Realtime:
                                break;
    
                        }
    
    
                   
                }
                catch (Exception eX)
                {
                    PrintTo = PrintTo.OutputTab1;
                    Print("Exception " + eX.StackTrace);
                }
    
            }
    		
    		#region Properties
    		
    
    		[Browsable(true)]
    		[XmlIgnore]
    		public Series<string> MarketDirection
    		{
    			get { return direction; }
    		}
    		
    		public Series<string> BounceState
    		{
    			get { return bouncestate; }
    		}
    		#endregion
    
    	}
    }
    
    
    #region NinjaScript generated code. Neither change nor remove.
    
    namespace NinjaTrader.NinjaScript.Indicators
    {
    	public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
    	{
    		private STSVer2[] cacheSTSVer2;
    		public STSVer2 STSVer2()
    		{
    			return STSVer2(Input);
    		}
    
    		public STSVer2 STSVer2(ISeries<double> input)
    		{
    			if (cacheSTSVer2 != null)
    				for (int idx = 0; idx < cacheSTSVer2.Length; idx++)
    					if (cacheSTSVer2[idx] != null &&  cacheSTSVer2[idx].EqualsInput(input))
    						return cacheSTSVer2[idx];
    			return CacheIndicator<STSVer2>(new STSVer2(), input, ref cacheSTSVer2);
    		}
    	}
    }
    
    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
    	public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
    	{
    		public Indicators.STSVer2 STSVer2()
    		{
    			return indicator.STSVer2(Input);
    		}
    
    		public Indicators.STSVer2 STSVer2(ISeries<double> input )
    		{
    			return indicator.STSVer2(input);
    		}
    	}
    }
    
    namespace NinjaTrader.NinjaScript.Strategies
    {
    	public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
    	{
    		public Indicators.STSVer2 STSVer2()
    		{
    			return indicator.STSVer2(Input);
    		}
    
    		public Indicators.STSVer2 STSVer2(ISeries<double> input )
    		{
    			return indicator.STSVer2(input);
    		}
    	}
    }
    
    #endregion

    #2
    I think I had a bug which I fixed. but I am still not able to get rid of the NT errors
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;

    #endregion

    //This namespace holds MarketAnalyzerColumns in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
    public class MyStates : MarketAnalyzerColumn
    {
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Market Analyzer Column here.";
    Name = "MyStates";
    Calculate = Calculate.OnEachTick;
    }
    else if (State == State.Configure)
    {
    }
    }
    protected override void OnMarketData(Data.MarketDataEventArgs marketDataUpdate)
    {
    if (marketDataUpdate.IsReset)
    CurrentText = "NO DATA";
    else if (marketDataUpdate.MarketDataType == Data.MarketDataType.Ask)
    CurrentText = STSVer2().BounceState[0];
    }
    }
    }

    Comment


      #3
      Hello junkone,

      It looks like you are calling an indicator from a MarketAnalyzer column.
      The issue here is that there is not a dataseries created that can be supplied to the indicator call.

      You will need to make a BarsRequest and from the bars update method get the bars object and use that as the input series for the call to the indicator.

      protected void CustomBarUpdate(object sender, BarsUpdateEventArgs e)
      {
      Bars theBars = sender as Bars;
      Print(SMA(theBars, 14)[0]);
      }

      Attached is an example I have created previously that shows how to do a BarsRequest in a Market Analyzer column.

      Does this script need to be a Market Analyzer column? From the code, it looks like this script only calls an indicator. This could remain an indicator and be added to the Market Analyzer as an indicator column.
      Attached Files
      Chelsea B.NinjaTrader Customer Service

      Comment


        #4
        I still get a internal error after fixing the code
        you will notice that I created bar subscription and am calculating the values based on the subscribed bars.
        when I print the values, I get error
        A hosted indicator tried to load additional data. All data must first be loaded by the hosting NinjaScript in its configure state.
        A hosted indicator tried to load additional data. All data must first be loaded by the hosting NinjaScript in its configure state

        Code:
        #region Using declarations
        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.ComponentModel.DataAnnotations;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using System.Windows;
        using System.Windows.Input;
        using System.Windows.Media;
        using System.Xml.Serialization;
        using NinjaTrader.Cbi;
        using NinjaTrader.Gui;
        using NinjaTrader.Gui.Chart;
        using NinjaTrader.Gui.SuperDom;
        using NinjaTrader.Data;
        using NinjaTrader.NinjaScript;
        using NinjaTrader.Core.FloatingPoint;
        
        #endregion
        
        //This namespace holds MarketAnalyzerColumns in this folder and is required. Do not change it. 
        namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
        {
        	public class MyStates : MarketAnalyzerColumn
        	{
        		private BarsRequest		barsRequest;
        		Cbi.Instrument			primaryInstrument;
        		int primaryVolume ;
        		
        		protected override void OnStateChange()
        		{
        			try{
        			if (State == State.SetDefaults)
        			{
        				Description							= @"Enter the description for your new custom Market Analyzer Column here.";
        				Name								= "MyStates";
        				Calculate							= Calculate.OnEachTick;
        			}
        			else if (State == State.Historical)
        			{
        				primaryInstrument = Cbi.Instrument.GetInstrument(Instrument.FullName);			 
        				
        				if (primaryInstrument == null)
        					return;
        			    BarsPeriod barsPeriod = new BarsPeriod() { BarsPeriodType = BarsPeriodType.Minute, Value = 1 };
        				barsRequest = new BarsRequest(primaryInstrument,200)				 
        					{
        						BarsPeriod = barsPeriod,
        						TradingHours = TradingHours.Get("Default 24 x 7")
        					};
        				 
        				
        				barsRequest.Update+=OnBarUpdate;
        				barsRequest.Request(new Action<BarsRequest, ErrorCode, string>((bars, errorCode, errorMessage) =>
        				{
        					if (errorCode != ErrorCode.NoError)
        					{
        						// Handle any errors in requesting bars here
        						NinjaTrader.Code.Output.Process(string.Format("Error on requesting bars: {0}, {1}",
        								errorCode, errorMessage), PrintTo.OutputTab1);
        						return;
        					}
        
        					// Output the bars we requested. Note: The last returned bar may be a currently in-progress bar
        					for (int i = 0; i < bars.Bars.Count; i++)
        						if (i == bars.Bars.Count - 1)
        							  primaryVolume = (int)bars.Bars.GetVolume(i);
        						
        					// If requesting real-time bars, but there are currently no connections
        					lock (Connection.Connections)
        						if (Connection.Connections.FirstOrDefault() == null)
        							NinjaTrader.Code.Output.Process("Real-Time Bars: Not connected.", PrintTo.OutputTab1);
        				}));
        			}
        			else if (State == State.Terminated)
        			{
        				if (barsRequest != null)
        					barsRequest.Update -= OnBarUpdate;
        
        				
        			}
        			}
                    catch (Exception eX)
                    {
                        PrintTo = PrintTo.OutputTab1;
                        Print("Exception " + eX.StackTrace);
                    }
        		}
        		
        		// This method is fired on real-time bar events
        private void OnBarUpdate(object sender, BarsUpdateEventArgs e)
        {
           /* Depending on the BarsPeriod type of your barsRequest you can have situations where more than one bar is
            updated by a single tick. Be sure to process the full range of updated bars to ensure you did not miss a bar. */
         try{
           // Output bar information on each tick
           for (int i = e.MinIndex; i <= e.MaxIndex; i++)
           {
             // Processing every single tick
             NinjaTrader.Code.Output.Process(string.Format("Time: {0} Open: {1} High: {2} Low: {3} Close: {4}",
                                             e.BarsSeries.GetTime(i),
                                             e.BarsSeries.GetOpen(i),
                                             e.BarsSeries.GetHigh(i),
                                             e.BarsSeries.GetLow(i),
                                             e.BarsSeries.GetClose(i)), PrintTo.OutputTab1);
           }
           Bars theBars = sender as Bars;
           if (theBars.Instrument.FullName == primaryInstrument.FullName){
        	   Print(STSVer2(theBars).BounceState[0] +   STSVer2(theBars).MarketDirection[0] );
           }			 
           
           }
                    catch (Exception eX)
                    {
                        PrintTo = PrintTo.OutputTab1;
                        Print("Exception " + eX.StackTrace);
                    }
        }
        
        //		protected override void OnMarketData(Data.MarketDataEventArgs marketDataUpdate)
        //		{
        //			if (marketDataUpdate.IsReset)
        //				CurrentText =  "NO DATA";
        //			else if (marketDataUpdate.MarketDataType == Data.MarketDataType.Ask)
        //				CurrentText  = STSVer2().BounceState[0];
        //		}
        		
        		
        	}
        }
        Last edited by junkone; 05-14-2016, 09:14 AM.

        Comment


          #5
          Hi junkone,

          I think Chelsea was suggesting to try and make an indicator instead of a MA column (if it is possible to achieve your objectives, or use the existing indicator you are calling), and then load the indicator as a 'column' into the MA. I also took that approach as I found this was better because you can use OnBarUpdate as opposed to OnMarketData and for me was more familiar.

          For that error 'All data must first be loaded by the hosting NinjaScript in its configure state', try adding a bool which switches to true in State.DataLoaded and checking against that before running your other logic. This worked for me (I had an indicator loaded in the MA with multiple data series and I was getting that same error intermittently).

          Cheers,
          Shane
          Last edited by ShaneAU; 05-14-2016, 04:21 PM.

          Comment


            #6
            I think I am doing exactly as identified by Chelsea. I have a custom OnBarUpdate which processes the bars. infact I have checked if the state ==State.realtime which implies that all data is already loaded. it stops with the same error. I have a feeling that its a bug at this state. infact, I printed the barcount and it starts with 200 and when it moves to 201, something happens in the processing that causes this error.
            #region Using declarations
            using System;
            using System.Collections.Generic;
            using System.ComponentModel;
            using System.ComponentModel.DataAnnotations;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using System.Windows;
            using System.Windows.Input;
            using System.Windows.Media;
            using System.Xml.Serialization;
            using NinjaTrader.Cbi;
            using NinjaTrader.Gui;
            using NinjaTrader.Gui.Chart;
            using NinjaTrader.Gui.SuperDom;
            using NinjaTrader.Data;
            using NinjaTrader.NinjaScript;
            using NinjaTrader.Core.FloatingPoint;

            #endregion

            //This namespace holds MarketAnalyzerColumns in this folder and is required. Do not change it.
            namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
            {
            public class MyStates : MarketAnalyzerColumn
            {
            private BarsRequest barsRequest;
            Cbi.Instrument primaryInstrument;
            int primaryVolume ;

            protected override void OnStateChange()
            {
            try{
            if (State == State.SetDefaults)
            {
            Description = @"Enter the description for your new custom Market Analyzer Column here.";
            Name = "MyStates";
            Calculate = Calculate.OnEachTick;
            }
            else if (State == State.Historical)
            {
            primaryInstrument = Cbi.Instrument.GetInstrument(Instrument.FullName);

            if (primaryInstrument == null)
            return;
            BarsPeriod barsPeriod = new BarsPeriod() { BarsPeriodType = BarsPeriodType.Minute, Value = 1 };
            barsRequest = new BarsRequest(primaryInstrument,200)
            {
            BarsPeriod = barsPeriod,
            TradingHours = TradingHours.Get("Default 24 x 7")
            };


            barsRequest.Update+=OnBarUpdate;
            barsRequest.Request(new Action<BarsRequest, ErrorCode, string>((bars, errorCode, errorMessage) =>
            {
            if (errorCode != ErrorCode.NoError)
            {
            // Handle any errors in requesting bars here
            NinjaTrader.Code.Output.Process(string.Format("Err or on requesting bars: {0}, {1}",
            errorCode, errorMessage), PrintTo.OutputTab1);
            return;
            }

            // Output the bars we requested. Note: The last returned bar may be a currently in-progress bar
            for (int i = 0; i < bars.Bars.Count; i++)
            if (i == bars.Bars.Count - 1)
            primaryVolume = (int)bars.Bars.GetVolume(i);

            // If requesting real-time bars, but there are currently no connections
            lock (Connection.Connections)
            if (Connection.Connections.FirstOrDefault() == null)
            NinjaTrader.Code.Output.Process("Real-Time Bars: Not connected.", PrintTo.OutputTab1);
            }));
            }
            else if (State == State.Terminated)
            {
            if (barsRequest != null)
            barsRequest.Update -= OnBarUpdate;
            }
            }
            catch (Exception eX)
            {
            PrintTo = PrintTo.OutputTab1;
            Print("Exception " + eX.StackTrace);
            }
            }


            private void OnBarUpdate(object sender, BarsUpdateEventArgs e)
            {

            try{
            if (State == State.Realtime){
            Bars theBars = sender as Bars;
            Print(theBars.GetTime(0).ToString() + " count " + theBars.Count);
            if (theBars.Instrument.FullName == primaryInstrument.FullName && theBars.Count>200){
            Print(STSVer2(theBars).BounceState[0] + STSVer2(theBars).MarketDirection[0] );
            }
            }
            }
            catch (Exception eX)
            {
            PrintTo = PrintTo.OutputTab1;
            Print("Exception " + eX.StackTrace);
            }
            }

            }
            }
            [CODE]#region Using declarations
            using System;
            using System.Collections.Generic;
            using System.ComponentModel;
            using System.ComponentModel.DataAnnotations;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using System.Windows;
            using System.Windows.Input;
            using System.Windows.Media;
            using System.Xml.Serialization;
            using NinjaTrader.Cbi;
            using NinjaTrader.Gui;
            using NinjaTrader.Gui.Chart;
            using NinjaTrader.Gui.SuperDom;
            using NinjaTrader.Data;
            using NinjaTrader.NinjaScript;
            using NinjaTrader.Core.FloatingPoint;
            using NinjaTrader.NinjaScript.DrawingTools;
            #endregion

            //This namespace holds Indicators in this folder and is required. Do not change it.
            namespace NinjaTrader.NinjaScript.Indicators
            {
            static class bounceStates
            {
            public const string wait4longpullback="wait4longpullback";
            public const string watch4longbounce="watch4longbounce";
            public const string wait4shortpullback="wait4shortpullback";
            public const string watchforshortbounce="watchforshortbounce";
            }

            public class STSVer2 : Indicator
            {
            private DateTime first100barhigh,first100barlow,previouslast100barh igh,previouslast100barlow;
            private bool firstLongBO, firstShortBO=false;
            public string currentState="STARTED";
            private Series<string> direction;
            private Series<string> bouncestate;
            private const string DIR_LONG ="LONG";
            private const string DIR_SHORT ="SHORT";
            //const enum bounceStates{wait4longpullback=1,watch4longbounce= 2, wait4shortpullback=3,watchforshortbounce};
            protected override void OnStateChange()
            {
            if (State == State.SetDefaults)
            {
            Description = @"Enter the description for your new custom Indicator here.";
            Name = "STSVer2";
            Calculate = Calculate.OnEachTick;
            IsOverlay = false;
            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;
            MaximumBarsLookBack = MaximumBarsLookBack.Infinite;

            }
            else if (State == State.Historical)
            {
            // Syncs a Series object to the primary bar object




            }

            else if (State == State.Configure)
            {
            // Add a 5 minute Bars object - BarsInProgress index = 1
            AddDataSeries(BarsPeriodType.Minute, 5);
            AddDataSeries(BarsPeriodType.Tick, 1);
            direction = new Series<string>(BarsArray[0]);
            bouncestate = new Series<string>(BarsArray[0]);

            }
            }




            protected override void OnBarUpdate()
            {
            if(State!=State.Historical || State!=State.Realtime)
            return;

            //Add your custom indicator logic here

            if (BarsInProgress > 0)
            return;
            if(CurrentBar<200)
            return;
            try
            {
            //Print("Got here1");

            if((CrossAbove(High,DonchianChannel(100).Upper[1],1)) && direction[0] !=DIR_LONG)
            {
            direction[0] =DIR_LONG;
            bouncestate[0]=bounceStates.wait4longpullback;
            Print(Instrument.FullName + "Got first Donchian high BO" + Times[0].ToString()+ CurrentBar);

            }
            if((CrossBelow(Low,DonchianChannel(100).Lower[1],1)) && direction[0] !=DIR_SHORT)
            {
            direction[0] =DIR_SHORT;
            Print(Instrument.FullName + "Got first Donchian low BO" + Times[0].ToString() + CurrentBar );
            bouncestate[0]=bounceStates.wait4shortpullback;
            }
            Print(DateTime.Now + Instrument.FullName + direction[0] + bouncestate[0] + "BarsInProgress" + BarsInProgress);
            if(IsFirstTickOfBar){
            direction[0]=direction[1];
            bouncestate[0]=bouncestate[1];

            }

            switch(bouncestate[0]){
            case bounceStates.wait4longpullback:

            if(Lows[2][0]<Lows[1][1])
            {
            bouncestate[0]=bounceStates.watch4longbounce;
            // keep an eye for bounce play
            }


            break;
            case bounceStates.wait4shortpullback:
            if(Highs[2][0]>Highs[1][1])
            {
            bouncestate[0]=bounceStates.watchforshortbounce;
            // keep an eye for bounce play
            }
            break;
            case bounceStates.watch4longbounce:
            if(Highs[2][0]>Highs[1][1])
            {
            bouncestate[0]=bounceStates.wait4longpullback;
            // should have entered into trade and if trade closed watch for pullback
            }
            break;
            case bounceStates.watchforshortbounce:
            if(Lows[2][0]<Lows[1][1])
            {
            bouncestate[0]=bounceStates.wait4shortpullback;
            // should have entered into trade and if trade closed watch for pullback
            }
            break;
            }





            switch (State)
            {
            case State.Historical:
            break;
            case State.Realtime:
            break;

            }



            }
            catch (Exception eX)
            {
            PrintTo = PrintTo.OutputTab1;
            Print("Exception " + eX.StackTrace);
            }

            }

            #region Properties


            [Browsable(true)]
            [XmlIgnore]
            public Series<string> MarketDirection
            {
            get { return direction; }
            }

            public Series<string> BounceState
            {
            get { return bouncestate; }
            }
            #endregion

            }
            }
            Last edited by junkone; 05-15-2016, 08:04 AM.

            Comment


              #7
              Hi junkone,

              As I am not able to test your script, I have created a simple script to show how to use a bars request and provide the bars object to an indicator call. I have exported this to make this easy for you to import and test on your end. (Tools -> Export -> NinjaScript...)

              To import a NinjaScript into NinjaTrader 8 do the following:
              1. Download the script to your desktop, keep it in the compressed .zip file.
              2. From the Control Center window select Tools -> Import -> NinjaScript...
              3. Click the Desktop icon on the left to navigate to the desktop
              4. Select the downloaded .zip file -> then click Open
              5. NinjaTrader will then confirm if the import has been successful.


              Critical *Note that on any files that say "File already exists on your PC" that start with an "@" symbol are the ones that came preloaded inside of NinjaTrader so you would say "No" so that you do not override those files.
              Attached Files
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                i don't see why you have to go through all that trouble to plot sma on market analyzer. the onbarupdate can be overridden and plotted much more simply. I think the problem with the cases that I had earlier was due to the fact that I am using tick and minute bars in my indicator and when I called it from market analyser, there is no ticks bars to process it. I cannot figure out why NT will throw the error and where it is throwing the error.
                I am attaching a simplier code to prove that we don't need to create bars array to plot simple indicators in market analyser.
                #region Using declarations
                using System;
                using System.Collections.Generic;
                using System.ComponentModel;
                using System.ComponentModel.DataAnnotations;
                using System.Linq;
                using System.Text;
                using System.Threading.Tasks;
                using System.Windows;
                using System.Windows.Input;
                using System.Windows.Media;
                using System.Xml.Serialization;
                using NinjaTrader.Cbi;
                using NinjaTrader.Gui;
                using NinjaTrader.Gui.Chart;
                using NinjaTrader.Gui.SuperDom;
                using NinjaTrader.Data;
                using NinjaTrader.NinjaScript;
                using NinjaTrader.Core.FloatingPoint;

                #endregion

                //This namespace holds MarketAnalyzerColumns in this folder and is required. Do not change it.
                namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
                {
                public class MyCustomMarketAnalyzerColumn : MarketAnalyzerColumn
                {
                protected override void OnStateChange()
                {
                if (State == State.SetDefaults)
                {
                Description = @"Enter the description for your new custom Market Analyzer Column here.";
                Name = "MyCustomMarketAnalyzerColumn";
                Calculate = Calculate.OnEachTick;
                }
                else if (State == State.Configure)
                {
                }
                }
                protected override void OnBarUpdate()
                {
                try{

                CurrentText = string.Format("SMA(14): {0}", SMA(14)[0].ToString());
                }
                catch (Exception eX)
                {
                PrintTo = PrintTo.OutputTab1;
                Print("Exception " + eX.StackTrace);
                }
                }

                }
                }
                Finally, I still have a problem with the code posted yesterday and need to know how to fix it.

                Comment


                  #9
                  Hello junkone,

                  Thank you for the sample.

                  I clarified with our development that a bar object does get created with a Market Analyzer column.

                  Is the indicator being called adding a secondary data series?


                  As a tip, to export a NinjaTrader 8 NinjaScript do the following:
                  1. Click Tools -> Export -> NinjaScript...
                  2. Click the 'add' link -> check the box(es) for the script(s) you want to include
                  3. Click the 'Export' button
                  4. Enter a unique name for the file in the value for 'File name:'
                  5. Choose a save location -> click Save
                  6. Click OK to clear the export location message

                  By default your exported file will be in the following location:
                  • (My) Documents/NinjaTrader 8/bin/Custom/ExportNinjaScript/<export_file_name.zip>


                  Below is a link to the help guide on Exporting NinjaScripts.
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    I have the similar problem when I load a strategy. I will send my code and I can see that the error is logged in Ninjatrader code that I cannot touch.

                    Comment


                      #11
                      Hello junkone,

                      This likely means that an error is being hit in the indicator and likely is not specific to the market analyzer.

                      If you are not able to post the script, this is likely because the script has a lot of code you would like to keep private.

                      Instead, create a simple example script that only includes the code to reproduce the behavior. By only including the code that causes the behavior this will allow me to quickly view the code and see the issue without having to debug your script which is not a service that is provided by NinjaTrader support.

                      Please create a sample that demonstrates the behavior and does not include any code that is not absolutely necessary to reproduce the behavior.

                      Also, you can use prints to find out which line is causing the error. Have you added any prints to your code to debug the code?
                      May I have the print and the output from the debugging?
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        I got the answer via email from NT support and want to reiterate the solution as it will help others in same situation.
                        I have both tick and 5 minute bars in my indicator. so if I want to call it from my strategy or market analyser, I need to add the tick and 5 minute bar in the strategy and market analyser before calling the indicator.

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by Aviram Y, Today, 05:29 AM
                        0 responses
                        1 view
                        0 likes
                        Last Post Aviram Y  
                        Started by quantismo, 04-17-2024, 05:13 PM
                        3 responses
                        25 views
                        0 likes
                        Last Post NinjaTrader_Gaby  
                        Started by ScottWalsh, 04-16-2024, 04:29 PM
                        7 responses
                        34 views
                        0 likes
                        Last Post NinjaTrader_Gaby  
                        Started by cls71, Today, 04:45 AM
                        0 responses
                        6 views
                        0 likes
                        Last Post cls71
                        by cls71
                         
                        Started by mjairg, 07-20-2023, 11:57 PM
                        3 responses
                        216 views
                        1 like
                        Last Post PaulMohn  
                        Working...
                        X