Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Adding Breakeven to ProfitChaseStopTrailExitOrdersExample

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

    Adding Breakeven to ProfitChaseStopTrailExitOrdersExample

    HI NinjaTrader_ChelseaB

    I was following an example of ProfitChaseStopTrailExitOrdersExample to add second order and breakeven and I have trouble

    breakevenShort:20882.25
    7/11/2024 6:17:00 AM | OOU | order | 7/11/2024 6:16:13 AM | orderId='24b7847733cd4ac991f398c828409341' account='Playback101' name='MyTargetShort' orderState=Filled instrument='NQ 09-24' orderAction=BuyToCover orderType='Limit' limitPrice=20877.25 stopPrice=0 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=20877.25 onBehalfOf='' id=184901 time='2024-07-11 06:16:13' gtd='2099-12-01' statementDate='2024-07-11'
    7/11/2024 6:17:00 AM | OOU | stop or target filled, preventing oco actions until reset Primary
    7/11/2024 6:16:13 AM Strategy '312671451/jockey: Cancelled pending exit order, since associated position is closed, orderId='f8b64bedada54717b4d9ab0bfdeecc3e' account='Playback101' name='MyStopShort' orderState=Accepted instrument='NQ 09-24' orderAction=BuyToCover orderType='Stop Market' limitPrice=0 stopPrice=20886.5 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=184902 time='2024-07-11 06:13:32' gtd='2099-12-01' statementDate='2024-07-11'

    Often as a result I am getting Error on calling 'OnBarUpdate' method on bar " ": Object reference not set to an instance of an object. when order is left hanging. I notice it when breakeven is used. maybe my breakeven part is wrong? Any Help would be appriciated

    ------------------
    In my strategy I want to use two entry orders(entryOrderS, entryOrderR, same entry price and stop loss but different take profits. However if breakeven is used, it onply applies to runner order(entryOrderR).

    private Order entryOrderS,entryOrderR, exitFlatS, exitFlatR;
    private Order placeHolderOrderS, profitTargetS, stopLossS, placeHolderOrderR, profitTargetR, stopLossR;​

    private void AssignOrderToVariable(ref Order order)
    {
    // Assign Order variable 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 (PrintDetails)
    // Print(string.Format("{0} | assigning {1} to variable", Time[0], order.Name));

    if ((order.Name == "MyEntryLong" || order.Name == "MyEntryShort") && entryOrderS != order)
    entryOrderS = order;


    if ((order.Name == "MyTargetLong" || order.Name == "MyTargetShort") && profitTargetS != order)
    profitTargetS = order;

    if ((order.Name == "MyStopLong" || order.Name == "MyStopShort") && stopLossS != order)
    stopLossS = order;

    if (order.Name == exitNameS && exitFlatS != order)
    exitFlatS = order;

    // Runner
    if ((order.Name == "MyEntryLongRunner" || order.Name == "MyEntryShortRunner") && entryOrderR != order)
    entryOrderR = order;


    if ((order.Name == "MyTargetLongRunner" || order.Name == "MyTargetShortRunner") && profitTargetR != order)
    profitTargetR = order;

    if ((order.Name == "MyStopLongRunner" || order.Name == "MyStopShortRunner") && stopLossR != order)
    stopLossR = order;
    if (order.Name == exitNameR && exitFlatR != order)
    exitFlatR = order;

    }

    -----------My Entry for longs
    (condition)
    if(longPrice >= GetCurrentAsk() && entryOrderS == null && profitTargetS == null && stopLossS == null)
    {
    entryOrderS = placeHolderOrderS;
    suppressOcoS = false;
    EnterLongStopMarket(0,true, PositionSize, longPrice, "MyEntryLong");
    if(TradeRunner && entryOrderR == null && profitTargetR == null && stopLossR == null)
    {
    entryOrderR = placeHolderOrderR;
    suppressOcoR = false;
    EnterLongStopMarket(0,true, PositionSizeRunner, longPrice, "MyEntryLongRunner");
    if(TradeRunner && entryOrderR == null && profitTargetR == null && stopLossR == null)
    {
    entryOrderR = placeHolderOrderS;
    suppressOcoR = false;
    EnterShortStopMarket(0,true, PositionSizeRunner, shortPrice, "MyEntryShortRunner");
    }
    }​

    ----------My Take Profit Stop Loss and breakeven

    if (UseProfitTargetS && entryOrderS != null && entryOrderS.Name == "MyEntryLong" &&
    profitTargetS != null && (profitTargetS.OrderState == OrderState.Accepted || profitTargetS.OrderState == OrderState.Working) &&
    longTarget > GetCurrentBid())
    {
    ExitLongLimit(0, true, entryOrderS.Quantity, longTarget, "MyTargetLong", "MyEntryLong");
    }

    // trigger the trail action when the current price is further than the set distance to the stop loss
    if (UseStopLossS &&
    stopLossS != null && (stopLossS.OrderState == OrderState.Accepted || stopLossS.OrderState == OrderState.Working) &&
    longStop < GetCurrentBid())
    {
    ExitLongStopMarket(0, true, entryOrderS.Quantity, longStop, "MyStopLong", "MyEntryLong");
    }​

    if (SetBreakeven )

    {
    if(

    stopLossR != null && (stopLossR.OrderState == OrderState.Accepted || stopLossR.OrderState == OrderState.Working) &&
    Close[0] >= breakevenTriggerLong
    )
    {

    breakevenLong = Position.AveragePrice; //Define what a breakeven is. (We set it at the average filled price)
    ExitLongStopMarket(0, true, PositionSizeRunner, breakevenLong, "MyStopLong", "MyEntryLongRunner");

    myFreeBELong = false; //BE bool is false after setting stop. You can now move it around freely.
    Print("BreakEvenLong:" + breakevenLong);

    }
    }



    --------- on Execution
    protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price, int quantity,
    Cbi.MarketPosition marketPosition, string orderId, DateTime time)
    {

    Print(string.Format("{0} | OEU | execution | {1} | {2}", Time[0], time, execution.ToString()));

    if (execution.Order.OrderState != OrderState.Filled)
    return;
    ​if (entryOrderR != null && execution.Order != entryOrderS && execution.Order == entryOrderR)
    {

    if (UseProfitTargetS)
    {
    if (PrintDetails)
    Print(string.Format("{0} | OEU | placing profit target Runner", execution.Time));

    if (execution.Name == "MyEntryLongRunner" && (execution.Order.AverageFillPrice + (ProfitTargetTicks*TickSize)) >= GetCurrentBid())
    {
    profitTargetR = placeHolderOrderR;
    ExitLongLimit(0, true, entryOrderR.Quantity, execution.Order.AverageFillPrice + (ProfitTargetTicks*TickSize), "MyTargetLongRunner", "MyEntryLongRunner");
    }
    if (execution.Name == "MyEntryShortRunner" && (execution.Order.AverageFillPrice - (ProfitTargetTicks*TickSize)) <= GetCurrentAsk())
    {
    profitTargetR = placeHolderOrderR;
    ExitShortLimit(0, true, entryOrderR.Quantity, execution.Order.AverageFillPrice - (ProfitTargetTicks*TickSize), "MyTargetShortRunner", "MyEntryShortRunner");
    }
    }

    if (UseStopLossS)
    {
    if (PrintDetails)
    Print(string.Format("{0} | OEU | placing stop loss Runner", execution.Time));

    if(execution.Name == "MyEntryLongRunner" && longStop <= GetCurrentBid())
    {
    stopLossR = placeHolderOrderR;
    ExitLongStopMarket(0, true, entryOrderR.Quantity, longStop, "MyStopLongRunner", "MyEntryLongRunner");
    }
    if(execution.Name == "MyEntryShortRunner" && shortStop >= GetCurrentAsk())
    {
    stopLossR = placeHolderOrderR;
    ExitShortStopMarket(0, true, entryOrderR.Quantity, shortStop, "MyStopShortRunner", "MyEntryShortRunner");
    }
    }
    }​


    -------- OnOrderUpdate
    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 (PrintDetails)
    Print(string.Format( "{0} | OOU | order | {1} | {2}", Time[0], time, order.ToString() ));

    AssignOrderToVariable(ref order);​

    if (orderState == OrderState.Filled && ((profitTargetR != null && order == profitTargetR) ||
    (stopLossR != null && order == stopLossR)))
    {

    Print(string.Format( "{0} | OOU | stop or target filled, preventing oco actions until reset Runner", Time[0] ));

    suppressOcoR = true;
    }​

    if (!suppressOcoR && profitTargetR != null && order == profitTargetR &&
    (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
    stopLossR != null &&
    (stopLossR.OrderState == OrderState.Accepted || stopLossR.OrderState == OrderState.Working) )
    {

    Print(string.Format( "{0} | OOU | cancelling stop Runner", Time[0] ));

    CancelOrder(stopLossR);
    }​
    else if (!suppressOcoR && stopLossR != null && order == stopLossR &&
    (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
    profitTargetR != null &&
    (profitTargetR.OrderState == OrderState.Accepted ||
    profitTargetR.OrderState == OrderState.Working) )
    {

    Print(string.Format( "{0} | OOU | cancelling target Runner", Time[0] ));

    CancelOrder(profitTargetR);
    }​

    else if ( entryOrderR != null && order != entryOrderR &&
    (!UseProfitTargetS || (profitTargetR != null &&
    (profitTargetR.OrderState == OrderState.Cancelled ||
    profitTargetR.OrderState == OrderState.Rejected))) &&
    (!UseStopLossS || (stopLossR != null &&
    (stopLossR.OrderState == OrderState.Cancelled ||
    stopLossR.OrderState == OrderState.Rejected))) )
    {
    // if either the stop or target is cancelled, wait 1 tick in OBU to check
    // to see if this was because of the Exit on close occurring or if manually cancelled
    ordersCancelledR = true;

    if (PrintDetails)
    Print(string.Format( "{0} | OOU | stop or target cancelled or rejected Runner", Time[0] ));
    }​

    if ( (profitTargetR != null && profitTargetR.OrderState == OrderState.Filled && (stopLossR == null || stopLossR.OrderState == OrderState.Cancelled)) ||
    (stopLossR != null && stopLossR.OrderState == OrderState.Filled && (profitTargetR == null || profitTargetR.OrderState == OrderState.Cancelled))
    || stopLossR != null && stopLossR.OrderState == OrderState.Cancelled
    || profitTargetR != null && profitTargetR.OrderState == OrderState.Cancelled)

    {

    Print(string.Format( "{0} | OOU | resetting Runner", Time[0] ));

    entryOrderR = null;
    profitTargetR = null;
    stopLossR = null;


    }​​​​
    Attached Files

    #2
    Hello tkaboris,

    What is the specific line of code causing the error?

    If you are unsure, add prints one line above each condition, assignment, and method call. I recommend printing the line number to quickly identify where the last print appearing is in the code.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3

      I am attaching output from one trade, Strategy gets disabled when there is buystop order left hanging on the chart. Strategy opened two orders with TP and SL as Suppose to but when Breakeven occurs I think stoploss is getting lost. I am attaching output

      Comment


        #4
        Could you provide an example to ProfitChaseStopTrailExitOrdersExample how you would immplement a breakeven? That way i can reference it in my script.

        Comment


          #5
          NinjaTrader_ChelseaB
          I put up prints as you mentioned earlier to determine which line causes issue
          Last print was in OrderUpdate debug 15. It seems when breakeven happens debug15 cant get evaluated and other conditions need to be revised.

          On the chart it take profit from runner is left out and wasnt cancelled when order hit stoploss.

          Below is an ouput
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 0
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 1
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 2
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 4
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 6
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 13
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 15
          7/11/2024 6:43:00 AM | OOU | order | 7/11/2024 6:42:18 AM | orderId='f35e44221107483f9e7b647312cd18a4' account='Playback101' name='MyStopLongRunner' orderState=Accepted instrument='NQ 09-24' orderAction=Sell orderType='Stop Market' limitPrice=0 stopPrice=20960 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=184960 time='2024-07-11 06:42:18' gtd='2099-12-01' statementDate='2024-07-11'
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 0
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 1
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 2
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 4
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 6
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 13
          7/11/2024 6:43:00 AM | OOU | OrderUpdate debug 15​
          7/11/2024 6:42:18 AM Strategy 'jockey/312671451': Amended matching order at 7/11/2024 6:42:18 AM: BarsInProgress=0 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=20960.00 SignalName='MyStopLongRunner' FromEntrySignal='MyEntryLongRunner'
          BreakEvenLong:20960
          entryOrderS
          entryOrderRorderId='71915ce03c6341dca59d08853b7ef5 c2' account='Playback101' name='MyEntryLongRunner' orderState=Filled instrument='NQ 09-24' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=20960 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=20960 onBehalfOf='' id=184948 time='2024-07-11 06:42:07' gtd='2099-12-01' statementDate='2024-07-11'
          entryOrderRFilled
          Strategy 'jockey': Error on calling 'OnBarUpdate' method on bar 5018: Object reference not set to an instance of an object.
          Disabling NinjaScript strategy 'jockey/312671451'​

          and OrderUpdate Code

          region OnOrderUpdate
          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 (PrintDetails)
          Print(string.Format( "{0} | OOU | order | {1} | {2}", Time[0], time, order.ToString() ));
          Print(string.Format( "{0} | OOU | OrderUpdate debug 0", Time[0] ));
          AssignOrderToVariable(ref order);

          // the logic below is to simulate OCO when manually cancelling an order.

          // if the stop or target has filled (instead of being cancelled), nt will automatically
          // cancel any remaining orders attached to the entry's signal name.
          // prevent the OCO logic below to prevent overfills (cancelling an already cancelled order)
          Print(string.Format( "{0} | OOU | OrderUpdate debug 1", Time[0] ));
          if (orderState == OrderState.Filled && ((profitTargetS != null && order == profitTargetS) ||
          (stopLossS != null && order == stopLossS)))
          {

          Print(string.Format( "{0} | OOU | stop or target filled, preventing oco actions until reset Primary", Time[0] ));
          Print(string.Format( "{0} | OOU | OrderUpdate debug 1", Time[0] ));
          suppressOcoS = true;
          }
          Print(string.Format( "{0} | OOU | OrderUpdate debug 2", Time[0] ));
          if (orderState == OrderState.Filled && ((profitTargetR != null && order == profitTargetR) ||
          (stopLossR != null && order == stopLossR)))
          {

          Print(string.Format( "{0} | OOU | stop or target filled, preventing oco actions until reset Runner", Time[0] ));
          Print(string.Format( "{0} | OOU | OrderUpdate debug 3", Time[0] ));
          suppressOcoR = true;
          }

          // oco strings cannot be used in the managed approach. So simulate OCO here for manually cancelled orders
          // if the profit target is cancelled and the stop loss is still working, cancel the stop loss
          Print(string.Format( "{0} | OOU | OrderUpdate debug 4", Time[0] ));
          if (!suppressOcoS && profitTargetS != null && order == profitTargetS &&
          (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
          stopLossS != null &&
          (stopLossS.OrderState == OrderState.Accepted || stopLossS.OrderState == OrderState.Working) )
          {

          Print(string.Format( "{0} | OOU | cancelling stop Primary", Time[0] ));
          Print(string.Format( "{0} | OOU | OrderUpdate debug 5", Time[0] ));
          CancelOrder(stopLossS);
          }
          Print(string.Format( "{0} | OOU | OrderUpdate debug 6", Time[0] ));
          if (!suppressOcoR && profitTargetR != null && order == profitTargetR &&
          (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
          stopLossR != null &&
          (stopLossR.OrderState == OrderState.Accepted || stopLossR.OrderState == OrderState.Working) )
          {

          Print(string.Format( "{0} | OOU | cancelling stop Runner", Time[0] ));
          Print(string.Format( "{0} | OOU | OrderUpdate debug 7", Time[0] ));
          CancelOrder(stopLossR);
          }

          // if the stop loss is cancelled and the profit target is still working, cancel the profit target

          else if (!suppressOcoS && stopLossS != null && order == stopLossS &&
          (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
          profitTargetS != null &&
          (profitTargetS.OrderState == OrderState.Accepted ||
          profitTargetS.OrderState == OrderState.Working) )
          {
          Print(string.Format( "{0} | OOU | OrderUpdate debug 8", Time[0] ));
          Print(string.Format( "{0} | OOU | cancelling target Primary", Time[0] ));
          Print(string.Format( "{0} | OOU | OrderUpdate debug 9", Time[0] ));
          CancelOrder(profitTargetS);
          }
          else if (!suppressOcoR && stopLossR != null && order == stopLossR &&
          (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
          profitTargetR != null &&
          (profitTargetR.OrderState == OrderState.Accepted ||
          profitTargetR.OrderState == OrderState.Working) )
          {

          Print(string.Format( "{0} | OOU | cancelling target Runner", Time[0] ));
          Print(string.Format( "{0} | OOU | OrderUpdate debug 10", Time[0] ));
          CancelOrder(profitTargetR);
          }

          // if both the profit target and stop loss are cancelled or rejected,
          // then exit the position and reset for a new entry
          else if ( entryOrderS != null && order != entryOrderS &&
          (!UseProfitTargetS || (profitTargetS != null &&
          (profitTargetS.OrderState == OrderState.Cancelled ||
          profitTargetS.OrderState == OrderState.Rejected))) &&
          (!UseStopLossS || (stopLossS != null &&
          (stopLossS.OrderState == OrderState.Cancelled ||
          stopLossS.OrderState == OrderState.Rejected))) )
          {
          // if either the stop or target is cancelled, wait 1 tick in OBU to check
          // to see if this was because of the Exit on close occurring or if manually cancelled
          Print(string.Format( "{0} | OOU | OrderUpdate debug 11", Time[0] ));
          ordersCancelledS = true;

          if (PrintDetails)
          Print(string.Format( "{0} | OOU | stop or target cancelled or rejected Primary", Time[0] ));
          }
          else if ( entryOrderR != null && order != entryOrderR &&
          (!UseProfitTargetS || (profitTargetR != null &&
          (profitTargetR.OrderState == OrderState.Cancelled ||
          profitTargetR.OrderState == OrderState.Rejected))) &&
          (!UseStopLossS || (stopLossR != null &&
          (stopLossR.OrderState == OrderState.Cancelled ||
          stopLossR.OrderState == OrderState.Rejected))) )
          {
          // if either the stop or target is cancelled, wait 1 tick in OBU to check
          // to see if this was because of the Exit on close occurring or if manually cancelled
          Print(string.Format( "{0} | OOU | OrderUpdate debug 12", Time[0] ));
          ordersCancelledR = true;

          if (PrintDetails)
          Print(string.Format( "{0} | OOU | stop or target cancelled or rejected Runner", Time[0] ));
          }
          // end of simulated oco logic for manual cancellations
          Print(string.Format( "{0} | OOU | OrderUpdate debug 13", Time[0] ));
          // once the stop loss or profit target (or exit for flat / exit for manual cancel) fills, reset for a new entry
          if ( (profitTargetS != null && profitTargetS.OrderState == OrderState.Filled && (stopLossS == null || stopLossS.OrderState == OrderState.Cancelled)) ||
          (stopLossS != null && stopLossS.OrderState == OrderState.Filled && (profitTargetS == null || profitTargetS.OrderState == OrderState.Cancelled))
          )

          {
          Print(string.Format( "{0} | OOU | OrderUpdate debug 14", Time[0] ));
          Print(string.Format( "{0} | OOU | resetting Primary", Time[0] ));

          entryOrderS = null;
          profitTargetS = null;
          stopLossS = null;


          }
          Print(string.Format( "{0} | OOU | OrderUpdate debug 15", Time[0] ));
          if ( (profitTargetR != null && profitTargetR.OrderState == OrderState.Filled && (stopLossR == null || stopLossR.OrderState == OrderState.Cancelled)) ||
          (stopLossR != null && stopLossR.OrderState == OrderState.Filled && (profitTargetR == null || profitTargetR.OrderState == OrderState.Cancelled))
          )

          {

          Print(string.Format( "{0} | OOU | resetting Runner", Time[0] ));
          Print(string.Format( "{0} | OOU | OrderUpdate debug 16", Time[0] ));
          entryOrderR = null;
          profitTargetR = null;
          stopLossR = null;


          }
          }
          #endregion​

          Click image for larger version

Name:	image.png
Views:	157
Size:	17.7 KB
ID:	1311686
          Last edited by tkaboris; 07-24-2024, 04:20 PM.

          Comment


            #6
            Hello tkaboris,

            I've copied the ProfitChaseStopTrailExitOrdersExample and modified this to do a breakeven instead of trailing.
            BreakEvenExitOrdersTest_NT8.zip

            Your error appears to be coming from OnBarUpdate().
            Strategy 'jockey': Error on calling 'OnBarUpdate' method on bar 5018: Object reference not set to an instance of an object.
            Disabling NinjaScript strategy 'jockey/312671451'​
            ​Have you added a print above each line in OnBarUpdate()?
            Attached Files
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              hi thank you, I think its working now as expected.

              There is one issue remains when I add runner order. I mean I have primary and runner order. Runner order uses breakeven. If I am in Long and primary order(profitTargetS) hits target but runner (profitTargetR) hits breakeven then strategy doesnt reset runner order to null.
              I was wondering how to go about it




              I have atrached below my current script.


              if ( (profitTargetS != null && profitTargetS.OrderState == OrderState.Filled && (stopLossS == null || stopLossS.OrderState == OrderState.Cancelled)) ||
              (stopLossS != null && stopLossS.OrderState == OrderState.Filled && (profitTargetS == null || profitTargetS.OrderState == OrderState.Cancelled))
              )

              {


              entryOrderS = null;
              profitTargetS = null;
              stopLossS = null;
              longBreakEven = false;
              shortBreakEven = false;

              }​

              if ( (profitTargetR != null && profitTargetR.OrderState == OrderState.Filled && (stopLossR == null || stopLossR.OrderState == OrderState.Cancelled)) ||
              (stopLossR != null && stopLossR.OrderState == OrderState.Filled && (profitTargetR == null || profitTargetR.OrderState == OrderState.Cancelled))

              )

              {

              entryOrderR = null;
              profitTargetR = null;
              stopLossR = null;
              longBreakEven = false;
              shortBreakEven = false;

              }​

              Comment


                #8
                I wanted to make sure i am assigning orders correctly for both longs, shorts primary and runner order.

                What I did basically from ProfitChaseStopTrailExitOrdersExample
                I renamed entryOrder to entryOrderS to have this order as primary and stopLossS and profitTargetS respectively.
                I added entryOrderR and stopLossR and profitTargetR for runner order.
                And copied blocks of code respectively

                For some reason for my runner order short I get profit target for longs.

                Below is from print output
                entryOrderSorderId='63d772142b634ef099220663c1480a b3' account='Sim101' name='MyEntryShort' orderState=Accepted instrument='NQ 09-24' orderAction=SellShort orderType='Stop Market' limitPrice=0 stopPrice=18929.75 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=185450 time='2024-07-30 11:40:05' gtd='2099-12-01' statementDate='2024-07-30'
                profitTargetS
                stopLossS
                entryOrderRorderId='74372940d57949b48db9c090237bd3 13' account='Sim101' name='MyEntryShortRunner' orderState=Accepted instrument='NQ 09-24' orderAction=SellShort orderType='Stop Market' limitPrice=0 stopPrice=18929.75 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=185451 time='2024-07-30 11:40:05' gtd='2099-12-01' statementDate='2024-07-30'
                profitTargetRorderId='af742779c6cb435aa1ea82ebeba4 2e86' account='Sim101' name='MyTargetLongRunner' orderState=Cancelled instrument='NQ 09-24' orderAction=Sell orderType='Limit' limitPrice=18907.75 stopPrice=0 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=185445 time='2024-07-30 11:27:09' gtd='2099-12-01' statementDate='2024-07-30'
                stopLossRorderId='c652481dc5134286a3f447b07c36aee0 ' account='Sim101' name='MyStopLongRunner' orderState=Cancelled instrument='NQ 09-24' orderAction=Sell orderType='Stop Market' limitPrice=0 stopPrice=18880.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=185446 time='2024-07-30 11:27:09' gtd='2099-12-01' statementDate='2024-07-30'​


                Code:
                #region OnOrderUpdate
                        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 (PrintDetails)
                                Print(string.Format( "{0} | OOU | order | {1} | {2}", Time[0], time, order.ToString() ));
                            Print(string.Format( "{0} | OOU | OrderUpdate debug 0", Time[0] ));
                            AssignOrderToVariable(ref order);
                            
                            // the logic below is to simulate OCO when manually cancelling an order.
                
                            // if the stop or target has filled (instead of being cancelled), nt will automatically
                            // cancel any remaining orders attached to the entry's signal name.
                            // prevent the OCO logic below to prevent overfills (cancelling an already cancelled order)
                            Print(string.Format( "{0} | OOU | OrderUpdate debug 1", Time[0] ));
                            if (orderState == OrderState.Filled && ((profitTargetS != null && order == profitTargetS) ||
                                (stopLossS != null && order == stopLossS)))
                            {
                                
                                    Print(string.Format( "{0} | OOU | stop or target filled, preventing oco actions until reset Primary", Time[0] ));
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 1", Time[0] ));
                                suppressOcoS = true;
                            }
                            Print(string.Format( "{0} | OOU | OrderUpdate debug 2", Time[0] ));
                            if (orderState == OrderState.Filled && ((profitTargetR != null && order == profitTargetR) ||
                                (stopLossR != null && order == stopLossR)))
                            {
                                
                                    Print(string.Format( "{0} | OOU | stop or target filled, preventing oco actions until reset Runner", Time[0] ));
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 3", Time[0] ));
                                suppressOcoR = true;
                            }
                            
                            // oco strings cannot be used in the managed approach. So simulate OCO here for manually cancelled orders
                            // if the profit target is cancelled and the stop loss is still working, cancel the stop loss
                            Print(string.Format( "{0} | OOU | OrderUpdate debug 4", Time[0] ));
                            if (!suppressOcoS && profitTargetS != null && order == profitTargetS &&
                                (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
                                stopLossS != null &&
                                (stopLossS.OrderState == OrderState.Accepted || stopLossS.OrderState == OrderState.Working) )
                            {
                                
                                    Print(string.Format( "{0} | OOU | cancelling stop Primary", Time[0] ));
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 5", Time[0] ));
                                CancelOrder(stopLossS);
                            }
                            Print(string.Format( "{0} | OOU | OrderUpdate debug 6", Time[0] ));
                            if (!suppressOcoR && profitTargetR != null && order == profitTargetR &&
                                (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
                                stopLossR != null &&
                                (stopLossR.OrderState == OrderState.Accepted || stopLossR.OrderState == OrderState.Working) )
                            {
                                
                                    Print(string.Format( "{0} | OOU | cancelling stop Runner", Time[0] ));
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 7", Time[0] ));
                                CancelOrder(stopLossR);
                            }
                
                            // if the stop loss is cancelled and the profit target is still working, cancel the profit target
                            
                            else if (!suppressOcoS && stopLossS != null && order == stopLossS &&
                                    (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
                                    profitTargetS != null &&
                                    (profitTargetS.OrderState == OrderState.Accepted ||
                                        profitTargetS.OrderState == OrderState.Working) )
                            {
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 8", Time[0] ));
                                    Print(string.Format( "{0} | OOU | cancelling target Primary", Time[0] ));
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 9", Time[0] ));
                                CancelOrder(profitTargetS);
                            }
                            else if (!suppressOcoR && stopLossR != null && order == stopLossR &&
                                    (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
                                    profitTargetR != null &&
                                    (profitTargetR.OrderState == OrderState.Accepted ||
                                        profitTargetR.OrderState == OrderState.Working) )
                            {
                                
                                    Print(string.Format( "{0} | OOU | cancelling target Runner", Time[0] ));
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 10", Time[0] ));
                                CancelOrder(profitTargetR);
                            }
                            
                            // if both the profit target and stop loss are cancelled or rejected,
                            // then exit the position and reset for a new entry
                            else if    ( entryOrderS != null && order != entryOrderS &&
                                    (!UseProfitTargetS || (profitTargetS != null &&
                                            (profitTargetS.OrderState == OrderState.Cancelled ||
                                                profitTargetS.OrderState == OrderState.Rejected))) &&
                                    (!UseStopLossS || (stopLossS != null &&
                                            (stopLossS.OrderState == OrderState.Cancelled ||
                                                stopLossS.OrderState == OrderState.Rejected))) )
                            {
                                // if either the stop or target is cancelled, wait 1 tick in OBU to check
                                // to see if this was because of the Exit on close occurring or if manually cancelled
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 11", Time[0] ));
                                ordersCancelledS = true;
                
                                if (PrintDetails)
                                    Print(string.Format( "{0} | OOU | stop or target cancelled or rejected Primary", Time[0] ));
                            }
                            else if    ( entryOrderR != null && order != entryOrderR &&
                                    (!UseProfitTargetS || (profitTargetR != null &&
                                            (profitTargetR.OrderState == OrderState.Cancelled ||
                                                profitTargetR.OrderState == OrderState.Rejected))) &&
                                    (!UseStopLossS || (stopLossR != null &&
                                            (stopLossR.OrderState == OrderState.Cancelled ||
                                                stopLossR.OrderState == OrderState.Rejected))) )
                            {
                                // if either the stop or target is cancelled, wait 1 tick in OBU to check
                                // to see if this was because of the Exit on close occurring or if manually cancelled
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 12", Time[0] ));
                                ordersCancelledR = true;
                
                                if (PrintDetails)
                                    Print(string.Format( "{0} | OOU | stop or target cancelled or rejected Runner", Time[0] ));
                            }
                            // end of simulated oco logic for manual cancellations
                            Print(string.Format( "{0} | OOU | OrderUpdate debug 13", Time[0] ));
                            // once the stop loss or profit target (or exit for flat / exit for manual cancel) fills, reset for a new entry
                            if ((profitTargetS != null && profitTargetS.OrderState == OrderState.Filled && (stopLossS == null || stopLossS.OrderState == OrderState.Cancelled)) ||
                                (stopLossS != null && stopLossS.OrderState == OrderState.Filled && (profitTargetS == null || profitTargetS.OrderState == OrderState.Cancelled))
                                
                                )
                                
                            {
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 14", Time[0] ));
                                    Print(string.Format( "{0} | OOU | resetting Primary", Time[0] ));
                
                                
                                entryOrderS        = null;
                                profitTargetS    = null;
                                stopLossS        = null;                
                                longBreakEven = false;
                                shortBreakEven = false;
                                
                            }
                            Print(string.Format( "{0} | OOU | OrderUpdate debug 15", Time[0] ));
                //            Print("profitTargetR"+profitTargetR);
                //            Print("stopLossR"+stopLossR);
                //            Print("entryOrderR"+entryOrderR);
                //            Print("profitTargetR.OrderState"+profitTargetR.OrderState);
                //            Print("stopLossR.OrderState"+stopLossR.OrderState);
                            if ((profitTargetR != null && profitTargetR.OrderState == OrderState.Filled && (stopLossR == null || stopLossR.OrderState == OrderState.Cancelled)) ||
                                (stopLossR != null && stopLossR.OrderState == OrderState.Filled && (profitTargetR == null || profitTargetR.OrderState == OrderState.Cancelled))
                              
                                )
                                
                            {
                                
                                    Print(string.Format( "{0} | OOU | resetting Runner", Time[0] ));
                                Print(string.Format( "{0} | OOU | OrderUpdate debug 16", Time[0] ));
                                entryOrderR        = null;
                                profitTargetR    = null;
                                stopLossR        = null;
                                longBreakEven = false;
                                shortBreakEven = false;
                                
                            }
                        }
                        #endregion​
                and assigning orders
                Code:
                #region Asign Order TO variables
                        private void AssignOrderToVariable(ref Order order)
                        {
                            ......
                            if ((order.Name == "MyEntryLongRunner" || order.Name == "MyEntryShortRunner") && entryOrderR != order){
                                Print(string.Format( "{0} | OOU | AssignOrders debug 2", Time[0] ));
                                entryOrderR = order;
                            }
                            
                
                            if ((order.Name == "MyTargetLongRunner" || order.Name == "MyTargetShortRunner") && profitTargetR != order)
                                profitTargetR = order;
                
                            if ((order.Name == "MyStopLongRunner" || order.Name == "MyStopShortRunner") && stopLossR != order)
                                stopLossR = order;    
                            if (order.Name == exitNameR && exitFlatR != order)
                                exitFlatR = order;
                
                            
                            
                        }
                        #endregion​
                Last edited by tkaboris; 07-30-2024, 11:53 AM.

                Comment


                  #9
                  Hello tkaboris,

                  You are allowing multiple orders to be assigned to the same variable.

                  I would advise against this. Use a different variable for each order.
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    NinjaTrader_ChelseaB
                    Hi I have a question in regards to the ProfitChaseStopTrailExitOrdersExample specifically to ordertype placeHolderOrder.

                    for longs
                    in execution update we use
                    profitTarget = placeHolderOrder;
                    ExitLongLimit(1, true, entryOrder.Quantity, currentPtPrice, "profit target", "entry");

                    stopLoss = placeHolderOrder;
                    ExitLongStopMarket(1, true, entryOrder.Quantity, currentSlPrice, "stop loss", "entry");​

                    and when we submit order we have
                    entryOrder = placeHolderOrder;
                    EnterLong(1, 1, "entry");​


                    My question is when I have
                    for longs
                    for shorts
                    do i need to use different placeHolderOrder variables? or it should remain the same

                    Comment


                      #11
                      Hello tkaboris,

                      The placeHolderOrder is only used to make the entryOrder variable not null, as many of the conditions for sending new orders after a reset are looking for the order variable to be null.

                      placeHolderOrder can be reused and is just an empty order type object that is not null.
                      Chelsea B.NinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by NullPointStrategies, Today, 05:17 AM
                      0 responses
                      44 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
                      65 views
                      0 likes
                      Last Post NabilKhattabi  
                      Started by Deep42, 03-06-2026, 12:28 AM
                      0 responses
                      42 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