Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Error executing 2 orders, 1 BuyStop 1 SellStop at the same time.

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

    Error executing 2 orders, 1 BuyStop 1 SellStop at the same time.

    Error executing 2 orders, 1 BuyStop 1 SellStop at the same time.

    Hello, good morning, Thank you for reading me in advance.

    I have a problem and I'm wondering if you can help me please.

    I want to put in my script

    1 "BuyStop" above the current price.

    1 a "SellStop" below the current price.


    But only execute the first one in the line.

    Example:

    if ((Close[0] > MINIMUM)
    && (TRADING_CONTROL == true)
    && (Close[0] < MAXIMUM))
    {
    EnterLongStopMarket(3, ASK + (30 * TickSize),, @"LONG"); //BUYSTOP
    EnterShortStopMarket(3, BID - (30 * TickSize), @"SHORT"); //SELLSTOP
    }


    If I reverse the lines, it still only executes 1 order.

    Example:

    if ((Close[0] > MINIMUM)
    && (TRADING_CONTROL == true)
    && (Close[0] < MAXIMUM))
    {
    EnterShortStopMarket(3, BID - (30 * TickSize), @"SHORT"); //SELLSTOP
    EnterLongStopMarket(3, ASK + (30 * TickSize),, @"LONG"); //BUYSTOP
    }


    My automatic strategy is based on entering a trade by breaking the price range or distribution.

    The code would be more or less like this:​

    -------------------------------------------------------------------------------------------------------------------------------------



    Code:
    else if (State == State.Configure)
    {
    TRADING_CONTROL = true;
    }
    
    if ((Close[0] > MINIMUM)
    && (TRADING_CONTROL == true)
    && (Close[0] < MAXIMUM))
    {
    EnterLongStopMarket(3, ASK + (30 * TickSize),, @"LONG"); //BUYSTOP
    EnterShortStopMarket(3, BID - (30 * TickSize), @"SHORT"); // SELLSTOP
    }
    
    if (Position.MarketPosition == MarketPosition.Short)
    TRADING_CONTROL = false;
    
    if (Position.MarketPosition == MarketPosition.Long)
    TRADING_CONTROL = false;
    …
    if (Position.MarketPosition == MarketPosition.Long)
    {
    ExitLongStopMarket(3, BID - (100 * TickSize), "SL ", "");
    ExitLongLimit(3, ASK + (200 * TickSize)), "TP", "");
    }
    if (Position.MarketPosition == MarketPosition.Short)
    {
    ExitShortStopMarket(3, ASK + (100 * TickSize), @"SL ", "");
    ExitShortLimit(3, BID - (200 * TickSize)), "TP", "");
    }
    ​​
    Last edited by kliberthtrading20231107; 12-07-2023, 12:30 PM.

    #2
    Hello kliberthtrading20231107,

    Welcome to the NinjaTrader forums!

    This violates the managed approach internal order handing rules.

    "Methods that generate orders to enter a position will be ignored if:
    The strategy position is flat and an order submitted by an enter method (EnterLongLimit() for example) is active and the order is used to open a position in the opposite direction​"
    https://ninjatrader.com/support/help...antedPositions

    If you enable TraceOrders, you will see an ignored order message appearing in the NinjaScript Output window.
    https://ninjatrader.com/support/foru...121#post791121

    You will need to use the unmanaged approach.



    Below is a link to an example.
    https://ninjatrader.com/support/foru...579#post770579
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hi ChelseaB,

      Thanks for reading me.

      I have already successfully tested the solution of the links and the code that you prepared.

      But I have a detail that I don't understand.

      When I use the "SubmitOrderUnmanaged()" method in the "number of contracts" parameter (image attached) I have other results, apparently it is multiplied by 2, and it is something I do not understand.

      In the attached images you can see what was mentioned.

      code example:

      Code:
      protected override void OnExecutionUpdate(
          Cbi.Execution execution,    
          string executionId,                  
          double price,                          
          int quantity,                        
          Cbi.MarketPosition marketPosition,        
          string orderId,                  
          DateTime time)                
      {
      
          if (longStopEntry != null && execution.Order == longStopEntry)
          {        
      
              ocoString = string.Format("unmanageexitdoco{0}", DateTime.Now.ToString("hhmmssffff"));
      
              // TP
              SubmitOrderUnmanaged(
              0,    //selectedBarsInProgress,
              OrderAction.Sell,    //orderAction,
              OrderType.Limit,    //orderType,
              6,    //quantity,
              GetCurrentAsk(0) + (target_ticks* TickSize),    //limitPrice,
              0,    //stopPrice,
              ocoString,    //oco,
              "longProfitTarget");    // =signalName
      
              // SL
              SubmitOrderUnmanaged(
              0,
              OrderAction.Sell,
              OrderType.StopMarket,
              6,    //quantity,
              0,    
              PRICE_MIN - (5 * TickSize),    
              ocoString,
              "longStopLoss");    // =signalName
          }    
      
      
          else if (shortStopEntry != null && execution.Order == shortStopEntry)
          {
              ocoString = string.Format("unmanageexitdoco{0}", DateTime.Now.ToString("hhmmssffff"));
      
              // TP
              SubmitOrderUnmanaged(
              0,
              OrderAction.BuyToCover,
              OrderType.Limit,
               6,    //quantity, 
              GetCurrentBid(0) - (target_ticks* TickSize),    
              0,  
              ocoString,
              "shortProfitTarget");    // =signalName
      
              //  SL
              SubmitOrderUnmanaged(
              0,
              OrderAction.BuyToCover,
              OrderType.StopMarket,
              6,    
              0,    
              PRECIO_MAXIMO + (5 * TickSize),
              ocoString,
              "shortStopLoss");    // =signalName
          }
      
      
          else if (    execution.Name == "longProfitTarget"
                  ||    execution.Name == "longStopLoss"
                  ||     execution.Name == "shortProfitTarget"
                  ||    execution.Name == "shortStopLoss")
          {
              longStopEntry    = null;
              shortStopEntry    = null;
          }
      }​






      Attached Files
      Last edited by kliberthtrading20231107; 12-08-2023, 12:25 AM.

      Comment


        #4
        Hello kliberthtrading20231107,

        Is the entry execution part filling and causing the exit orders to be sent multiple times?

        Enable TraceOrders and print the order object in OnOrderUpdate() to understand what is going on?


        Save the output from the NinjaScript Output Window and include this with your next post and I will be happy to assist with analyzing the output.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi ChelseaB,

          Thanks for reading me again,

          I am using a variable called

          "CANTIDAD_CONTRATOS" = "QUANTITY_CONTRACTS"

          To only change one value in the entire code.

          I sent what was requested plus a screenshot​

          Code:
          CANTIDAD_CONTRATOS 1: 6
          08/12/2023 10:18:56 Strategy 'ASISTENTE KIN     >>  /251737721': Entered internal SubmitOrderUnmanaged() method at 08/12/2023 10:18:56: BarsInProgress=0 Action=Buy OrderType=StopMarket Quantity=6 LimitPrice=0 StopPrice=15955.50 SignalName='longStopEntry'
          CANTIDAD_CONTRATOS 2: 6
          08/12/2023 10:18:56 Strategy 'ASISTENTE KIN     >>  /251737721': Entered internal SubmitOrderUnmanaged() method at 08/12/2023 10:18:56: BarsInProgress=0 Action=SellShort OrderType=StopMarket Quantity=6 LimitPrice=0 StopPrice=15949.00 SignalName='shortStopEntry'
          CANTIDAD_CONTRATOS 5: 6
          08/12/2023 10:19:48 Strategy 'ASISTENTE KIN     >>  /251737721': Entered internal SubmitOrderUnmanaged() method at 08/12/2023 10:19:48: BarsInProgress=0 Action=BuyToCover OrderType=Limit Quantity=6 LimitPrice=15874.25 StopPrice=0 SignalName='shortProfitTarget'
          CANTIDAD_CONTRATOS 6: 6
          08/12/2023 10:19:48 Strategy 'ASISTENTE KIN     >>  /251737721': Entered internal SubmitOrderUnmanaged() method at 08/12/2023 10:19:48: BarsInProgress=0 Action=BuyToCover OrderType=StopMarket Quantity=6 LimitPrice=0 StopPrice=15961.50 SignalName='shortStopLoss'
          CANTIDAD_CONTRATOS 5: 6
          08/12/2023 10:19:48 Strategy 'ASISTENTE KIN     >>  /251737721': Entered internal SubmitOrderUnmanaged() method at 08/12/2023 10:19:48: BarsInProgress=0 Action=BuyToCover OrderType=Limit Quantity=6 LimitPrice=15874.25 StopPrice=0 SignalName='shortProfitTarget'
          CANTIDAD_CONTRATOS 6: 6
          08/12/2023 10:19:48 Strategy 'ASISTENTE KIN     >>  /251737721': Entered internal SubmitOrderUnmanaged() method at 08/12/2023 10:19:48: BarsInProgress=0 Action=BuyToCover OrderType=StopMarket Quantity=6 LimitPrice=0 StopPrice=15961.50 SignalName='shortStopLoss'​
          From what I observe, this code is repeated twice.

          Code:
          else if (shortStopEntry != null && execution.Order == shortStopEntry)
              {
                  ocoString = string.Format("unmanageexitdoco{0}", DateTime.Now.ToString("hhmmssffff"));
          
                  Print("CANTIDAD_CONTRATOS 5: " + CANTIDAD_CONTRATOS);
          
                  // TP
          
                  SubmitOrderUnmanaged(
                  0,
                  OrderAction.BuyToCover,
                  OrderType.Limit,
                  CANTIDAD_CONTRATOS, ////quantity,    
                  GetCurrentBid(0) - (TICKS_OBJETIVO * TickSize),    
                  0,    
                  ocoString,
                  "shortProfitTarget");    
          
                  Print("CANTIDAD_CONTRATOS 6: " + CANTIDAD_CONTRATOS);
          
                  // SL
                  SubmitOrderUnmanaged(
                  0,
                  OrderAction.BuyToCover,
                  OrderType.StopMarket,
                  CANTIDAD_CONTRATOS,    //quantity,
                  0,    
                  PRECIO_MAXIMO + (5 * TickSize),    
                  ocoString,
                  "shortStopLoss");    // =signalName
              }​​​
          Attached Files

          Comment


            #6
            Hello kliberthtrading20231107,

            I'm not seeing the print of the order object from OnOrderUpdate().

            May I confirm you are printing the order object from OnOrderUpdate()? (This is going to tell us if the entry part filled)


            To save the output from the output window to a text file, right-click the NinjaScript Output window -> select Save As. Then attach the file as an attachment to your next post.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Hi ChelseaB,

              I send the requested

              More copy of the code​​
              Attached Files

              Comment


                #8
                In my script it is modified so that I only make one trade per day.

                Comment


                  #9
                  Sending attached other results
                  Attached Files

                  Comment


                    #10
                    Hello kliberthtrading20231107,

                    This output file does not have the print of the order object from OnOrderUpdate().

                    Please place the following in the scope of the class.
                    Code:
                    protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string comment)
                    {
                    Print(order.ToString());
                    }​
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Thanks for example.

                      I send attached what was requested.​
                      NinjaScript Output 08_12_2023 13_37.txt
                      Attached Files

                      Comment


                        #12
                        Hello kliberthtrading20231107,

                        You have an entry order that part filled. OnExecutionUpdate() will run for each part fill. In this case it ran twice from two part fills.
                        With the code you have, this would submit four exit orders (two profit targets and two stop losses) all with the total quantity.

                        orderId='0cfd9591efe04d7ab322c1ba91d0a4de' account='Sim101' name='shortStopEntry' orderState=PartFilled instrument='MNQ DEC23' orderAction=SellShort orderType='Stop Market' limitPrice=0 stopPrice=16043.5 quantity=6 tif=Gtc oco='unmanagedentryoco0136565378' filled=1 averageFillPrice=16043.5 onBehalfOf='' id=43814 time='2023-12-08 13:36:56' gtd='2099-12-01' statementDate='2023-12-08'

                        orderId='0cfd9591efe04d7ab322c1ba91d0a4de' account='Sim101' name='shortStopEntry' orderState=Filled instrument='MNQ DEC23' orderAction=SellShort orderType='Stop Market' limitPrice=0 stopPrice=16043.5 quantity=6 tif=Gtc oco='unmanagedentryoco0136565378' filled=6 averageFillPrice=16043.2916666667 onBehalfOf='' id=43814 time='2023-12-08 13:36:56' gtd='2099-12-01' statementDate='2023-12-08'

                        orderId='d1c3e23164de4338ae4b44dc0d2371ec' account='Sim101' name='shortProfitTarget' orderState=Submitted instrument='MNQ DEC23' orderAction=BuyToCover orderType='Limit' limitPrice=16027 stopPrice=0 quantity=6 tif=Gtc oco='unmanageexitdoco0136567168' filled=0 averageFillPrice=0 onBehalfOf='' id=43815 time='2023-12-08 13:36:56' gtd='2099-12-01' statementDate='2023-12-08'

                        orderId='76d1b636aded459da30821d59c8b6f2e' account='Sim101' name='shortStopLoss' orderState=Submitted instrument='MNQ DEC23' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=16059 quantity=6 tif=Gtc oco='unmanageexitdoco0136567168' filled=0 averageFillPrice=0 onBehalfOf='' id=43816 time='2023-12-08 13:36:56' gtd='2099-12-01' statementDate='2023-12-08'

                        orderId='45d0e783d5a244f6b5c667b9396e60e7' account='Sim101' name='shortProfitTarget' orderState=Submitted instrument='MNQ DEC23' orderAction=BuyToCover orderType='Limit' limitPrice=16026.75 stopPrice=0 quantity=6 tif=Gtc oco='unmanageexitdoco0136567777' filled=0 averageFillPrice=0 onBehalfOf='' id=43817 time='2023-12-08 13:36:56' gtd='2099-12-01' statementDate='2023-12-08'

                        orderId='cbdcd641f0504b83ace17976c270a931' account='Sim101' name='shortStopLoss' orderState=Submitted instrument='MNQ DEC23' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=16059 quantity=6 tif=Gtc oco='unmanageexitdoco0136567777' filled=0 averageFillPrice=0 onBehalfOf='' id=43818 time='2023-12-08 13:36:56' gtd='2099-12-01' statementDate='2023-12-08'
                        You could choose to either wait until the order is fully filled before sending the exit orders.

                        Or you can choose to submit the exits on the first part fill, and then use ChangeOrder() to modify the quantity of each successive fill.​
                        The UnmanagedRithmicIBFriendlyExample in the export linked below demonstrates.
                        Hello, I see in the documentation you have fixed: 15048 Added Adapter, Rithmic Updated Rithmic API to version 11.3.0.0 Can you elaborate on that please? Will OnOrderUpdate() OnExecutionUpdate() and OnPositionUpdate() be called in the expected order?
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          You have 1 example of

                          "You could choose to either wait until the order is fully filled before sending the exit orders."

                          I appreciate it please.

                          While I review the second solution

                          "UnmanagedRithmicIBFriendlyExample"

                          Chelsea B. Thanks for the help!​

                          Comment


                            #14
                            Hello kliberthtrading20231107,

                            I don't have an example of this, but the logic is similar.
                            Code:
                            if (execution.Name == "Long limit entry 1")
                            {
                            // We sum the quantities of each execution making up the entry order
                            sumFilledLong1 += execution.Quantity;​
                            
                            if (sumFilledLong1 == execution.Order.Quantity)
                            {
                            stopLossLong1 = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.StopMarket, sumFilledLong1, 0, averageEntryPrice - StopDistance * TickSize, oco, "StopLossLong1");
                            targetLong1 = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Limit, sumFilledLong1, averageEntryPrice + ProfitDistance * TickSize, 0, oco, "TargetLong1");
                            sumFilledLong1 = 0;
                            ​}
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Hello ChelseB,

                              Thanks for the prompt and punctual response! thank you very much!!!

                              I tested the code for 2 days straight and it is a success.

                              "UnmanagedRithmicIBFriendlyExample.zip"​

                              "UnmanagedRithmicIBFriendlyExample.zip"​

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              59 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              134 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              75 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
                              50 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X