Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Calling SetStopLoss again after Rejection from Exchange

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

    Calling SetStopLoss again after Rejection from Exchange

    Hi

    I am calling SetStopLoss() to set a non-trailing stop. I have my logic to set to break even. Sometimes it gets rejected - this is fine.

    But the problem is that after the rejection all subsequent calls to SetStopLoss() is being ignored, and I am unable to set a StopLoss at all. This is unacceptable.

    Also, this is a problem even on Sim. For example, after getting the error "Sell stop or sell stop limit orders can't be placed above the market." all future calls to SetStopLoss() is ignored by NT8. There's no way to set a stop...


    Is this a known bug or is there a workaround for it.











    Last edited by madankumars; 11-18-2019, 11:17 AM.

    #2
    Hello madankumars,

    Thanks for your post.

    Are you ensuring that you are resetting your stop loss by calling SetStopLoss when the strategy is flat before the next Enter order is submitted? You will need to do this since SetStopLoss preps NinjaTrader to submit the next stop loss at this level.

    You can check the example below for demonstration on how setting a stop loss dynamically should be done. If you are still having issues, please attach a modification of this example script that shows how you are hitting this issue following this approach.

    SamplePriceModification - https://ninjatrader.com/support/help...of_stop_lo.htm

    I look forward to assisting.

    Comment


      #3
      Hi, thanks for your reply. I saw your sample...

      In my situation, the position is still open. and i want to send another stop loss after the 1st one is rejected

      for example, taking from your sample code :

      protected override void OnBarUpdate()
      {

      // If a long position is open, allow for stop loss modification to breakeven
      if (Position.MarketPosition == MarketPosition.Long)
      {
      // Once the price is greater than entry price+50 ticks, set stop loss to breakeven
      if (Close[0] > Position.AveragePrice + 50 * TickSize)
      {
      SetStopLoss(CalculationMode.Price, Position.AveragePrice);
      }
      }


      If the SetStopLoss() gets rejected for whatever reason, the next time OnBarUpdate() is called, it needs to submit again, correct? it does not work like that. It gets completely ignored.

      What do we need to do to make sure it submits the order again, if the first time it is rejected?






      Comment


        #4
        Hello madankumars,

        Thanks for your question.

        You could set RealtimeErrorHandling to IgnoreAllErrors, or StopCancelCloseIgnoreRejects, and then trap the rejection in OnOrderUpdate. You can then use an Exit method to submit your Stop Loss order instead of using SetStopLoss.

        For further direction on using OnOrderUpdate, I recommend our SampleOnOrderUpdate strategy.

        SampleOnOrderUpdate - https://ninjatrader.com/support/help...and_onexec.htm

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

        RealtimeErrorHandling - https://ninjatrader.com/support/help...orhandling.htm

        Please let me know if there is anything else I can do to help.

        Comment


          #5
          Hi, My strategy is already set to StopCancelCloseIgnoreRejects.

          Can you please tell me exactly what do I need to do in OnOrderUpdate ? I can trap the rejection in OnOrderUpdate. But what exactly do I need to do to ensure SetStopLoss() works again?

          Right now i am using my own logic to exit my position at market, but that is causing lots of slippage because there is no active stop order loss in place.

          Also this is risky because if i get disconnected or if NT crashes/hangs while I have an open position, that means there is basically no stop loss and I have a huge risk.








          Comment


            #6
            Hello madankumars,

            When you trap the rejection within OnOrderUpdate, submit your stop loss using an Exit method. You will need to use the Exit method instead of SetStopLoss because the strategy is already in a position.

            When the strategy is flat, call SetStopLoss again to reset it to an initial level before you call your next Enter method. I have attached an example that can demonstrate submitting a second stop loss on a rejection.

            Please let me know if you have any questions.
            Attached Files

            Comment


              #7
              Thanks for your response. But i dont want to exit the position using a market order.

              This is what I want:

              1. Enter Long
              2. [Open Position Exists]
              3. Call SetStopLoss() - this gets rejected.
              4. Call SetStopLoss() again - i need to set a new stop loss

              What you are telling me is that I need to go Flat , before calling #4. Otherwise nothing can be done. Did I get that right?


              Comment


                #8
                Hello madankumars,

                SetStopLoss needs to be called when the strategy is flat before it enters to prep NinjaTrader to submit the stop loss to an appropriate level once the associated Enter order fills.

                The test script does the following:

                1. Calls SetStopLoss to set stop loss to an initial level (invalid level to create a rejection.)
                2. Calls EnterLong to enter
                3. Traps the Stop loss's rejection
                4. Calls ExitLongStopMarket to place a stop market order to act as your stop loss which was initially rejected.

                You need to trap when the rejection happens in OnOrderUpdate and use an Exit method to submit the order instead of calling SetStopLoss again.

                Please test the attached script in post #6 for demonstration.

                We look forward to assisting.

                Comment


                  #9
                  Hello Jim,

                  I tried extending this code for two entries. But it only sets the stop for one entry, can you help me understand why its not working?

                  Code:
                  #region Using declarations
                  using System;
                  using System.Collections.Generic;
                  using System.ComponentModel;
                  using System.ComponentModel.DataAnnotations;
                  using System.Linq;
                  using System.Text;
                  using System.Threading.Tasks;
                  using System.Windows;
                  using System.Windows.Input;
                  using System.Windows.Media;
                  using System.Xml.Serialization;
                  using NinjaTrader.Cbi;
                  using NinjaTrader.Gui;
                  using NinjaTrader.Gui.Chart;
                  using NinjaTrader.Gui.SuperDom;
                  using NinjaTrader.Gui.Tools;
                  using NinjaTrader.Data;
                  using NinjaTrader.NinjaScript;
                  using NinjaTrader.Core.FloatingPoint;
                  using NinjaTrader.NinjaScript.Indicators;
                  using NinjaTrader.NinjaScript.DrawingTools;
                  #endregion

                  namespace NinjaTrader.NinjaScript.Strategies
                  {
                  public class SubmitSecondStopLoss : Strategy
                  {
                  protected override void OnStateChange()
                  {
                  if (State == State.SetDefaults)
                  {
                  Description = @"Enter the description for your new custom Strategy here.";
                  Name = "SubmitSecondStopLoss";
                  Calculate = Calculate.OnBarClose;
                  EntriesPerDirection = 1;
                  EntryHandling = EntryHandling.AllEntries;
                  IsExitOnSessionCloseStrategy = true;
                  ExitOnSessionCloseSeconds = 30;
                  IsFillLimitOnTouch = false;
                  MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                  OrderFillResolution = OrderFillResolution.Standard;
                  Slippage = 0;
                  StartBehavior = StartBehavior.WaitUntilFlat;
                  TimeInForce = TimeInForce.Gtc;
                  TraceOrders = true; // Changed to true for better debugging
                  RealtimeErrorHandling = RealtimeErrorHandling.StopCancelCloseIgnoreRejects ;
                  StopTargetHandling = StopTargetHandling.PerEntryExecution;
                  BarsRequiredToTrade = 20;
                  IsInstantiatedOnEachOptimizationIteration = true;
                  }
                  else if (State == State.Configure)
                  {
                  }
                  }

                  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)
                  {
                  Print($"{time} - Order Update: {order.Name} ({order.FromEntrySignal}) - State: {orderState}");

                  if(order.FromEntrySignal == "L1" && order.Name == "Stop loss" && orderState == OrderState.Rejected)
                  {
                  Print("L1 Stop Loss Rejected - Placing Emergency Stop");
                  ExitLongStopMarket(0, true, 1, Position.AveragePrice - 5 * TickSize, "Emergency Stop Loss1", "L1");
                  }

                  if(order.FromEntrySignal == "L2" && order.Name == "Stop loss" && orderState == OrderState.Rejected)
                  {
                  Print("L2 Stop Loss Rejected - Placing Emergency Stop");
                  ExitLongStopMarket(0, true, 1, Position.AveragePrice - 5 * TickSize, "Emergency Stop Loss2", "L2");
                  }
                  }

                  protected override void OnBarUpdate()
                  {
                  if (State == State.Realtime && Position.MarketPosition == MarketPosition.Flat)
                  {
                  // L1 Entry with stop loss
                  double l1StopPrice = Close[0] + 10 * TickSize;
                  SetStopLoss("L1", CalculationMode.Price, l1StopPrice, false);
                  EnterLong(1, "L1");
                  Print($"L1 Entry at {Close[0]} with Stop Loss at {l1StopPrice}");

                  // L2 Entry with stop loss
                  double l2StopPrice = Close[0] + 15 * TickSize;
                  SetStopLoss("L2", CalculationMode.Price, l2StopPrice, false);
                  EnterLong(1, "L2");
                  Print($"L2 Entry at {Close[0]} with Stop Loss at {l2StopPrice}");
                  }
                  }
                  }
                  }​

                  Last edited by ulisesguerrero; 01-20-2025, 08:06 PM.
                  ulisesguerrero
                  NinjaTrader Ecosystem Vendor - Thrifty Coders

                  Comment


                    #10
                    Hello ulisesguerrero,

                    It looks like you have added debugging prints which would be helpful in determining the issue.

                    May I have the output from the output window save to a text file?
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Hello Chelsea,

                      Here's the output:
                      Enabling NinjaScript strategy 'SubmitSecondStopLoss/344729656' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=5 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions, ignore order rejections ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes
                      1/21/2025 8:47:49 AM Strategy 'SubmitSecondStopLoss/344729656': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='L1' Mode=Price Value=21722.5 IsSimulatedStop=False IsMarketIfTouched=False
                      1/21/2025 8:47:49 AM Strategy 'SubmitSecondStopLoss/344729656': Entered internal SubmitOrderManaged() method at 1/21/2025 8:47:49 AM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='L1' FromEntrySignal=''
                      1/21/2025 8:47:49 AM - Order Update: L1 () - State: Submitted
                      1/21/2025 8:47:49 AM - Order Update: L1 () - State: Accepted
                      1/21/2025 8:47:49 AM - Order Update: L1 () - State: Working
                      1/21/2025 8:47:49 AM - Order Update: L1 () - State: Filled
                      1/21/2025 8:47:49 AM - Order Update: Stop loss (L1) - State: Submitted
                      1/21/2025 8:47:49 AM - Order Update: Stop loss (L1) - State: Rejected
                      L1 Stop Loss Rejected - Placing Emergency Stop
                      1/21/2025 8:47:49 AM Strategy 'SubmitSecondStopLoss/344729656': Entered internal SubmitOrderManaged() method at 1/21/2025 8:47:49 AM: BarsInProgress=0 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=21719.00 SignalName='Emergency Stop Loss1' FromEntrySignal='L1'
                      1/21/2025 8:47:49 AM - Order Update: Emergency Stop Loss1 (L1) - State: Submitted
                      1/21/2025 8:47:49 AM - Order Update: Emergency Stop Loss1 (L1) - State: Accepted
                      L1 Entry at 21720 with Stop Loss at 21722.5
                      1/21/2025 8:47:49 AM Strategy 'SubmitSecondStopLoss/344729656': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='L2' Mode=Price Value=21723.75 IsSimulatedStop=False IsMarketIfTouched=False
                      1/21/2025 8:47:49 AM Strategy 'SubmitSecondStopLoss/344729656': Entered internal SubmitOrderManaged() method at 1/21/2025 8:47:49 AM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='L2' FromEntrySignal=''
                      1/21/2025 8:47:49 AM - Order Update: L2 () - State: Submitted
                      1/21/2025 8:47:49 AM - Order Update: L2 () - State: Accepted
                      1/21/2025 8:47:49 AM - Order Update: L2 () - State: Working
                      1/21/2025 8:47:49 AM - Order Update: L2 () - State: Filled
                      Strategy 'SubmitSecondStopLoss/344729656': An Set() method to submit an exit order at '01/21/2025 08:47:48' has been ignored. Please search on the term 'Internal Order Handling Rules that Reduce Unwanted Positions' in the Help Guide for detailed explanation.
                      L2 Entry at 21720 with Stop Loss at 21723.75
                      1/21/2025 8:48:16 AM - Order Update: Emergency Stop Loss1 (L1) - State: Working
                      1/21/2025 8:48:16 AM - Order Update: Emergency Stop Loss1 (L1) - State: Filled
                      ulisesguerrero
                      NinjaTrader Ecosystem Vendor - Thrifty Coders

                      Comment


                        #12
                        Hello ulisesguerrero,

                        Saving to a text file allows you to provide the full output attached to the post and keeps your post short.

                        To save the output window to a text file right-click the output window and select Save as.

                        Below is a link to a support article with this instruction.



                        That said, I am seeing an order was ignored due to internal order handling rules.

                        Strategy 'SubmitSecondStopLoss/344729656': An Set() method to submit an exit order at '01/21/2025 08:47:48' has been ignored. Please search on the term 'Internal Order Handling Rules that Reduce Unwanted Positions' in the Help Guide for detailed explanation.


                        I'm seeing that EntriesPerDirection is set to 1 so you are only wanting to allow one entry order to be submitted into a position and not two.

                        However, both entry orders are being submitted at the same time. The EntriesPerDirection is based on the position. Once the position is entered this causes future entry orders to be ignored. If a second entry is submitted before the position has changed, that second entry will not get ignored, but will end up past the EntriesPerDirection allowed.

                        If you want to two entries into a direction set EntriesPerDirection to 2, then remove the instance of the strategy from the Configured list and add a new instance from the Available list (to pull the new default).
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Hello Chelsea,

                          I had already tried with many entries per direction, unfortunately it still doesn't work. Can you please test on your side? It only submits one stop (same terminal output).

                          Regards
                          Ulises
                          ThriftyCoders
                          ulisesguerrero
                          NinjaTrader Ecosystem Vendor - Thrifty Coders

                          Comment


                            #14
                            Hello Ulises,

                            I would be happy to test an export of the updated script.

                            Please provide an export of the script which has EntriesPerDirection set to 2 and prints the full order.ToString() in OnOrderUpdate().

                            To export a NinjaTrader 8 NinjaScript so this can be shared and imported by the recipient do the following:
                            1. Click Tools -> Export -> NinjaScript Add-on...
                            2. Click the 'add' link -> check the box(es) for the script(s) and reference(s) you want to include
                            3. Click the 'Export' button
                            4. Enter the script name in the value for 'File name:'
                            5. Choose a save location -> click Save
                            6. Click OK to clear the export location message
                            By default your exported file will be in the following location:
                            • (My) Documents/NinjaTrader 8/bin/Custom/ExportNinjaScript/<export_file_name.zip>
                            Below is a link to the help guide on Exporting NinjaScripts.


                            Once exported, please attach the file as an attachment to your next post.​


                            Provide the instrument, bar type, interval, and date range (with the smallest date range possible that can still reproduce the error).
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Hello Chelsea,

                              Attached the strategy source code. Tested with NQ 03-25, 1 minute chart, last 3 days.

                              Thank you,
                              Ulises
                              Attached Files
                              ulisesguerrero
                              NinjaTrader Ecosystem Vendor - Thrifty Coders

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Today, 05:17 AM
                              0 responses
                              38 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              124 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              64 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              41 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              46 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X