Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Trailing Stop loss Error- where can it be caught and handled

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

    Trailing Stop loss Error- where can it be caught and handled

    My strategy incorporates a trailing stop loss. I have taken most of the code out to try and narrow this issue down so at this point its very simple

    Based on EMA or whatever, if criteria is met we
    try
    {
    SetTrailStop(CalculationMode.Ticks, 20);
    EnterLong("123") or EnterShort("321")
    }
    catch....

    I am running the strategy against the playback of the last week (7/24 through 7/28). There are a couple places (at least two) where this issue occurs, the order criteria is met and so I enter long or short, the order gets submitted and filled. The problem is when the TrailStop attempts to get created I get an error Stop price can't be changed below the market....From watching the data the bar seems to have a huge influx of volume one way and then the other. My strategy isn't looking for the volume but something in the price it hits forces an order and then before the trailing stop order can get positioned the price has gone fully the other way.

    I have attempted to handle this error in a couple places. First I wrapped the orderEntry in a try catch but that did not capture the error. I then overrode the OnOrderUpdate event, I found that the ErrorCode object in that event has the error that occurred. So I wrapped the call to the base method in a try catch but that didn't capture it either. Meaning I get the error and I can display it but the strategy is still force stopped and the position is left open.

    My question is, it seems like the OnOrderUpdate only gets this error after the fact. What event can I override to get ahead of this error and handle it so that NInja doesn't shut down the strategy?

    #2
    Hello TimWhitbeck,

    Thank you for your post.

    Depending on the volatility of the market, you may need to use wider stops to prevent the error from happening; in some cases, after an entry is executed and by the time the stop is submitted, the market could have moved drastically so that the stop ends up being submitted on the wrong side of the market. There is a note to keep in mind about trail stop orders and the price based on the Calculate setting for a strategy:
    "Trail stop orders are modified based on the strategies 'Calculate' settings. In the case of 'Calculate' on bar close, when the bar closes the trail stop order modification will occur using the lowest/highest price of the bar as the reference price to apply the trail offset. Subsequently if the open price of the next bar is significantly higher or lower than this price then there is a possibility that the calculated trail stop price is now an invalid stop price. This is a risk with modifying any stop order closer to the current market price since any modification above/below the current price would be rejected."


    In the case of an error, the default behavior is for the strategy to StopCancelClose which would stop/disable the strategy, submit a cancel request for any working orders, and send a Close order to attempt to close any open positions. The RealtimeErrorHandling may also be set to either StopCancelCloseIgnoreRejects or IgnoreAllErrors in which you may trap certain errors/rejections and implement your own custom logic in the case of an error/rejection. For more details on RealtimeErrorHandling:


    Please let us know if we may be of further assistance.

    Comment


      #3
      Hey thank you for your quick response I appreciate it.

      As for the first part of your answer, in order to cover these 2 bars that are triggering this error I would have to more than triple my loss tolerance. I have tested with 3 weeks of data in total, 2 bars in the current week trigger this error but none of the other data does. Tripling my loss tolerance on all trade to account for 2 trades in the course of 3 weeks worth of data is a bit like using a Jet Engine to cook a chicken nugget. It would be overkill but also it would drastically throw off the balance I have for profit to loss tolerance.

      As for the second part this is more in line with what I am attempting to do. I set RealTimeErrorHandling to IgnoreAllErrors and even with this setting there seems to be no way to "handle" this error in code before the strategy is closed down. I tried real simple code in the OnOrderUpdate that simply said if orderstate is rejected then print the order name the overridden event doesn't fire before the strategy shuts down.

      To go a little further I have overridden the CloseStrategy event. I figured this would fire when the strategy was getting shut down after the error but it didn't fire either. So at the end of that my question is if there is a way that I can handle this code and tell the base that the exception has been handled or is there simply no way to intercept this error?

      Comment


        #4
        Hello TimWhitbeck,

        Thank you for your reply.
        • What are the messages in your log when the strategy is disabled?
        • If you print the value of RealtimeErrorHandling in your script, such as in OnBarUpdate() does the print show that it is set to IgnoreAllErrors or a different value?
        • Are you testing with the playback connection or in the Strategy Analyzer? Do you intend to use this strategy with Calculate.OnBarClose, Calculate.OnPriceChange, or Calculate.OnEachTick?
        • For the bars triggering this error, does the cause seem to be due to a large jump in price/high volatility? For example, is the price that the trailing stop is submitted/modified at off from the last price by a few ticks or more?
        I appreciate your patience and look forward to assisting you further.

        Comment


          #5
          I have answered your questions below and added a screen shot of the RealTimeErrorHandling output.
          • What are the messages in your log when the strategy is disabled? -
            • At the time it gets disabled? I have none from the event. I am currently logging OnBarUpdate, OnPositionUpdate, OnOrderUpdate and OnExecutionUpdate, and also in the overridden procedure I created for CloseStrategy. None of these capture the event. When this thing fails it doesn't seem to hit any of those before disabling the strategy.
          • If you print the value of RealtimeErrorHandling in your script, such as in OnBarUpdate() does the print show that it is set to IgnoreAllErrors or a different value?
            • I will attach a screen shot it shows that its ignorallerrors
          • Are you testing with the playback connection or in the Strategy Analyzer? Do you intend to use this strategy with Calculate.OnBarClose, Calculate.OnPriceChange, or Calculate.OnEachTick?
            • I am using Playback currently. Calculation is OnEachTick
          • For the bars triggering this error, does the cause seem to be due to a large jump in price/high volatility? For example, is the price that the trailing stop is submitted/modified at off from the last price by a few ticks or more?
            • Yes on the day in question everything goes along fine. Volume is somewhat flat then in this one candle we drop (which at some point in the drop we satisfy all the criteria to enter a short). But it immediately spikes back up. So its only down long enough for the EnterShort to trigger but before it can put in the stop loss.


          Click image for larger version

Name:	NinjaBarUpdateRealTimeError.jpg
Views:	765
Size:	49.3 KB
ID:	1262565

          Comment


            #6
            Hello Tim,

            Thank you for your reply.

            I would like to clarify; the question "What are the messages in your log when the strategy is disabled?" was referring to the Log tab of the Control Center. What messages do you see there when your strategy is disabled? Otherwise, I would be glad to review your log and trace files via email to get a better understanding of what is happening with the RealtimeErrorHandling behavior. You can send these files from the platform by going to the Control Center-> Help-> Email Support Ensuring 'Log and Trace Files' is checked will include these files. This is checked by default.​ Please include "ATTN Emily C" in the subject line and a link to this forum thread in the body of the email.

            I look forward to investigating this item with you.

            Comment


              #7
              A little embarrassed I didn't even see that log tab there or see anything on it in all the documents I read. So that said I will recreate the issue, check that log and see what I get and send it to you! Thank you!

              Comment


                #8
                Emily C It's unfortunately not much help just has the same message that is in the Message box. I will add a screen shot and add the logs as you suggested. It was running at 1K x speed so its repeated a bunch! Sorry!
                Click image for larger version

Name:	NinjaTrader_LogError.jpg
Views:	745
Size:	277.3 KB
ID:	1262668

                Comment


                  #9
                  I think I have a similar problem, but can't figure out how to resolve it.

                  I have a trailing stop that follows the Bollinger Bands. I don't have a problem when I enter the order and set the initial stop.

                  But when my stop is attempting to come down with the BB while price is going up, I will occasionally get the message that my stop couldn't be moved. In that case, I'm fine with my order closing out at the previous stop.

                  here is my code

                  PHP Code:
                                  else
                                  {
                                      bbStopLoss = Bollinger(.7, 25).Lower[0] + 5 * TickSize;
                                      bbStopLoss = Math.Min(bbStopLoss, maxBbStopLoss);
                                      try
                                      {
                                      SetStopLoss(@"Short", CalculationMode.Price, bbStopLoss, false);
                                      }
                                      catch
                                      {
                                          Print("stoploss error");
                                      }
                                      maxBbStopLoss = bbStopLoss;
                                  }
                  ​ 
                  

                  When the error occurs, my order closes out at the previous stop level, which is fine. But I get 10 error windows with this

                  Click image for larger version

Name:	image.png
Views:	648
Size:	13.0 KB
ID:	1281228

                  I thought I could use try-catch so that if it couldn't move the stop, it would just skip that code.

                  I have error handling set to
                  PHP Code:
                  RealtimeErrorHandling = RealtimeErrorHandling.StopCancelCloseIgnoreRejects; 
                  
                  so my strategy doesn't stop running but I have to clear all the error boxes.

                  ​is there an elegant way to "attempt" to move my stop, but if it's not possible to move, then just skip it?

                  Comment


                    #10
                    Originally posted by cre8able View Post
                    I think I have a similar problem, but can't figure out how to resolve it.

                    I have a trailing stop that follows the Bollinger Bands. I don't have a problem when I enter the order and set the initial stop.

                    But when my stop is attempting to come down with the BB while price is going up, I will occasionally get the message that my stop couldn't be moved. In that case, I'm fine with my order closing out at the previous stop.

                    here is my code

                    PHP Code:
                     else
                    {
                    bbStopLoss = Bollinger(.7, 25).Lower[0] + 5 * TickSize;
                    bbStopLoss = Math.Min(bbStopLoss, maxBbStopLoss);
                    try
                    {
                    SetStopLoss(@"Short", CalculationMode.Price, bbStopLoss, false);
                    }
                    catch
                    {
                    Print("stoploss error");
                    }
                    maxBbStopLoss = bbStopLoss;
                    }
                    ​ 
                    

                    When the error occurs, my order closes out at the previous stop level, which is fine. But I get 10 error windows with this

                    Click image for larger version

Name:	image.png
Views:	648
Size:	13.0 KB
ID:	1281228

                    I thought I could use try-catch so that if it couldn't move the stop, it would just skip that code.

                    I have error handling set to
                    PHP Code:
                    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelCloseIgnoreRejects; 
                    
                    so my strategy doesn't stop running but I have to clear all the error boxes.

                    ​is there an elegant way to "attempt" to move my stop, but if it's not possible to move, then just skip it?
                    Hello cre8able,

                    Thank you for your note.

                    Rejections could be trapped in the OnOrderUpdate() method of a strategy:


                    An order submitted via SetStopLoss() will have the signal name "Stop loss" so you could check if order.Name == "Stop loss" and if order.OrderState == OrderState.Rejected to catch when that order is rejected. The RealtimeErrorHandling page has an example snippet that shows how to trap a specific order when it is rejected, and if it is rejected you could add logic to handle that:


                    For example, you could add a bool that is toggled to allow the SetStopLoss() method to be called, then if you catch a rejection for the "Stop loss" order you could toggle the bool so that the SetStopLoss() method isn't called again in your OnBarUpdate() logic. The bool would then need to be reset, such as when the position is flat again, to allow for future stop loss orders to be submitted.

                    Please let us know if we may be of further assistance.

                    Comment


                      #11
                      I'm getting closer

                      I added code into "OnOrderUpdate" to change setStop to false when I generate the error trying to move the stop.

                      PHP 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)
                              {
                                  Print(order.Name + "   " + order.OrderState + "   " + Time[0].ToString("HH:mm:ss") + "      " + setStop);
                      
                                    if (order.Name == "Stop loss" && order.OrderState == OrderState.Cancelled)
                                    {
                                        setStop = false;
                                      longTrade = false;
                                      shortTrade = false;
                                      Print("====================================");
                                    }
                      
                              }
                      ​ 
                      

                      here is where I was changing the trailing stop

                      PHP Code:
                              protected override void OnBarUpdate()
                              {            
                                  if (CurrentBar < 100) return;    
                      
                                  CheckForPlaceTrade();
                      
                                  CheckForOpenTrade();
                      
                                  CheckBbZone();
                      
                                  if(setStop)
                                      SetStop();
                      
                                  Print (longTrade + "   " +bbZone + "   " + shortTrade + "   " +Time[0].ToString("HH:mm:ss") + "   " + setStop + "   " + Position.MarketPosition);    
                      
                                  DrawText();
                              }
                      
                      &#8203; 
                      
                      now it catches the error and stops trying to move the stop.

                      it has reduced the number of error dialog boxes to just 2. Down from 14.

                      here is how I set error handling
                      PHP Code:
                              RealtimeErrorHandling                = RealtimeErrorHandling.StopCancelClose;
                                      StopTargetHandling                    = StopTargetHandling.PerEntryExecution;
                      &#8203; 
                      
                      But I still get the error 1 time and the 2 error dialog boxes. It also closes the Strategy, so I have to re-enable it.

                      How do I capture the error BEFORE it generates the 2 dialog boxes and closes the strategy?

                      thanks

                      Click image for larger version

Name:	image.png
Views:	640
Size:	178.0 KB
ID:	1283259

                      Comment


                        #12
                        Hello cre8able,

                        Thank you for your reply.

                        "But I still get the error 1 time and the 2 error dialog boxes. It also closes the Strategy, so I have to re-enable it.

                        How do I capture the error BEFORE it generates the 2 dialog boxes and closes the strategy?​"

                        When using RealtimeErrorHandling.StopCancelClose there is always a chance of the errors being thrown and disabling the strategy. You may not be able to fully prevent these errors from happening. Since they have to do with attempting to move a stop price to the wrong side of the market, you can always add additional debugging prints that print out the last trade price as well as the stop price to get a better understanding of at what point the stop is being moved to the wrong side of the market. You could add strategy logic that checks if the stop price is above/below the market prior to attempting to modify the order price to the new stop price, though there is always the possibility of large market moves where the price changes to the other side of the stop price by the time the change is received by the broker and the change gets rejected. This is most common for orders with stop prices very close to the market price, so using wider stops is one way to prevent this from happening.

                        Otherwise, if you want to stop your strategy from being disabled even if an order gets rejected, you may need to consider changing your RealtimeErrorHandling to handle rejected orders and take a different action in the case of an order being rejected as I previously mentioned.

                        Thank you for your time and patience.

                        Comment


                          #13
                          thanks Emily

                          I have code that checks to see if there is a few ticks of clearance before I move the stop. But it price is moving fast, it will sometimes price will collide with my moving stop. If I make that clearance too far, then my stop doesn't trail where I need it .

                          At least by capturing the error in OnOrderUpdate, I limit the number of error dialog boxes to two so it's easier to clear them.

                          A perfect world would be to let me capture the error, but not have an error dialog box created. That would be a great option for a future version of NT

                          thanks for your help.

                          Comment


                            #14
                            Originally posted by cre8able View Post
                            thanks Emily

                            I have code that checks to see if there is a few ticks of clearance before I move the stop. But it price is moving fast, it will sometimes price will collide with my moving stop. If I make that clearance too far, then my stop doesn't trail where I need it .

                            At least by capturing the error in OnOrderUpdate, I limit the number of error dialog boxes to two so it's easier to clear them.

                            A perfect world would be to let me capture the error, but not have an error dialog box created. That would be a great option for a future version of NT

                            thanks for your help.
                            Thank you for your suggestion.

                            I have submitted this as a feature request to the Development Team and will follow up with an internal tracking number for your reference as soon as it is created.

                            Thanks in advance for your patience.

                            Comment


                              #15
                              Hello cre8able,

                              Thanks for your patience.

                              The internal tracking number for your feature request is SFT-6175. Please reference this internal tracking number when contacting Platform Support if you ever have questions regarding this feature request.

                              When a feature request is implemented, you'll find a description of the new feature in the release notes:Thank you for using NinjaTrader.​

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              56 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              133 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              73 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              45 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              49 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X