Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Unmanaged Approach: Errors in Changing Orders

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

    Unmanaged Approach: Errors in Changing Orders

    Hi,

    My strategy uses unmanaged approach and I am getting the following error when changing the stopOrders:

    Error 1 for Short Positions: Sim101, Stop price can't be changed below the market affected Order: BuyToCover 1 StopMarket @ 11,599
    Error 2 for Long Positions: Sim101 Stop price can't be changed above the market, affected Order: Sell 1 StopMarket @ 11,599.50.

    I tested the trail stop losses in ATM strategies and realized that these errors almost never occur when using the ATM strategies.

    I need to know how I code my script so that I can catch these errors and and safely submit the change orders without it crashing my strategies and my hopes.

    Thanks,


    Attached Files

    #2
    Hello bjunaid,

    Thank you for your note.

    In the case of rejections, there are really only two ways you can handle this. The simplest solution would be that you can adjust your existing logic to prevent this from happening to start with. If the order is being placed at a price that causes a rejection it would be expected to stop the script.

    The second approach is more advanced as this would entail you handle all possible outcomes yourself. You can have the strategy ignore rejects and continue, you could then handle this situation however you want logically. Just please be advised this would require you test all cases.

    http://ninjatrader.com/support/helpG...tsub=rejection

    I look forward to being of further assistance.
    Kate W.NinjaTrader Customer Service

    Comment


      #3
      Hi Kate,

      I don't know know if it will be a good idea for me to ignore all errors. I want to know how can use the simplest approach: I am thinking, if I can catch the rejection in OnOrderUpdate and cancel the ChangeOrder before it is submitted. Can you please give me some examples of strategies that shows how this could be achieved.

      Thanks,

      Comment


        #4
        Hello bjunaid,

        Thank you for your note.

        In order for you to catch the rejection you'd have to use the second approach I detailed, or when the rejection occurred the strategy would just shut down using the default handling. You could certainly use RealtimeErrorHandling.StopCancelCloseIgnoreRejects so that the default handling is done for all errors other than rejections. The page I linked above shows the approach needed to then handle the rejection in OnOrderUpdate:

        Code:
        private Order stopLossOrder = null;
        private Order entryOrder = null;
        
        protected override void OnStateChange()
        {
          if (State == State.Configure)
          {
            RealtimeErrorHandling = RealtimeErrorHandling.Ig noreAllErrors;
          }
        }
        
        protected override void OnBarUpdate()
        {
          if (entryOrder == null && Close[0] > Open[0])
            EnterLong("myEntryOrder");
        
          if (stopLossOrder == null)
            stopLossOrder = ExitLongStopMarket(Position.Aver agePrice - 10 * TickSize, "myStopLoss", "myEntryOrder");
        }
        
        protected override void OnOrderUpdate(Order order,  double limitPrice, double stopPrice, int quantity , int filled, double averageFillPrice,
                                            OrderState orderState, DateTime time, ErrorCode  error, string nativeError)
        {
          // Assign stopLossOrder in OnOrderUpdate() to ensure the assignment occurs when expected.
          // This is more reliable than assigning Order objects in OnBarUpdate,
          // as the assignment is not guaranteed to be complete if it is referenced immediately after submitting
          if (order.Name == "myStopLoss" && orderState ==  OrderState.Filled)
            stopLossOrder = order;
        
          if (stopLossOrder != null && stopLossOrder == or der)
          {
            // Rejection handling
            if (order.OrderState == OrderState.Rejected)
            {
                // Stop loss order was rejected !!!!
                // Do something about it here - you could try resubmitting at a different price, or send a market order to close out the position, for example.
            }
          }
        }
        Please let us know if we may be of further assistance to you.
        Kate W.NinjaTrader Customer Service

        Comment


          #5
          Hi Kate,

          What statement do I put in the following, if I want to cancel the change order from being submitted. In other words, how do I cancel the change order without canceling the previous stoporder.


          if (stopLossOrder != null && stopLossOrder == order)
          {
          // Rejection handling
          if (order.OrderState == OrderState.Rejected)
          {
          // Stop loss order was rejected !!!! // Do something about it here - you could try resubmitting at a different price, or send a market order to close out the position, for example.
          }
          }

          Comment


            #6
            Hello bjunaid,

            Thank you for your reply.

            You can't cancel the change order from being submitted at that point, if the order was rejected, that order is just rejected and that's the end of that order. You'd need to place a new stop order using SubmitOrderUnmanaged() and assign that new order to your stopLossOrder variable so it may be tracked.

            Please let us know if we may be of further assistance to you.
            Kate W.NinjaTrader Customer Service

            Comment


              #7

              The simplest solution would be that you can adjust your existing logic to prevent this from happening to start with
              Hi bjunaid,

              I just want to support what Kate wrote in that quote above.

              The three causes of the rejections I see are:
              1. Bugs in the logic of my own code
              2. Market Data Feed Lag time - In reality the price is not really where the last market data says it is.
              3. Delays from local processing CPU load - When my local PC or VPS environment is too complex to always keep up with the market data it receives.

              The three best methods I found to fix the rejection problems are:
              A. If heavy lagging is not apparent ( numbers 2 & 3 above ) assume the problem is the logic in my code.
              1. First, I test to identify and fix the bugs or validate my own code.
              2. Second, I add a quick 'last instant' price distance test to reduce rejection risk. See the quick snip of pseudo code below.
              Code:
              //
              
              // Risk Management - 'At the last possible instant' test for Market Price Distance
              /// Below find pseudo code copied and simplified from an earlier strategy.
              if( 'your planned new stop price' < ( GetCurrentAsk(0) + (2 * TickSize) ) {
              // The Risk Management Price Distance Test Failed. Cause is likely logic in my code or data lag. // Add logging and test fail response logic here.
              } else {
              // The Risk Management Price Distance Test Passed. If a data lag test also just passed (the code snip below) // the desired new price is less likely to be on the wrong side of market price or so close // to the current price that it will likely cause rejection. // enter other quality tests and order logic here.
              }
              //



              B. I address both # 2 & 3 above, Data Lag and System slow-down, by testing for Data Lag. See one pseudo code example just below .

              Code:
              //
              
              // Risk Management - 'At the last possible instant' test for Low Risk Data Lag
              /// Below find pseudo code copied and simplified from an earlier strategy. Not tested to confirm it compiles.
              double dataLagDiffFromCoreTime = 0.0; double MaxNTDataLagAllowedForEntry = .6; /// or below instead of Time[0] use " - Times[1][0];" if submitting against an added faster secondary series TimeSpan timeDiffTimeSpan = System.DateTime.Now - Time[0]; dataLagDiffFromCoreTime = timeDiffTimeSpan.TotalSeconds; if( dataLagDiffFromCoreTime > MaxNTDataLagAllowedForEntry ) {
              // The Risk Management Data Lag Test Failed. Add any logging, alerting or response logic here. // Log the Order submission denied incident to your chosen logger or print it to the Output window. Print(Name + " Bar# " + CurrentBar + " " + System.DateTime.Now.ToString("hh:mm:ss:fff")
              + " ORDER SUBMISSION DENIED -- DATA LAG LIMIT REACHED -- dataLagDiffFromCoreTime = " + dataLagDiffFromCoreTime.ToString("0,0.000" );
              // Alert when Data Lag exceeds defined limits
              if( dataLagDiffFromCoreTime > (MaxNTDataLagAllowedForEntry * 1.4 ))
              Alert("DataLagLimitBreach", Priority.High, System.DateTime.Now.ToString("hh:mm:ss:ffff") + " Strat: " + Name + " Data Lag Limit Breached "
              + dataLagDiffFromCoreTime , [email protected]"\sounds\Aler t1.wav", 10, Brushes.Black, Brushes.Yellow);
              } else {
              // The Risk Management Data Lag Test Passed. Data Lag does not exceed your limits. // enter other quality tests and order logic here.
              }
              //


              Best of Luck,
              HedgePlay
              Last edited by hedgeplay; 10-24-2020, 11:54 AM.

              Comment


                #8
                Hi,

                Thanks for reply. I was able to temporarily fix that issue. However as I am further testing the strategy in Playback connection. I am having some issues.
                1. After the first stoploss or target is tagged, my strategy is still enabled however it stops calculating because I don't see anything being calculated in the output window no orders are being submitted. I can see that the chart is processing nothing being calculating.

                Do you know why this could be?

                Comment


                  #9
                  I was able to figure out the last error today. I this issue is now seems to be fixed.

                  Thanks,

                  Comment


                    #10
                    Originally posted by hedgeplay View Post


                    B. I address both # 2 & 3 above, Data Lag and System slow-down, by testing for Data Lag. See one pseudo code example just below .

                    Code:
                    double dataLagDiffFromCoreTime = 0.0;
                    double MaxNTDataLagAllowedForEntry = .6;

                    Best of Luck,
                    HedgePlay
                    Hi HedgePlay can you tell me how the value maxNTDataLagAllowedForEntry was created, why 0.6? with me there would never be an entryorder with this value ;-) dataLagDiffFromCoreTime = 01.112 is about my current value

                    Comment


                      #11
                      Originally posted by sidlercom80 View Post

                      Hi HedgePlay can you tell me how the value maxNTDataLagAllowedForEntry was created, why 0.6? with me there would never be an entryorder with this value ;-) dataLagDiffFromCoreTime = 01.112 is about my current value

                      Hi sidlercom,

                      maxNTDataLagAllowedForEntry should = (whatever is the correct value for your infrastructure and strategy)

                      So 01.112 is means the data is available 1.1 Seconds after the timestamp printed by the data provider, which could be 1.3-1.5 seconds after the originating order was placed. This could Ok if you know, plan and test your strategies with an expectation of this Data Lag plus 1-2 Standard Deviations higher.


                      Where (what strategy and context) did the .6 second max lag limit come from?

                      Infrastructure:
                      I pulled that from a strategy running on a Chicago based VPS. Being in Chicago and keeping the System lightly loaded the average Data Lag on that machine is way lower than 600ms.

                      Strategy:
                      The Strategy ran on short time frames with tight entries and stops and so was broken, entries and order management unreliable if Data Lag ever exceeded 600ms.
                      If your strategy trades off of 15 minute bars then Data Lag constraints might be less stringent.

                      Did that answer the question?

                      Comment


                        #12
                        Hi hedgeplay, thank you very much for your answer, that's enough for me

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by lmatiukas, Today, 07:09 PM
                        0 responses
                        2 views
                        0 likes
                        Last Post lmatiukas  
                        Started by ComfyCouch, Today, 06:04 PM
                        0 responses
                        12 views
                        0 likes
                        Last Post ComfyCouch  
                        Started by Ousher, Today, 04:35 PM
                        0 responses
                        4 views
                        0 likes
                        Last Post Ousher
                        by Ousher
                         
                        Started by Rugosoft, 11-17-2020, 08:22 AM
                        3 responses
                        38 views
                        0 likes
                        Last Post Shansen
                        by Shansen
                         
                        Started by hpolthof, Today, 03:48 PM
                        0 responses
                        7 views
                        0 likes
                        Last Post hpolthof  
                        Working...
                        X