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

Timer to replace Thread.Sleep()

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

    Timer to replace Thread.Sleep()

    Hello,

    Could someone please help me with some code. I am looking to implement a timer to be used as a pause method within certain parts of my indicator and work in the same way as using Thread.Sleep() without the unsuaitable side effects. e.g One use is that I want to hold up the transition from State=DataLoaded to State=Historical to allow some code in dataloaded to fully complete before I move on to the next state.

    I've look at the code in the guide linked below however that appears specfic to starting and stoping some other methd and allowing it time to complete. I just want to use a timer and be able to insert it as a "pause" step wherever I need it, then move on to the next line of my script whatever that may be.



    The only way I can think of to make a timer work in this way is to have the script start the timer and then go into some sort of loop until the timer triggers then break; or continue; out of it? I'm not sure if this is the most effecient (or safest) way of creating a pause or how it would look as code so reaching out for some assistance.

    Thanks

    #2
    Hello b16_aln,

    Thanks for your post.

    It would not be supported to use Thread.Sleep to delay a thread, and we strictly do not recommend it. We also could not recommend a way to delay transition from historical to realtime data.

    See Performance Best Paractices - https://ninjatrader.com/support/help...tm#Performance

    If you are wanting to start a timer at start up and which then checks for your other code to be complete before executing that part of code further, this may be considered.

    My thought process is the same as yours to accomplish: 1. Indicator starts 2. Timer starts 3. Complex code is loaded 4. Timer completes, waits for code to be loaded. 5. Timer restarts if code is not loaded 6. When code is loaded timer then sets a variable allowing the rest of the script to process what is loaded from the complex part.

    To get around an issue with having the complex code fully loaded after the script transitions to realtime data, you could keep track of the CurrentBar index, and then when the complex code is loaded, process all of the data on the chart up until that point.

    I look forward to assisting.
    Attached Files
    JimNinjaTrader Customer Service

    Comment


      #3
      Thanks Jim.

      I'm thinking that on entering State=State.Historical, the first bit of code could have a bool controlled by the timer method that switches it to true on timer trigger but while it' false it re-sets the state to historical causing a loop on entry to state historical until the bool (timer) is true. Could that work?

      else if(State == State.Historical)
      {
      if(timerTriggered==false
      {
      TimerPauseMethod()
      SetState(State.Historical)
      }
      }

      Comment


        #4
        Hello b16_aln,

        SetState will ignore going back to a previous state so I could not guarantee that that will work.do no think that will be a way forward. Preliminary testing on my end to restart a state is showing this would not be feasible.

        I would suggest moving forward with the suggestion to track which bar this code is ready, and then to process all bars in the data series accordingly to get "caught up."
        JimNinjaTrader Customer Service

        Comment


          #5
          Thanks Jim,

          I'm struggling to get my head round your suggestion. I'm fairly new to coding.

          Would it be possible to use the delayed timer event in historical to switch a proceedBool to true and simply have if(proceedBool==false) return; as the first line in ONBARUPDATE, that way the onbarupdate code won;t get rununtil the timer triggered in historical finishes?

          EDIT UODATE: Couldn;t get that to work either.
          Last edited by b16_aln; 11-26-2020, 09:48 AM.

          Comment


            #6
            Would it be safe to use Thread.Sleep on a dispatcher thread? That way it won;t hold up the UI thread which I imagine is where the problems begin.

            Comment


              #7
              So the only solution I can come up with that doesn;t appear to block the UI is:

              Task.Delay(2000).Wait();

              Can you confirm that it is safe to use it and it won;t mess up the rest of NT8.

              Thanks

              Comment


                #8
                Hello b16_aln,

                There would not be any supported way to pause a NinjaTrader thread, or have NinjaTrader wait for some asynchronous code to load so it is instead handled synchronously.

                You also would not want to use Thread.Sleep in a dispatcher. This will make the thread that we are dispatching from sleep, and we don't want to put any NinjaTrader thread to sleep.

                You could either use a timer to trigger some actions after a point where you know your code is loaded, or you could consider implementing a routine in that code to loop through all bars in the data series after your code is loaded and do your historical processing there.
                JimNinjaTrader Customer Service

                Comment


                  #9
                  In case anyone else is looking for a working alternative to Thread.Sleep(). I have implemented this pause method. Set the int_delay varaible to however long you wish to pause the scipt for in milliseconds.
                  __________________________________________________ __________________________________________________ __________________________________________________ ___
                  using System.Diagnostics;

                  private void PauseIt(int _delay)
                  {
                  Stopwatch sw = new Stopwatch(); // sw cotructor
                  sw.Start(); // starts the stopwatch
                  for (int i = 0; ; i++)
                  {
                  if (i % 100000 == 0) // if in 100000th iteration (could be any other large number
                  // depending on how often you want the time to be checked)
                  {
                  sw.Stop(); // stop the time measurement
                  if (sw.ElapsedMilliseconds > _delay) // check if desired period of time has elapsed
                  {
                  break; // if more than 5000 milliseconds have passed, stop looping and return
                  // to the existing code
                  }
                  else
                  {
                  sw.Start(); // if less than 5000 milliseconds have elapsed, continue looping
                  // and resume time measurement
                  }
                  }
                  }
                  }

                  Comment


                    #10
                    Hi Everyone,
                    I would to perform the following task:

                    Wait n seconds before load a custom indicator on the chart at the start up of ninjatrader. In particular, this is necessary because the mentioned indicator execute a check on the draw object created by another custom indicator and i want to attend that the draw objects series is fully loaded.

                    Please, can you help me?

                    Thanks

                    Comment


                      #11
                      Why don't you just have the indicator check periodically e.g. once a second or whatever for the drawing objects to see if they've been added yet? Use a timer for that. Don't sleep the threads or implement a busy wait - those are regrettable solutions that lead to lots of issues down the road.
                      Bruce DeVault
                      QuantKey Trading Vendor Services
                      NinjaTrader Ecosystem Vendor - QuantKey

                      Comment


                        #12
                        Hi,
                        Yes, i think that this can be a good idea. Please, can you give me an example? How can i run the code into the indicator once time (at startup and for each bar loaded into the chart) and another time once every 30 minutes for example (and i have to re-check all the bars now)?

                        Thanks a lot

                        Comment


                          #13
                          What size bar is this? If it's only every 30 minutes you may not even need a timer. Can't you just keep track of the time you last checked, and in OnBarUpdate if ((DateTime.Now - TimeLastChecked).TotalMinutes >= 30) { DoSomething(); TimeLastChecked = DateTime.Now; }? You don't need to recheck all the bars if your only goal is to see if a drawing tool changed.
                          Bruce DeVault
                          QuantKey Trading Vendor Services
                          NinjaTrader Ecosystem Vendor - QuantKey

                          Comment


                            #14
                            Yes, 30 minutes bars. Ok; thank you!

                            Comment


                              #15
                              Well, if it's 30 minute bars and you want to check every 30 minutes, then it's even easier - just run it once per bar in OnBarUpdate with Calculate = Calculate.OnBarClose.
                              Bruce DeVault
                              QuantKey Trading Vendor Services
                              NinjaTrader Ecosystem Vendor - QuantKey

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by firefoxforum12, Yesterday, 08:53 PM
                              1 response
                              13 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by kmunroe478, Yesterday, 05:39 PM
                              2 responses
                              14 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by kevinenergy, 02-17-2023, 12:42 PM
                              115 responses
                              2,699 views
                              1 like
                              Last Post kevinenergy  
                              Started by prdecast, Today, 06:07 AM
                              1 response
                              4 views
                              0 likes
                              Last Post NinjaTrader_LuisH  
                              Started by Christopher_R, Today, 12:29 AM
                              1 response
                              14 views
                              0 likes
                              Last Post NinjaTrader_LuisH  
                              Working...
                              X