Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

OnConnectionStatusUpdate called before OnBarUpdate

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

    OnConnectionStatusUpdate called before OnBarUpdate

    In debugging my NT8 code, I found that when running a strategy in Strategy Analyzer, the OnBarUpdate code is called before OnConnectionStatusUpdate is ever called. I need to know whether I'm in a PlayBack connection or not before OnBarUpdate is called, because I need to set some variables in OnBarUpdate based on whether it's Playback or Realtime connection.

    Can you help?

    Thanks!
    Bryan
    cassb
    NinjaTrader Ecosystem Vendor - Logical Forex

    #2
    Hello Bryan,

    Thank you for writing in.

    You can create a boolean in your script that will only change to true if you are on the playback connection. Once this changes to true, OnBarUpdate() can run its logic.

    For example:
    Code:
    private bool playbackConnection = false;
    
    protected override void OnBarUpdate()
    {
         if (!playbackConnection)
              return;
    
         // do stuff
    }
    
    protected override void OnConnectionStatusUpdate(ConnectionStatusEventArgs c)
    {
         if (c.Connection.Options.Name == "Playback Connection")
              playbackConnection = true;
    }
    Please, let us know if we may be of further assistance.
    Zachary G.NinjaTrader Customer Service

    Comment


      #3
      hmm... that's not going to work in my case. Here's the code to play with:

      Code:
              private bool        PlaybackMode            = false;        // Whether we are in MarketReplay or not
              private DateTime    tradingEndDate;
      
              protected override void OnBarUpdate()
              {
                  if (Now >= tradingEndDate)        // Reset trading time start/end for next session
                  {
                      tradingBeginDate = Now.Date.Add(tradingBegin);
                      tradingEndDate = Now.Date.Add(tradingEnd);
                      if (tradingEnd < tradingBegin) tradingEndDate = tradingEndDate.AddDays(1);
                  }
              }
      
              protected override void OnConnectionStatusUpdate(ConnectionStatusEventArgs connectionStatusUpdate)
              {
                  if (connectionStatusUpdate.Connection.Options.Name == "Playback Connection") PlaybackMode = true;
                  else PlaybackMode = false;
              }
      
              // Returns the 'chart' time when called.
              private DateTime Now
              {
                  get 
                  { 
                      DateTime now;
                      if (PlaybackMode) now = NinjaTrader.Cbi.Connection.PlaybackConnection.Now;
                      else now = NinjaTrader.Core.Globals.Now;
                      if (now.Millisecond > 0)
                          now = NinjaTrader.Core.Globals.MinDate.AddSeconds((long) System.Math.Floor(now.Subtract(NinjaTrader.Core.Globals.MinDate).TotalSeconds));
                      return now;
                  }
              }
      Run this in Market Replay or in Strategy Analyzer and it will call OnBarUpdate before PlaybackMode = true.
      cassb
      NinjaTrader Ecosystem Vendor - Logical Forex

      Comment


        #4
        Hello Bryan,

        In order to prevent OnBarUpdate() from actually running any logic, you need to check if PlaybackMode is set to true or false before running its logic. If it's false, then just return.

        Code:
        protected override void OnBarUpdate()
        {
             // return if PlaybackMode is false; the logic below will not run if it's false
             if (!PlaybackMode)
                  return;
        
             if (Now >= tradingEndDate)        // Reset trading time start/end for next session
             {
                  tradingBeginDate = Now.Date.Add(tradingBegin);
                  tradingEndDate = Now.Date.Add(tradingEnd);
                  if (tradingEnd < tradingBegin) tradingEndDate = tradingEndDate.AddDays(1);
             }
        }
        Zachary G.NinjaTrader Customer Service

        Comment


          #5
          I have an idea... I'll put a bool variable in OnConnectionStatusUpdate() so that it's only true the first time that code runs. Not sure why I didn't think of that before.

          Do you know of the reason why OnBarUpdate even runs at all before the Connection type is known?

          Code:
                  private bool        ConnectionKnown            = false;    // Whether the OnConnectionStatusUpdate() code was called yet
          
                  protected override void OnConnectionStatusUpdate(ConnectionStatusEventArgs connectionStatusUpdate)
                  {
                      ConnectionKnown = true;
                  }
          
                  protected override void OnBarUpdate()
                  {
                      if (!ConnectionKnown) return;            // Connection status is unknown -- wait until connection established before running
                  [...]
                  }
          Last edited by cassb; 07-05-2016, 11:19 AM.
          cassb
          NinjaTrader Ecosystem Vendor - Logical Forex

          Comment


            #6
            Hello Bryan,

            Both OnBarUpdate() and OnConnectionStatusUpdate() are event driven methods. OnBarUpdate() is called whenever a bar is updated and OnConnectionStatusUpdate() is called whenever a change in connection status occurs.

            OnBarUpdate() is not going to wait for OnConnectionStatusUpdate() to be called before doing anything. It solely relies on the update of a bar.
            Zachary G.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_ZacharyG View Post
              Hello Bryan,

              Both OnBarUpdate() and OnConnectionStatusUpdate() are event driven methods. OnBarUpdate() is called whenever a bar is updated and OnConnectionStatusUpdate() is called whenever a change in connection status occurs.

              OnBarUpdate() is not going to wait for OnConnectionStatusUpdate() to be called before doing anything. It solely relies on the update of a bar.
              OK, that makes sense programmatically, but seems a little silly functionally to update bars when there is no connection established yet. I would think that the connection would 'change' to "None" before OnBarUpdate is ever called... but then again, I didn't design the code. ;-)
              cassb
              NinjaTrader Ecosystem Vendor - Logical Forex

              Comment


                #8
                Ugh. Does Strategy Analyzer ever call OnConnectionStatusUpdate()? This is getting really frustrating.

                Put this code into SampleMACrossOver and then put a break in it. Run SA with this code and it will never call OnConnectionStatusUpdate.

                protected override void OnConnectionStatusUpdate(ConnectionStatusEventArgs connectionStatusUpdate)
                {
                bool ConnectionKnown = true;
                }
                cassb
                NinjaTrader Ecosystem Vendor - Logical Forex

                Comment


                  #9
                  Hello Bryan,

                  The Strategy Analyzer does not utilize a connection and will not call OnConnectionStatusUpdate().

                  If you wish for your strategy to do something when running a specific mode in the Strategy Analyzer, you can take a look at the undocumented StrategyBase.Category enum: http://ninjatrader.com/support/forum...31&postcount=2
                  Zachary G.NinjaTrader Customer Service

                  Comment


                    #10
                    What Category is Market Replay?

                    All I am trying (unsuccessfully) to do here is have the variable "Now" represent the date/time of each tick on the chart, not the current clock time. That's all. So far I have written several variables and overrode the Now function and added an override for OnConnectionStatusUpdate and it's not working in all cases.

                    It seems like a simple thing to do, yet has become my nemesis. ;-)
                    Last edited by cassb; 07-05-2016, 12:33 PM.
                    cassb
                    NinjaTrader Ecosystem Vendor - Logical Forex

                    Comment


                      #11
                      Hello Bryan,

                      The Strategy Analyzer and Market Replay are two different things. There is no category for Market Replay; Market Replay is a connection. The Strategy Analyzer is used for backtesting and optimizing a script. Whatever "Backtest type" you select in the Market Analyzer is its category.

                      To get the date and time for each tick, you can add a 1 tick series to your script and then assign Times[1][0] to your variable.

                      To add data series to your script, please take a look at this help guide link: https://ninjatrader.com/support/help...dataseries.htm

                      For more information about the Times collection, please take a look at this help guide link: https://ninjatrader.com/support/help...ries_times.htm

                      For more information about running a multi series script, plesae take a look at this help guide link: https://ninjatrader.com/support/help...nstruments.htm
                      Zachary G.NinjaTrader Customer Service

                      Comment


                        #12
                        The second data series sounds good, except SA does not allow multi-series strategies with High Order Fill Resolution. And that's what I think I have to use if my strategy depends on tick data to run. :-( If Order Fill is set to Standard, does it only fill orders on the first tick of the bar?

                        Second question: In SA, does Position.MarketPosition always return MarketPosition.Flat even if an order was filled?
                        Last edited by cassb; 07-05-2016, 01:40 PM.
                        cassb
                        NinjaTrader Ecosystem Vendor - Logical Forex

                        Comment


                          #13
                          Hello Bryan,

                          You are correct that high fill resolution will only work on single series strategies. In this case, you do not need to add a tick series. If you select high fill resolution and set Type to Tick and Value to 1, this is adding that secondary tick series for you.

                          You will still be able to use Times[1][0] to obtain the time of each tick bar.

                          With your Strategy Analyzer set to standard fill resolution, fills occur at the close of each bar.

                          What Position.MarketPosition returns depends on what position the strategy is in when that call occurs. It will not always return Flat in the Strategy Analyzer.
                          Zachary G.NinjaTrader Customer Service

                          Comment


                            #14
                            Hi,
                            I think you can use the following. This way you do not have to add a variable just for the replay connection detection.
                            Code:
                                    private DateTime Now
                                    {
                                        get 
                                        { 
                                            DateTime now;
                                            if (State == State.Historical) now = Time[0];
                                            else if (Bars.IsInReplayMode) now = NinjaTrader.Cbi.Connection.PlaybackConnection.Now;
                                            else now = NinjaTrader.Core.Globals.Now;
                                            if (now.Millisecond > 0)
                                                now = NinjaTrader.Core.Globals.MinDate.AddSeconds((long) System.Math.Floor(now.Subtract(NinjaTrader.Core.Globals.MinDate).TotalSeconds));
                                            return now;
                                        }
                                    }

                            What is the reason you use the code in the end regarding the milliseconds?
                            Code:
                            if (now.Millisecond > 0)
                                                now = NinjaTrader.Core.Globals.MinDate.AddSeconds((long) System.Math.Floor(now.Subtract(NinjaTrader.Core.Globals.MinDate).TotalSeconds));

                            Comment


                              #15
                              State.Historical can be the state when both painting historical bars on the chart and when running Strategy Analyzer. And I have to handle those differently. Also, Now can be called when State.Terminated when the Timers object is undefined.

                              I came up with this code and it works for SA so far. Need to test in Market Replay and when just painting bars on the chart when it loads.

                              Code:
                              private DateTime    now                        = Core.Globals.Now;
                              
                                      private DateTime Now
                                      {
                                          get
                                          {
                                              if (State != State.Historical && State != State.Realtime) now = Core.Globals.Now;    // Some weird state; just use DateTime.Now
                                              else if (Category != null) now = Times[1][0];    // Strategy Analyzer is running - use chart time
                                              else now = (Cbi.Connection.PlaybackConnection != null ? Cbi.Connection.PlaybackConnection.Now : Core.Globals.Now);
                              
                                              if (now.Millisecond > 0)
                                                  now = Core.Globals.MinDate.AddSeconds((long)Math.Floor(now.Subtract(Core.Globals.MinDate).TotalSeconds));
                              
                                              return now;
                                          }
                                      }
                              cassb
                              NinjaTrader Ecosystem Vendor - Logical Forex

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by jpapa, Today, 07:22 AM
                              1 response
                              4 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by kevinenergy, 02-17-2023, 12:42 PM
                              116 responses
                              2,757 views
                              1 like
                              Last Post kevinenergy  
                              Started by franatas, 12-04-2023, 03:43 AM
                              7 responses
                              106 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by Jltarrau, Today, 05:57 AM
                              3 responses
                              8 views
                              0 likes
                              Last Post Jltarrau  
                              Started by f.saeidi, Today, 05:56 AM
                              2 responses
                              8 views
                              0 likes
                              Last Post NinjaTrader_Erick  
                              Working...
                              X