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

BarsRequest variable scope

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

    BarsRequest variable scope

    How to access variables data outside the scope of BarsRequest.Request: see code sample

    Code:
    List<double> _Closes = new List<double>(); 
    	_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;
    			      }
    				 
    				  for (int i = 0; i < bars.Bars.Count; i++)
    			      {
    			        // Output the bars
    					  _Closes.Add(bars.Bars.GetClose(i));
    			      }
    				  
    				 [COLOR="Red"] [B]// This return the correct count[/B][/COLOR]
    				  NinjaTrader.Code.Output.Process(this.Time[0].ToShortDateString()  + " =>Count Within: " + [COLOR="red"]_Closes.Count[/COLOR] ,PrintTo.OutputTab1);
    
    				  
    		      // 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);
    				
    	    		}));
    
    [COLOR="red"][B]//However this is always null[/B][/COLOR]
     NinjaTrader.Code.Output.Process(this.Time[0].ToShortDateString()  + " =>Count Without: " +[COLOR="Red"] _Closes.Count[/COLOR] ,PrintTo.OutputTab1);

    Is there to wait for for BarsRequest.Request to complete before executing any other code?

    #2
    Hello eebene,

    That is correct, BarsRequest.Request() is synchronous method call and will complete before any code after this call is run.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hi ChelseaB,

      It appears then that BarsRequest.Request() is misbehaving, could you check to see that is not a bug? I could show you the behavior.

      Comment


        #4
        Hello eebene,

        Thank you for your response.

        Please do provide us more information or a specific use case we may reproduce what you are trying to detail.

        Comment


          #5
          BarsRequest variable scope

          Hi Patrick,

          Sure please see the attached image.

          Shouldn't the results displayed on NinjaScript Ouput been inversed, based on the code seen on NinjaScript Editor?
          Attached Files

          Comment


            #6
            Hello eebene,

            If you are using the OnBarUpdate() method for your BarsRequest.Update you could use the following:
            Code:
            		private void OnBarUpdate(object sender, BarsUpdateEventArgs e)
            		{
            			if (State == State.DataLoaded)
            			{
            				Print("BarsRequest Complete");
            			}
            		}

            Comment


              #7
              Hi Patrick,

              I tried that and could not get it to work. Please see the attached indicator. It is meant to be used on a monthly chart. Can you please assist.
              Attached Files

              Comment


                #8
                Hello eebene,

                Thank you for your response.

                Place your print for "outside BarsRequest" in the if (State == State.DataLoaded) and test again. I suspect it is due to BarsRequest being called in OnBarUpdate().

                In addition, any specific reason for the call inside OnBarUpdate() for a Daily series back one month?

                Comment


                  #9
                  Hi Patrick, thank you for the reply.

                  Unfortunately, I couldn't get to work, as to your question:

                  The indicator will be use on Monthly charts exclusively. As a result, for all monthly bars whose highest price bar is higher than the previous month bar, and whose lowest price is lower than the previous month, I would like to know if the the highest price for the current monthly bar occurred before the lowest price of the current monthly bar. See attached image.

                  Any help would be appreciated.

                  Originally posted by NinjaTrader_PatrickH View Post
                  In addition, any specific reason for the call inside OnBarUpdate() for a Daily series back one month?
                  Attached Files
                  Last edited by eebene; 02-12-2016, 12:33 PM.

                  Comment


                    #10
                    Hello eebene,

                    Thank you for your response.

                    Have you considered just using AddDataSeries() to add the needed data?

                    Comment


                      #11
                      The solution - how to use BarsRequest within OnBarUpdate

                      Folks,

                      It appears that BarsRequest is asynchronous, therefore if used within OnBarUpdate(), before the request is completed,it move on to the next bar, so the solution is to wait for the request to completed.

                      Code:
                      BarsRequest barsRequest = new BarsRequest(this.Instrument, new DateTime(Time[0].Year, Time[0].Month, 1), Time[0]); //Monthly
                      barsRequest.BarsPeriod = new BarsPeriod() { BarsPeriodType = BarsPeriodType.Day, Value = 1 };
                      [COLOR="red"]object isBarsCompleted = null;[/COLOR]
                      
                      				
                      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;
                      	}
                      					 
                      	[COLOR="Red"]isBarsCompleted = true;[/COLOR]	
                      
                            // 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);					  					
                      }));	
                      
                      [COLOR="DarkGreen"]//Needed otherwise we move to the next bar before barsRequest.Request( is completed
                      while(isBarsCompleted == null) { System.Threading.Thread.Sleep(1); } [/COLOR]
                      Enjoy folks

                      Comment


                        #12
                        Thank you eebene, I wouldn't have figured it out without this solution.

                        Comment


                          #13
                          Originally posted by eebene View Post
                          The solution - how to use BarsRequest within OnBarUpdate

                          It appears that BarsRequest is asynchronous, therefore if used within OnBarUpdate(), before the request is completed,it move on to the next bar, so the solution is to wait for the request to completed.

                          while(isBarsCompleted == null) { System.Threading.Thread.Sleep(1); }
                          The above code in red is a really bad idea.

                          Probably.
                          Last edited by bltdavid; 11-18-2021, 11:25 PM.

                          Comment


                            #14
                            Yes, absolutely bltdavid, I have already changed it in my code.

                            Since I only need that code to run once, I changed

                            Code:
                            while(isBarsCompleted == null) { System.Threading.Thread.Sleep(1); }
                            with

                            Code:
                            if (isBarsCompleted == null) { System.Threading.Thread.Sleep(500); }
                            The while statement has frozen my software, as it can do if anything unexpected happens.
                            Last edited by RT001; 11-18-2021, 11:39 PM.

                            Comment


                              #15
                              Hello everyone,

                              I wanted to chime in on a few points:
                              • BarsRequests are asynchronous
                              • We do not recommend using while loops or System.Threading.Sleep to make NinjaTrader wait for an action to be completed (or in other words, make an asynchronous task synchronous)
                              In this kind of scenario, I would suggest either of the following:
                              • Keep track of CurrentBar indexes before the BarsRequest starts and when the BarsRequest finishes. When the BarsRequest is finished, loop back over those bar indexes and perform calculations on the data that was processed as the BarsRequest was loading, with the needed BarsRequest data
                              • Only accept/plot "valid" values that require the BarsRequest data after the BarsRequest completes
                              • If you need data loaded in a synchronous fashion, use AddDataSeries.
                              Others are welcome to share ideas for making the BarsRequest synchronous and their experiences here, but we want to be clear that it would fall out of our scope of support.
                              Last edited by NinjaTrader_Jim; 11-19-2021, 01:11 PM.
                              JimNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Christopher_R, Today, 12:29 AM
                              0 responses
                              9 views
                              0 likes
                              Last Post Christopher_R  
                              Started by sidlercom80, 10-28-2023, 08:49 AM
                              166 responses
                              2,235 views
                              0 likes
                              Last Post sidlercom80  
                              Started by thread, Yesterday, 11:58 PM
                              0 responses
                              3 views
                              0 likes
                              Last Post thread
                              by thread
                               
                              Started by jclose, Yesterday, 09:37 PM
                              0 responses
                              8 views
                              0 likes
                              Last Post jclose
                              by jclose
                               
                              Started by WeyldFalcon, 08-07-2020, 06:13 AM
                              10 responses
                              1,415 views
                              0 likes
                              Last Post Traderontheroad  
                              Working...
                              X