Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Exit and reverse position

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

    Exit and reverse position

    Hi,

    I have been having trouble of using EnterStopLimit orders to exit and reverse position at the same time. Let say DefaultQuantity = 1, after my strategy pyramiding the positions (say current position = long 2 contracts), a sell signal occurs to warrant a short position, I use
    EnterShortStopLimit(0, true, DefaultQuantity, Low[0], Low[0], "sell");
    to trigger a short position. I expect NT will close out the 2 lots and short 1 lot. However, when I looked at the execution log, NT just closed out 1 lot and sold 1 lot...effectively ended up with a flat position rather than a short position. Is it a bug or is there any ways to get around the issue?
    thx.

    #2
    imagineer, this is correct all Enter() method should reverse if needed. Is this happening for both your strategy and account positions? If you see a mismatch only in the account position, you would need to ensure proper synching at strategy startup - http://www.ninjatrader-support.com/H...tPosition.html
    BertrandNinjaTrader Customer Service

    Comment


      #3
      I have only back-tested the strategy and didn't trade it live. I found the issue through the chart and execution report in the strategy analyzer. Please help.

      Comment


        #4
        imagineer, please print the actual position from the strategy to the output window to debug this further - http://www.ninjatrader-support.com/H.../Quantity.html

        Then post the outputs here...
        BertrandNinjaTrader Customer Service

        Comment


          #5
          Hi Bertrand,

          I copy the main code for your reference below. The output is attached as you suggested. I really appreciate your help.


          protected override void Initialize()
          {
          SMA(Fast).Plots[0].Pen.Color = Color.Orange;
          SMA(Slow).Plots[0].Pen.Color = Color.Green;
          TraceOrders = false;
          Add(SMA(Fast));
          Add(SMA(Slow));
          ExitOnClose = true;
          CalculateOnBarClose = true;
          }

          /// <summary>
          /// Called on each bar update event (incoming tick)
          /// </summary>
          protected override void OnBarUpdate()
          {Print(Position.MarketPosition.ToString() + " " + Position.Quantity.ToString());
          tryToBuyJustTriggered = false;
          tryToSellJustTriggered = false;

          if (CrossAbove(SMA(Fast), SMA(Slow), 1))
          {
          TryToBuy();
          tryToBuyJustTriggered = true;
          }
          else if (CrossBelow(SMA(Fast), SMA(Slow), 1))
          {
          TryToSell();
          tryToSellJustTriggered = true;
          }

          if (entryOrder != null) // amend orders
          {
          if ((entryOrder.Action==Action.Buy || entryOrder.Action==Action.BuyToCover) && tryToBuyJustTriggered==false) TryToBuy();
          else if ((entryOrder.Action==Action.SellShort || entryOrder.Action==Action.Sell) && tryToSellJustTriggered==false) TryToSell();
          }

          }

          private void TryToBuy()
          {
          if (Position.MarketPosition==MarketPosition.Short)
          {
          if (stopOrder != null)
          {
          CancelOrder(stopOrder); //opposite entry orders will be ignored if stop not canceled first
          }
          orderQty = Position.Quantity + DefaultQuantity;
          }
          else orderQty = DefaultQuantity;

          entryOrder = EnterLongStopLimit(0, true, orderQty, High[0] + TickSize, High[0] + TickSize, "buy");
          }


          private void TryToSell()
          {
          if (Position.MarketPosition==MarketPosition.Long)
          {
          if (stopOrder!=null)
          {
          CancelOrder(stopOrder); //opposite entry orders will be ignored if stop not canceled first
          }
          orderQty = Position.Quantity + DefaultQuantity;
          }
          else orderQty = DefaultQuantity;

          entryOrder = EnterShortStopLimit(0, true, orderQty, Low[0] - TickSize, Low[0] - TickSize, "sell");
          }


          protected override void OnOrderUpdate(IOrder order)
          {
          if (entryOrder != null && entryOrder.Token == order.Token)
          {
          // Reset the entryOrder object to null if order was cancelled without any fill
          if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
          {
          entryOrder = null;
          }
          }
          if (stopOrder != null && stopOrder.Token == order.Token)
          {
          // Reset the stopOrder object to null if OCO
          if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
          {
          stopOrder = null;
          }
          }
          }

          protected override void OnExecution(IExecution execution)
          {
          if (entryOrder != null && entryOrder.Token == execution.Order.Token)
          {
          if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
          {
          if (execution.Order.Action == Action.Buy)
          {
          protectiveSellStopPrice = MIN(Low, 2)[0] - 100 * TickSize;
          stopOrder = ExitLongStop(0, true, Position.Quantity, protectiveSellStopPrice, "SellStop", "buy");
          }
          if (execution.Order.Action == Action.SellShort)
          {
          protectiveBuyStopPrice = MAX(High, 2)[0] + 100 * TickSize;
          stopOrder = ExitShortStop(0, true, Position.Quantity, protectiveBuyStopPrice, "BuyStop", "sell");
          }
          entryOrder = null;
          }
          }


          if (stopOrder != null && stopOrder.Token == execution.Order.Token)
          {
          if (execution.Order.OrderState == OrderState.Filled)
          {
          stopOrder = null;
          }
          Attached Files

          Comment


            #6
            imagineer, thanks - please activate the TraceOrders option and check the output window if you get 'ignored' orders when potentially running into the 'Internal Order Handling Rules' - http://www.ninjatrader-support.com/H...verview36.html ( botton section of this link )
            BertrandNinjaTrader Customer Service

            Comment


              #7
              Hi Bertrand, I forgot to post the variables section...

              #region Variables
              private int fast = 10;
              private int slow = 25;
              private IOrder entryOrder = null;
              private IOrder stopOrder = null;
              private double protectiveBuyStopPrice, protectiveSellStopPrice;
              private bool tryToBuyJustTriggered, tryToSellJustTriggered;
              private int orderQty;
              #endregion

              Comment


                #8
                Thanks looks good, did you try my suggestions from the previous post? You may need to work in waiting for cancel confirmation of your CancelOrders's before changing the quantity based on this.
                BertrandNinjaTrader Customer Service

                Comment


                  #9
                  got it. thanks Bertrand.

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by ChartTourist, Today, 08:22 AM
                  0 responses
                  3 views
                  0 likes
                  Last Post ChartTourist  
                  Started by LiamTwine, Today, 08:10 AM
                  0 responses
                  2 views
                  0 likes
                  Last Post LiamTwine  
                  Started by Balage0922, Today, 07:38 AM
                  0 responses
                  5 views
                  0 likes
                  Last Post Balage0922  
                  Started by JoMoon2024, Today, 06:56 AM
                  0 responses
                  6 views
                  0 likes
                  Last Post JoMoon2024  
                  Started by Haiasi, 04-25-2024, 06:53 PM
                  2 responses
                  19 views
                  0 likes
                  Last Post Massinisa  
                  Working...
                  X