Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Exit Trade if unprofitable after N days

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

    Exit Trade if unprofitable after N days

    Hi all,

    I have a strategy that doesn't works as expected. One of the exit rules is to exit a trade Exit Trade if it's unprofitable after N days. Here's part of the code.

    Entry:
    Code:
    if (entryOrder == null && profitTakerOrder == null && stopLossOrder == null)
    {
        BackBrush = Brushes.LightGreen;
        SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Market,
            Convert.ToInt32(Math.Round(AssetAmount / Open[0], 0, MidpointRounding.ToEven)), 0, 0, "", entryName);
    }
    Exit by rule:
    Code:
    if (entryOrder != null)
    {
        if (BarsSinceEntryExecution(entryName) >= 4 && Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) <= 0)
        {
            BackBrush = Brushes.LightSalmon;
            Print(Instrument.FullName + " --- " + Time[0] + " --- ExitLongByUnprofitableRule --- " + entryOrder.ToString());
            CancelOrder(entryOrder);
        }
    }
    Furthermore i'm using the OnExecutionUpdate event.
    Code:
    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
    {
        if (execution.Order.OrderState != OrderState.Filled)
            return;
    
        Print("Execution: " + execution.ToString());
        if (entryOrder == null)
        {
            if (profitTakerOrder != null && (profitTakerOrder.OrderState == OrderState.Accepted || profitTakerOrder.OrderState == OrderState.Working))
                CancelOrder(profitTakerOrder);
            else if (stopLossOrder != null && (stopLossOrder.OrderState == OrderState.Accepted || stopLossOrder.OrderState == OrderState.Working))
                CancelOrder(stopLossOrder);
        }
    
        if (entryOrder != null && execution.Order == entryOrder)
        {
            // Stop Loss
            stopLossOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.StopMarket,
                execution.Order.Filled, 0, execution.Order.AverageFillPrice - ((execution.Order.AverageFillPrice / 100) * PctgSl), string.Empty, "Stop Loss");
    
            // Profit Taker
            profitTakerOrder = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Limit,
                execution.Order.Filled, execution.Order.AverageFillPrice + ((execution.Order.AverageFillPrice / 100) * PctgPl), 0, string.Empty, "Profit Taker");
    
            if (execution.Order.OrderState != OrderState.PartFilled)
                entryOrder = null;
        }
    
        if ((stopLossOrder != null && stopLossOrder == execution.Order) || (profitTakerOrder != null && profitTakerOrder == execution.Order))
        {
            if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
            {
                stopLossOrder = null;
                profitTakerOrder = null;
            }
        }
    }
    Would it be better to place such conditional exit rules into this event handler so that they work as expected?

    Thanks for your help.

    #2
    Hello Sweet&Sour,
    Thanks for your post.

    What specifically is happening instead of what you are expecting?
    Josh G.NinjaTrader Customer Service

    Comment


      #3
      I thought that the counter for BarsSinceEntryExecution() will be set to zero each time an order will be cancel (or or a trade will be sold). Obviously this isn't the case because BarsSinceEntryExecution() just count up.

      PG --- 05.07.2011 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:184 --- UnrealizedProfitLoss:0
      PG --- 14.02.2012 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:339 --- UnrealizedProfitLoss:0
      PG --- 19.11.2012 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:531 --- UnrealizedProfitLoss:0
      PG --- 10.01.2013 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:566 --- UnrealizedProfitLoss:0
      PG --- 14.05.2013 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:651 --- UnrealizedProfitLoss:0
      PG --- 07.06.2013 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:668 --- UnrealizedProfitLoss:0
      PG --- 13.06.2013 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:672 --- UnrealizedProfitLoss:0
      PG --- 25.06.2013 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:680 --- UnrealizedProfitLoss:0
      PG --- 04.09.2013 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:729 --- UnrealizedProfitLoss:0
      PG --- 28.01.2014 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:829 --- UnrealizedProfitLoss:0
      PG --- 19.06.2014 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:928 --- UnrealizedProfitLoss:0
      PG --- 05.02.2015 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:1087 --- UnrealizedProfitLoss:0
      PG --- 13.02.2015 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:1093 --- UnrealizedProfitLoss:0
      PG --- 22.01.2016 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:1329 --- UnrealizedProfitLoss:0
      PG --- 23.05.2016 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:1413 --- UnrealizedProfitLoss:0
      PG --- 24.05.2016 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:1414 --- UnrealizedProfitLoss:0
      PG --- 26.10.2016 22:00:00 --- ExitLongByUnprofitableRule --- BarsSinceEntryExecution:1522 --- UnrealizedProfitLoss:0

      One of my exit rules is to exit a trade if it's unprofitable after 4 days.

      Thanks...
      Last edited by Sweet&Sour; 09-05-2018, 10:33 AM.

      Comment


        #4
        You are correct in how it is supposed to work. Are you using multiple time frames or multiple instruments in this script?
        Josh G.NinjaTrader Customer Service

        Comment


          #5
          Single timeframe and single instrument.

          I just solved it using a little workaround. After SubmitOrderUnmanaged, i set an int called barCount to the value of the CurrentBar. Once i'm having an orderEntry object, i'm checking for...

          Code:
          (CurrentBar - barCounter) >= 4 && Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) <= 0
          .,, which works however my next problem just sits around the corner. When i'm reaching the point to cancel my orderEntry object, nothing is executed and the trade just stays in the market unless the stop loss at a lower level is reached.

          Code:
          if (entryOrder != null)
          {
              Print(Instrument.FullName + " --- " + Time[0] + " --- barCounter:" + barCounter + " " + CurrentBar + " " + Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]));
              if ((CurrentBar - barCounter) >= 4 && Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) <= 0)
              {
                  BackBrush = Brushes.LightSalmon;
                  CancelOrder(entryOrder);
              }
          }
          Any ideas?
          Last edited by Sweet&Sour; 09-05-2018, 10:58 AM.

          Comment


            #6
            If you put a Print() inside that condition do you see that it is actually becoming true?
            If you do see that it is becoming true, have you turned on TraceOrders?
            Last edited by NinjaTrader_JoshG; 09-05-2018, 01:55 PM.
            Josh G.NinjaTrader Customer Service

            Comment


              #7
              Attached is a screenshot which shows on candle 1371 that a trade was raised at candle 1366 and 5 candles later the PL was -236.5$.

              TraceOrder only shows the enter long trade, the stop loss, the profit taker and the stop loss raised, later on 7th of jan. 2016.
              Attached Files

              Comment


                #8
                Attached is the Code. An Indicator and a Strategy File. Take UNH Daily in Dez. 2016 over Kinetick EoD Datafeed.
                Attached Files

                Comment


                  #9
                  Using the output we can help you to decide why the condition is evaluating as true or false. Here is a link to a forum post that demonstrates how to use prints to understand behavior.



                  Please include the outputs from your prints in your response so we can assist with understanding why the condition is evaluating how it is.
                  Josh G.NinjaTrader Customer Service

                  Comment


                    #10
                    See attached screenshots after printing all all necessary informations like orders, executions and conditions. Stating from Bar 113, the cancel order should be raised as the condition is through but only on Bar 131, the profit taker comes in.
                    Attached Files

                    Comment


                      #11
                      Ok i've got it. It's a mistake in the OnExecutionUpdate. If execution.Order.OrderState != OrderState.PartFilled the entryOrder object will be set to null. This is the case on Bar 108, right after the all orders (submit, stop loss and profit taker) have been placed. This is why the entryOrder object is null when dealing with Bar 112/113.

                      The code for "execution.Order.OrderState != OrderState.PartFilled" is originated from https://ninjatrader.com/support/foru...ead.php?t=7499 so there seems to be a little bug in this sample.

                      Code:
                      // Resets the entryOrder object to null after the order has been filled
                      if (execution.Order.OrderState != OrderState.PartFilled)
                           entryOrder = null;
                      So please advise how can i change this condition without messing up the order handling framework. I cannot cancel an order without having a valid entryOrder object

                      Code:
                      CancelOrder(entryOrder);
                      Attached Files
                      Last edited by Sweet&Sour; 09-05-2018, 04:11 PM.

                      Comment


                        #12
                        I do not see the mistake in SampleOnOrderUpdate. It looks to me like your logic is different than that sample so I would not expect for those lines to behave the same way. Based on the snippet below, what is likely happening is the order object is being set to null prematurely
                        Code:
                        if (entryOrder != null && execution.Order == entryOrder)
                                    {
                                        if (execution.Order.OrderState != OrderState.PartFilled)
                                            entryOrder = null;
                                    }
                        You should be filtering what order states are allowed to be compared here if you want to use similar logic to the sample. For example, this is what the SampleOnOrderUpdate script uses as its filter condition (this logic is absent in your script).
                        Code:
                        if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                        and then it has the snippet you mentioned.
                        Code:
                        if (execution.Order.OrderState != OrderState.PartFilled)
                        						entryOrder = null;
                        Josh G.NinjaTrader Customer Service

                        Comment


                          #13
                          Hi Josh,

                          Changed the condition handler in OnExecutionUpdate according to https://ninjatrader.com/support/foru...ead.php?t=7499 but the issue is still the same. For more details, have a look at the attachment.

                          Thanks...
                          Attached Files

                          Comment


                            #14
                            Hello Sweet&Sour,

                            Thank you for your response.

                            From my review of your strategy you are only cancelling the entry order which would have already filled and thus be non-existent in the scenario. You wish to close the position when the profit is less than zero, can you provide detail on how you are attempting to close the position at this point through the cancelling of the entry order?

                            I look forward to your response.

                            Comment


                              #15
                              Code:
                              // Submit order if there is no existing order
                              if (entryOrder == null && profitTakerOrder == null && stopLossOrder == null)
                              {
                                  BackBrush = Brushes.LightGreen;
                                  SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Market,
                                      Convert.ToInt32(Math.Round(AssetAmount / Open[0], 0, MidpointRounding.ToEven)), 0, 0, "", entryName);
                                  barCounter = CurrentBar;
                              }
                              
                              // Cancel order if condition TradeLength <= MaxTradeLength and PL is leq 0
                              if (entryOrder != null)
                              {
                                 BackBrush = Brushes.LightSalmon;               
                                 if ((CurrentBar - barCounter) >= MaxTradeLength && Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) <= 0)
                                 {
                                    CancelOrder(entryOrder);           
                                 }
                              }

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Today, 05:17 AM
                              0 responses
                              37 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