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

Stop order rejected and strategy ends

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

    Stop order rejected and strategy ends

    Hello everyone

    Just to avoid rejected stop orders in scalping strategies, is there any example just to close position in case stop order can't be placed? I mean, I work with 20 ticks stop, but sometimes volatility is huge and stop order is rejected. What would be a good approach to close those positions and strategy go on? I do have this problem in full speed playback but also realtime.

    Any help or example will be welcome

    Sincerely,

    #2
    Hello Impessa,

    Thanks for your post.

    You can set RealtimeErrorHandling to RealtimeErroHandling.StopCancelCloseIgnoreRejects, and then you can trap the rejection in OnOrderUpdate to be able to handle the rejection.

    If you are handling your own order error or rejections, I suggest to include else-if logic to call CloseStrategy() for other order errors that you do not specifically handle.

    For example:

    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)
    {
        if (order.Name == "My Stop" && order.OrderState == OrderState.Rejected && comment.Contains("can't be placed below"))
        {
            ExitShort();
        }
        else if (order.OrderState == OrderState.Rejected)
        {
            CloseStrategy("Unhandled Rejection, Perform Stop Cancel Close");
        }
    }
    RealtimeErrorHandling - https://ninjatrader.com/support/help...orhandling.htm

    OnOrderUpdate - https://ninjatrader.com/support/help...rderupdate.htm

    CloseStrategy - https://ninjatrader.com/support/help...sestrategy.htm

    We look forward to assisting.
    Last edited by NinjaTrader_Jim; 03-18-2022, 11:36 AM.
    JimNinjaTrader Customer Service

    Comment


      #3
      Hi, jim

      Thanks for your fast answer. I will try your suggestion.
      Can I use comment.Contains("can't be placed below") just like that?

      Sincerely,

      Comment


        #4
        Hello Impessa,

        "comment" will reflect the native error that is given with the order rejection. The example would work for trapping the "Buy stop or buy stop limit orders can't be placed below the market" message from a Sim101 account specifically. This would need to match the live account's messaging to work correctly.

        You could test submitting orders that get rejected using the Order Ticket window to see the exact messaging when submitting orders to your live account.


        JimNinjaTrader Customer Service

        Comment


          #5
          Hey Jim-

          When I copy and paste your code from above. The editor tells me that comment in comment.Contains does not exist in the current context.

          What am I missing?

          Thank you,

          Nick

          Comment


            #6
            Hello Nick,

            When I copy that snippet into a strategy, I do not get any compile errors.

            Screenshot attached.
            Attached Files
            JimNinjaTrader Customer Service

            Comment


              #7
              Jim-

              I got it to work. I was using wrong syntax for the OnOrderUpdate line. Thank you.

              Is it possible to have multiple order names in the if(order.Name == "") line?

              Please see my attached screenshot and error message. Is there a different way to do this that will work?

              Thank you,

              Nick
              Attached Files

              Comment


                #8
                Hello Nick,

                The compiler is letting you know the C# syntax is incorrect. The line mentioned is at line 1311, but you can see what is described at line 1310.

                You are checking

                if the Name property of the order is "FifteenDoubleStop"

                And then you are checking:

                or "FifteenScapExit"

                the second statement is incomplete. I believe you want to check:

                or if the Name property of the order is "FifteenScalpExit"

                which would be:

                if (order.Name == "FifteenDoubleStop" || order.Name == "FifteenScalpExit")

                Parenthesis are relevant when setting up logic.

                Please note that this particular item is C# related. We are not C# programming educators, so I may suggest checking our some publicly available resources on C# to learn more about:
                • Operators
                • Data Types
                • If/Else statements.
                You may also wish to use the Strategy Builder and the View Code button to see how the Strategy Builder generates the C# syntax.

                I have included some publicly available resources on the C# concepts below.

                Data Types - https://www.tutorialsteacher.com/csh...arp-data-types

                Operators - https://www.tutorialsteacher.com/csh...harp-operators

                if/else statements - https://www.tutorialsteacher.com/csharp/csharp-if-else



                JimNinjaTrader Customer Service

                Comment


                  #9
                  Jim-

                  I am updating this part of my code.

                  What I want to happen is for the strategy to ignore the limit order reject, and close to position via a market order. But I want the strategy to remain running.

                  Right now the strategy handles the reject, sells via market order but disables.

                  I am running it on the Playback.

                  I have Realtime Error handling set to RealtimeErrorHandling.StopCancelCloseIgnoreRejects

                  and then I follow the code in the OnOrderUpdate from this link https://ninjatrader.com/support/help...orhandling.htm

                  How do I get the strategy to keep running?

                  Thank you,

                  Nick

                  Comment


                    #10
                    Hello Nick,

                    CloseStrategy will disable the strategy.

                    I suggest making sure your code takes a specific branch in OnOrderUpdate where you can take the action you want for each error you want to handle, and so can also make sure CloseStrategy() is not called if you do not want the strategy to be disabled.

                    Please also note that StopCancelCloseIgnoreRejects allows handling order rejections, but does not handle other order errors. If you want to have all order errors handled with your own logic, you can use RealtimeErrorHandling.IgnoreAllErrors.

                    JimNinjaTrader Customer Service

                    Comment


                      #11
                      Hello ,
                      i have the same problem as montionned before , mean "Stop order rejected and strategy ends " and that is happend sometimes cause of volatility of market.
                      if i want to add the set RealtimeErrorHandling to this code where can i add it exactely , and will i need to call other private bool or private string to do it ?
                      protected override void OnBarUpdate()
                      {
                      if (BarsInProgress != 0)
                      return;

                      if (CurrentBars[0] < 2)
                      return;
                      //Add for ATM STRATEGY use
                      // Make sure this strategy does not execute against historical data
                      if(State == State.Historical)
                      return;​
                      // Set 1
                      if (
                      ((orderId.Length == 0 && atmStrategyId.Length == 0 && Close[1] < EMA1[0])
                      || (CrossBelow(GetCurrentAsk(0), High, 2)))
                      // EMA Conditions
                      && ((EMA1[0] < EMA2[0])
                      && (EMA1[0] < EMA3[0])
                      && (EMA3[0] > EMA2[0]))

                      {
                      //atm strategy
                      isAtmStrategyCreated = false; // reset atm strategy created check to false
                      atmStrategyId = GetAtmStrategyUniqueId();
                      orderId = GetAtmStrategyUniqueId();
                      AtmStrategyCreate(OrderAction.Buy, OrderType.StopMarket, 0, (MAX1[0] + (1 * TickSize)), TimeInForce.Gtc, orderId, ATMStrategy, atmStrategyId, (atmCallbackErrorCode, atmCallBackId) => {
                      //check that the atm strategy create did not result in error, and that the requested atm strategy matches the id in callback

                      barNumberOfOrder = CurrentBar;

                      if (atmCallbackErrorCode == ErrorCode.NoError && atmCallBackId == atmStrategyId)
                      isAtmStrategyCreated = true;

                      });
                      }

                      // Check that atm strategy was created before checking other properties
                      if (!isAtmStrategyCreated)
                      return;

                      // Check for a pending entry order
                      if (orderId.Length > 0)
                      {
                      string[] status = GetAtmStrategyEntryOrderStatus(orderId);

                      // If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
                      if (status.GetLength(0) > 0)
                      {
                      //add for recalculat 2 bars to close
                      if (CurrentBar > barNumberOfOrder + 1 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                      {
                      AtmStrategyCancelEntryOrder(orderId); //cancel order if not filled after 2 bars
                      }
                      // Print out some information about the order to the output window
                      Print("The entry order average fill price is: " + status[0]);
                      Print("The entry order filled amount is: " + status[1]);
                      Print("The entry order order state is: " + status[2]);

                      // If the order state is terminal, reset the order id value
                      if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
                      orderId = string.Empty;
                      }
                      } // If the strategy has terminated reset the strategy id
                      else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                      atmStrategyId = string.Empty;

                      if (atmStrategyId.Length > 0)
                      {
                      // You can change the stop price
                      if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
                      AtmStrategyChangeStopTarget(0, Low[0] - 3 * TickSize, "STOP5", atmStrategyId);

                      // Print some information about the strategy to the output window, please note you access the ATM strategy specific position object here
                      // the ATM would run self contained and would not have an impact on your NinjaScript strategy position and PnL
                      Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
                      Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
                      Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId)) ;
                      Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId)) ;
                      }
                      //end

                      Comment


                        #12
                        Hello mariorac19,

                        Thanks for your notes.

                        GetAtmStrategyStopTargetOrderStatus() would be used to get the order name of a stop or target order when using Atm Strategy Methods such as "Stop1" or "Target2".

                        GetAtmStrategyStopTargetOrderStatus(): https://ninjatrader.com/support/help...rgetorders.htm

                        You could use RealtimeErrorHandling to determine the behavior of a strategy when the strategy places an order that is returned "Rejected". The default behavior is to stop the strategy, cancel any remaining working orders, and then close any open positions.

                        RealtimeErrorHandling could be set to IgnoreAllErrors to ignore any order errors received or StopCancelCloseIgnoreRejects to perform the default strategy behavior on all errors except order rejections. Please note that setting this property value to IgnoreAllErrors can have serious adverse affects on a running strategy unless you have programmed your own order rejection handling in the OnOrderUpdate() method. To do this you could trap the rejected order by checking if the OrderState is Rejected within OnOrderUpdate() followed by defining your own order rejection handling behavior for the rejected order.

                        Please see the example in the help guide link below that demonstrates using RealtimeErrorHandling and trapping a rejected order in OnOrderUpdate().

                        RealtimeErrorHandling — https://ninjatrader.com/es/support/h...orhandling.htm

                        Brandon H.NinjaTrader Customer Service

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by lightsun47, Today, 03:51 PM
                        0 responses
                        2 views
                        0 likes
                        Last Post lightsun47  
                        Started by 00nevest, Today, 02:27 PM
                        1 response
                        8 views
                        0 likes
                        Last Post 00nevest  
                        Started by futtrader, 04-21-2024, 01:50 AM
                        4 responses
                        41 views
                        0 likes
                        Last Post futtrader  
                        Started by Option Whisperer, Today, 09:55 AM
                        1 response
                        13 views
                        0 likes
                        Last Post bltdavid  
                        Started by port119, Today, 02:43 PM
                        0 responses
                        8 views
                        0 likes
                        Last Post port119
                        by port119
                         
                        Working...
                        X