Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Strategy OnBarUpdate Error

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

    Strategy OnBarUpdate Error

    Hello,
    is there a way to "catch" error - I mean perform action when I get this error? I want to echo variables when I get error.
    Thanks
    Paul

    #2
    Originally posted by kujista View Post
    Hello,
    is there a way to "catch" error - I mean perform action when I get this error? I want to echo variables when I get error.
    Thanks
    Paul
    Have you ever used a try-catch statement?

    Below is the method I use:

    Rename your current OnBarUpdate to OnBarUpdate_Handler, and make
    it a private method (no override), then add this code,

    Code:
    protected override void OnBarUpdate()
    {
        try {
            OnBarUpdate_Handler();
        }
        catch (Exception ex) {
            HandleException(ex);
            throw;
        }
    }
    
    private void HandleException(Exception ex)
    {
        StringBuilder sb = new StringBuilder(1024);
    
        sb.AppendLine(Name + " has encountered an error");
    
        do {
            sb.AppendLine("<EXCEPTION: " + ex.Message.Trim() + ">");
            sb.Append(ex.StackTrace);
            ex = ex.InnerException;
        } while (ex != null);
    
        string s = sb.ToString();
        Print(s);
        Log(s, LogLevel.Error);
    }
    ​
    This will catch all exceptions anywhere in OnBarUpdate and print
    a stack trace to the NinjaTrader output window and log file. You
    can adjust to taste, add more Print statements, etc, but this code
    above should be enough.

    Why? Because the real purpose is to print that stack trace

    Let me explain.

    Yes, this code should help you catch the errors, but it only works
    if the error is generating an exception
    . No matter, such errors are
    unpredictable and need 'catching' anyways, so you can see where they
    occurred. How so? By inspecting the stack trace, now you know which
    specific method generated the exception.

    The stack trace is a beacon, telling you which method(s) need attention.
    It is one of those method(s) where you need to "echo variables when I
    get error".

    The last method in the stack trace that contains code you wrote, that's
    the method (or one or more before it) that needs some investigative
    Print statements.

    Btw, this is one advantage of separating your code into lots of short
    quick methods -- it makes them easy to debug.

    Make sense?

    Comment


      #3
      Originally posted by bltdavid View Post

      Have you ever used a try-catch statement?

      Below is the method I use:

      Rename your current OnBarUpdate to OnBarUpdate_Handler, and make
      it a private method (no override), then add this code,

      Code:
      protected override void OnBarUpdate()
      {
      try {
      OnBarUpdate_Handler();
      }
      catch (Exception ex) {
      HandleException(ex);
      throw;
      }
      }
      
      private void HandleException(Exception ex)
      {
      StringBuilder sb = new StringBuilder(1024);
      
      sb.AppendLine(Name + " has encountered an error");
      
      do {
      sb.AppendLine("<EXCEPTION: " + ex.Message.Trim() + ">");
      sb.Append(ex.StackTrace);
      ex = ex.InnerException;
      } while (ex != null);
      
      string s = sb.ToString();
      Print(s);
      Log(s, LogLevel.Error);
      }
      ​
      This will catch all exceptions anywhere in OnBarUpdate and print
      a stack trace to the NinjaTrader output window and log file. You
      can adjust to taste, add more Print statements, etc, but this code
      above should be enough.

      Why? Because the real purpose is to print that stack trace

      Let me explain.

      Yes, this code should help you catch the errors, but it only works
      if the error is generating an exception
      . No matter, such errors are
      unpredictable and need 'catching' anyways, so you can see where they
      occurred. How so? By inspecting the stack trace, now you know which
      specific method generated the exception.

      The stack trace is a beacon, telling you which method(s) need attention.
      It is one of those method(s) where you need to "echo variables when I
      get error".

      The last method in the stack trace that contains code you wrote, that's
      the method (or one or more before it) that needs some investigative
      Print statements.

      Btw, this is one advantage of separating your code into lots of short
      quick methods -- it makes them easy to debug.

      Make sense?
      Hi bltdavid,

      Thank you for that great piece of code and the explanation. I've been using it on some of my more complex codes as I'm not fluent with Visual Basic or other programs to help find errors.

      When this is used in a Strategy code with OnBarUpdate, OnOrderUpdate, OnExecutionUpdate, etc, do I just need to make unique HandleException methods and it should work the same for discovering errors?

      On a current project my OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError) with the extras inside the (). Will those cause any unexpected issues or does my HandleException need more detail for those?

      Thanks in Advance for any insight.
      Kirk
      Last edited by zeller427; 02-12-2025, 09:31 AM.

      Comment


        #4
        Originally posted by zeller427 View Post
        When this is used in a Strategy code with OnBarUpdate, OnOrderUpdate, OnExecutionUpdate, etc, do I just need to make unique HandleException methods and it should work the same for discovering errors?
        The HandleException(ex) method itself does not need to be changed.

        But ... naturally ...
        Each handler for each of those 3 methods needs to be separate, but the
        catch block with the call to HandleException(ex) is the same for each.


        Originally posted by zeller427 View Post
        ​On a current project my OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError) with the extras inside the (). Will those cause any unexpected issues or does my HandleException need more detail for those?
        I would make OnOrderUpdate_Handler take the exact same
        arguments in the exact same order as the normal OnOrderUpdate.

        That way, OnOrderUpdate_Handler is seeing and processing the
        exact same things as your normal OnOrderUpdate would have done.

        Every time you do this try-catch technique using a middle-man
        handler, you want your middle-man handler method to be exact same
        signature (ie, the list of arguments) as the underlying original method
        it is handling.

        The idea is that this try-catch technique reuses the same exception
        handling routine HandleException in the catch statement. You
        don't need a unique exception handler, just call the same one each
        time inside your catch statement block.

        It is only the call to your new middle-man handler for the underlying
        original routine inside the try statement block that changes.

        The only purpose of the HandleException routine is to print the stack
        trace when an exception occurs -- and if one does occur, which should
        be rare, it's very catastrophic to your running strategy, so that stack
        trace will be extremely important in forensically investigating the root
        cause (which is probably a programmer logic error, not NT's or MS's
        fault).

        Make sense?

        Comment


          #5
          Thanks bltdavid.

          So, it makes sense so far with a couple of exceptions due to errors I'm seeing when trying to compile. Some strat files I have use the "Cbi." and some are without.

          from this
          HTML Code:
          https://ninjatrader.com/support/helpGuides/nt8/NT%20HelpGuide%20English.html?multi-time_frame__instruments.htm
          Code:
          protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice,
          int quantity, int filled, double averageFillPrice,
          OrderState orderState, DateTime time, ErrorCode error,
          string nativeError)
          {
          
          }
          Code:
          protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
                  {
                      try {
                          OnOrderUpdate_Handler(Cbi.Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment);
                      }
                      catch (Exception ex) {
                          HandleException(ex);
                          throw;
                      }
                  }
          //        protected override void - removed the override
                  private void OnOrderUpdate_Handler(Cbi.Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
                  ​


          It would possibly occur on the OnExecutionUpdate also but if you can help me over this hurdle I'll keep working towards a final compilable strat file.

          Thanks in Advance.
          Attached Files

          Comment


            #6
            Your code above has compilation errors. I have fixed them below.

            What was the error?
            When calling a method in C#, don't specify the types of each argument.
            You only specify type of the argument when defining the method.

            Code:
            protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice, int quantity, int filled,
                                                  double averageFillPrice, Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
            {
                try {
                    OnOrderUpdate_Handler(order, limitPrice, stopPrice, quantity, filled, averageFillPrice, orderState, time, error, comment);
                }
                catch (Exception ex) {
                    HandleException(ex);
                    throw;
                }
            }

            Comment


              #7
              bltdavid Thanks very much for the insight and the error correction. I was able to start using my modified code today and hope to progress more this month. I appreciate it! Have a great weekend!

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by gustavobp, Today, 02:50 AM
              0 responses
              3 views
              0 likes
              Last Post gustavobp  
              Started by rubiijonson, Today, 01:02 AM
              0 responses
              4 views
              0 likes
              Last Post rubiijonson  
              Started by fkronloff, Today, 12:25 AM
              0 responses
              3 views
              0 likes
              Last Post fkronloff  
              Started by Zadomani, Yesterday, 11:39 PM
              0 responses
              14 views
              0 likes
              Last Post Zadomani  
              Started by ToNovy, 01-27-2025, 11:22 PM
              20 responses
              198 views
              0 likes
              Last Post ToNovy
              by ToNovy
               
              Working...
              X