• If this is your first visit, you will have to register before you can post. To view messages, please scroll below and select the forum that you would like to visits. Questions? Be sure to check out the Forum FAQ.

Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

EnterLimit Order and Reverse

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

    EnterLimit Order and Reverse

    Hello,

    I have changed the ninjatrader SampleOnOrderUpdate_NT7.zip sample code with EnterLongLimit and EnterShortLimit for enter and reverse enter.

    I'd like to enter limit with limit in 3 ticks around the price.
    I'd like to reverse the order at 3 ticks of target.

    I enter with 4 ticks of stop loss and 8 ticks of target

    But I can enter reverse, only enter after the stop loss or target

    I attach the source code

    http://ninjatrader.com/support/forum...ead.php?t=7499

    I get the An Enter() method to submit an entry order at '' has been ignored. Please search.. in the log tab

    Best Regards
    David
    Attached Files
    Last edited by davidgamo; 06-23-2016, 12:59 PM.

    #2
    Hello davidgamo, and thank you for your question.

    I am providing the original and modified end sections of OnBarUpdate for review.

    Original :
    Code:
    
                    entryOrder = EnterLong(1, "MyEntry");
                }
                
                /* If we have a long position and the current price is 4 ticks in profit, raise the stop-loss order to breakeven.
                We use (7 * (TickSize / 2)) to denote 4 ticks because of potential precision issues with doubles. Under certain
                conditions (4 * TickSize) could end up being 3.9999 instead of 4 if the TickSize was 1. Using our method of determining
                4 ticks helps cope with the precision issue if it does arise. */
                if (Position.MarketPosition == MarketPosition.Long && Close[0] >= Position.AvgPrice + (7 * (TickSize / 2)))
                {
                    // Checks to see if our Stop Order has been submitted already
                    if (stopOrder != null && stopOrder.StopPrice < Position.AvgPrice)
                    {
                        // Modifies stop-loss to breakeven
                        stopOrder = ExitLongStop(0, true, stopOrder.Quantity, Position.AvgPrice, "MyStop", "MyEntry");
                    }
                }
            }
    Modified :
    Code:
    
                    entryOrder = EnterLongLimit(0, true, 1, (GetCurrentAsk() + (3 * TickSize)), "MyEntry");
                }
                if (entryOrder == null && Close[0] <= Open[0])
                {
                    /* The entryOrder object will take on a unique ID from our EnterLong()
                    that we can use later for order identification purposes in the OnOrderUpdate() method. */
                    entryOrder = EnterShortLimit(0, true, 1, (GetCurrentBid() - (3 * TickSize)), "MyEntry");
                }
                // Checks to see if our Stop Order has been submitted already to reverse at 3 ticks
                if (Position.MarketPosition == MarketPosition.Long && (Close[0] >= (Position.AvgPrice + (6 * (TickSize / 2)))))
                {
                    if (stopOrder != null && stopOrder.StopPrice < Position.AvgPrice)
                        entryOrder = EnterShortLimit(0, true, 1, (GetCurrentAsk() + (3 * TickSize)), "MyEntry");
                }
                // Checks to see if our Stop Order has been submitted already
                if (Position.MarketPosition == MarketPosition.Short && (Close[0] <= (Position.AvgPrice - (6 * (TickSize / 2)))))
                {
                    if (stopOrder != null && stopOrder.StopPrice > Position.AvgPrice)
                        entryOrder = EnterLongLimit(0, true, 1, (GetCurrentBid() - (3 * TickSize)), "MyEntry");
                }
                /*
                if (Position.MarketPosition == MarketPosition.Long && Close[0] >= Position.AvgPrice + (7 * (TickSize / 2)))
                {
                    // Checks to see if our Stop Order has been submitted already
                    if (stopOrder != null && stopOrder.StopPrice < Position.AvgPrice)
                    {
                        // Modifies stop-loss to breakeven
                        stopOrder = ExitLongStop(0, true, stopOrder.Quantity, Position.AvgPrice, "MyStop", "MyEntry");
                    }
                }
                */
            }
    I emphasized the parts that obey the Internal Order Handling Rules in the Original, and do not obey them in the Modified. Here are those rules :

    Originally posted by http://ninjatrader.com/support/helpGuides/nt7/managed_approach.htm
    NinjaTrader is a real-time live trading platform and thus we need to ensure that we prevent situations in real-time where you may have multiple orders working accomplishing the same task. An example of this would be if your strategy had a target limit order for 1 contract working, but then your strategy was also programmed to reverse the position at the price very close to the target limit order. Submitting both orders is dangerous since it could lead to a larger position than the strategy is designed to enter if both orders got filled in quick succession by the exchange! To prevent these types of situations, there are some "under the hood" rules that a NinjaScript strategy follows when order methods are called.

    Note: These rules do not apply to market orders like ExitLong() or ExitShort().

    For the most part, you do not need to be intimately familiar with these rules as you develop your strategies, its all taken care of for you internal within a strategy. If a rule is violated, you will be notified through an error log in the Control Center log tab when running a strategy in real-time or in a backtest.

    The following rules are true per unique signal name:


    Methods that generate orders to enter a position will be ignored if:
    A position is open and an order submitted by an exit method (ExitLongLimit() for example) is active and the order is used to open a position in the opposite direction
    A position is open and an order submitted by a set method (SetStopLoss() for example) is active and the order is used to open a position in the opposite direction
    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
    The entry signal name is not unique

    Methods that generate orders to exit a position will be ignored if:
    A position is open 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
    A position is open and an order submitted by a set method (SetStopLoss() for example) is active

    Set() methods that generate orders to exit a position will be ignored if:
    A position is open 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
    A position is open and an order submitted by an exit method (ExitLongLimit() for example) is active
    From these rules, we can see that you can not enter on the long and short sides of the market at the same time in the same strategy. You will either need to use unmanaged order entry, http://ninjatrader.com/support/helpG...d_approach.htm , and manually ensure the orders you are placing are legal and fulfilled by your broker, or you will need to modify your strategy so that all orders are on the same side of the market.

    Please let us know if there are any other ways we can help.
    Jessica P.NinjaTrader Customer Service

    Comment


      #3
      Hello

      I have changed the code, but the EnterLong/ShortLimit don't work for reverse order with the order opened. I can use the EnterLong/Short for reverse order. Could you test de code?
      You can debug the print output console

      And I dont know why in the first OrderLongLimit the price is so far from the current Price
      http://screencast.com/t/0yKyhoDC
      I use the configuration
      http://screencast.com/t/1hao1wPnlbj

      Best Regards
      David


      /// <summary>
      /// Sample demonstrating the use of the OnOrderUpdate() method.
      /// </summary>
      [Description("Sample strategy demonstrating a use case involving the OnOrderUpdate() method")]
      public class SampleOnOrderUpdate : Strategy
      {
      #region Variables
      private IOrder entryOrder = null; // This variable holds an object representing our entry order
      private IOrder stopOrder = null; // This variable holds an object representing our stop loss order
      private IOrder targetOrder = null; // This variable holds an object representing our profit target order
      #endregion

      /// <summary>
      /// This method is used to configure the strategy and is called once before any strategy method is called.
      /// </summary>
      protected override void Initialize()
      {
      CalculateOnBarClose = true;
      }

      /// <summary>
      /// Called on each bar update event (incoming tick)
      /// </summary>
      protected override void OnBarUpdate()
      {
      if (CurrentBar <= BarsRequired)
      return;
      // Submit an entry limit order if we currently don't have an entry order open
      if (entryOrder == null && Close[0] > Open[0])
      {
      entryOrder = EnterLongLimit(0, true, 1, (GetCurrentAsk() + (3 * TickSize)), "MyEntry");
      }
      if (entryOrder == null && Close[0] <= Open[0])
      {
      entryOrder = EnterShortLimit(0, true, 1, (GetCurrentBid() - (3 * TickSize)), "MyEntry");
      }
      // Checks to see if our Stop Order has been submitted already to reverse at 3 ticks
      if (Position.MarketPosition == MarketPosition.Long && (Close[0] >= (Position.AvgPrice + (6 * (TickSize / 2)))))
      {
      if (stopOrder != null && stopOrder.StopPrice < Position.AvgPrice)
      {
      Print("Short:" + stopOrder.StopPrice.ToString() + " Pos:" + Position.AvgPrice.ToString());
      // not work
      entryOrder = EnterShortLimit(0, true, 1, (GetCurrentAsk() + (3 * TickSize)), "MyEntry");
      // work
      //entryOrder = EnterShort(1, "MyEntry");
      }
      }
      // Checks to see if our Stop Order has been submitted already to reverse at 3 ticks
      if (Position.MarketPosition == MarketPosition.Short && (Close[0] <= (Position.AvgPrice - (6 * (TickSize / 2)))))
      {
      if (stopOrder != null && stopOrder.StopPrice > Position.AvgPrice)
      {
      Print("Long:" + stopOrder.StopPrice.ToString() + " Pos:" + Position.AvgPrice.ToString());
      // not work
      entryOrder = EnterLongLimit(0, true, 1, (GetCurrentBid() - (3 * TickSize)), "MyEntry");
      // work
      //entryOrder = EnterLong(1, "MyEntry");
      }
      }
      /*
      if (Position.MarketPosition == MarketPosition.Long && Close[0] >= Position.AvgPrice + (7 * (TickSize / 2)))
      {
      // Checks to see if our Stop Order has been submitted already
      if (stopOrder != null && stopOrder.StopPrice < Position.AvgPrice)
      {
      // Modifies stop-loss to breakeven
      stopOrder = ExitLongStop(0, true, stopOrder.Quantity, Position.AvgPrice, "MyStop", "MyEntry");
      }
      }
      */
      }

      /// <summary>
      /// Called on each incoming order event
      /// </summary>
      protected override void OnOrderUpdate(IOrder order)
      {
      // Handle entry orders here. The entryOrder object allows us to identify that the order that is calling the OnOrderUpdate() method is the entry order.
      if (entryOrder != null && entryOrder == order)
      {
      // Reset the entryOrder object to null if order was cancelled without any fill
      if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
      {
      entryOrder = null;
      }
      }
      }

      /// <summary>
      /// Called on each incoming execution
      /// </summary>
      protected override void OnExecution(IExecution execution)
      {
      /* We advise monitoring OnExecution to trigger submission of stop/target orders instead of OnOrderUpdate() since OnExecution() is called after OnOrderUpdate()
      which ensures your strategy has received the execution which is used for internal signal tracking. */
      if (entryOrder != null && entryOrder == execution.Order)
      {
      if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
      {
      if (Position.MarketPosition == MarketPosition.Long)
      {
      // Stop-Loss order 10 ticks below our entry price
      stopOrder = ExitLongStop(0, true, execution.Order.Filled, execution.Order.AvgFillPrice - 30 * TickSize, "MyStop", "MyEntry");

      // Target order 10 ticks above our entry price
      targetOrder = ExitLongLimit(0, true, execution.Order.Filled, execution.Order.AvgFillPrice + 30 * TickSize, "MyTarget", "MyEntry");
      }
      if (Position.MarketPosition == MarketPosition.Short)
      {
      // Stop-Loss order 10 ticks above our entry price
      stopOrder = ExitShortStop(0, true, execution.Order.Filled, execution.Order.AvgFillPrice + 30 * TickSize, "MyStop", "MyEntry");

      // Target order 10 ticks below our entry price
      targetOrder = ExitShortLimit(0, true, execution.Order.Filled, execution.Order.AvgFillPrice - 30 * TickSize, "MyTarget", "MyEntry");
      }
      // Resets the entryOrder object to null after the order has been filled
      if (execution.Order.OrderState != OrderState.PartFilled)
      {
      entryOrder = null;
      }
      }
      }

      // Reset our stop order and target orders' IOrder objects after our position is closed.
      if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
      {
      if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
      {
      stopOrder = null;
      targetOrder = null;
      }
      }
      }

      /// <summary>
      /// Called on each incoming position event
      /// </summary>
      protected override void OnPositionUpdate(IPosition position)
      {
      // Print our current position to the lower right hand corner of the chart
      DrawTextFixed("MyTag", position.ToString(), TextPosition.BottomRight);
      }

      #region Properties
      #endregion
      }
      Last edited by davidgamo; 06-24-2016, 04:04 AM.

      Comment


        #4
        Hello davidgamo,

        I believe I was unclear. What I was trying to draw attention to, is that your strategy can not enter both long and short at the same time in the same market.

        Thank you for providing a complete code sample. I will test your code and return to you with my findings.
        Jessica P.NinjaTrader Customer Service

        Comment


          #5
          Hello davidgamo,

          I noticed a couple things when running this script. I hope this information proves valuable to you as you debug this script.

          • I noticed you were using GetCurrentAsk and GetCurrentBid in your script, without any check to see whether historical or live data are to be processed. While this was something I could not replicate on my end, this may be contributing to your limit order being placed far away from the market price. GetCurrentAsk and GetCurrentBid only work with live data. I would recommend using an if(! Historical) section in your code, or using a multi-series script after ensuring your provider gives you historical ask / bid data.

            This discussion will prove valuable if you decide to use a multi-series script for historical bid / ask
            http://ninjatrader.com/support/forum...ad.php?t=45934

            This page in the help guide will let you know if your provider provides historical bid / ask data
            http://ninjatrader.com/support/helpG...rical_data.htm
          • When I ran your script, I got this message :

            An Enter() method to submit an entry order at '17-Apr-16 16:02:45' has been ignored. Please search on the term 'Internal Order Handling Rules' in the Help Guide for detailed explanation.

            This indicates that at some point, your script goes long and short at the same time.

            To debug this, I would comment out all the EnterShort calls, copy them, paste them as EnterLong calls, re-run your strategy, and then one-by-one turn these back into EnterShort calls until you find out which EnterShort call is producing this message.
          • When you would like to reverse, I would recommend closing your position first, and then reversing inside of OnExecution instead of OnBarUpdate after ensuring you have successfully flattened.
          • If you are experiencing your price points being passed without being filled for several ticks, please consider market orders. Limit orders only protect you in one direction, and do not enable your trade desk to enter at an earliest available price. Limit orders are good for risk management, market orders are good for guaranteeing you get into a trade. Many instruments have a no-bust range which will limit market order slippage which you can research.

          Please let us know if there are any other ways we can help.
          Jessica P.NinjaTrader Customer Service

          Comment


            #6
            Hello,

            I have changed the source code:

            1) Not enter in historical data
            2) EnterLimit High[0] or Low[0] + 10 tick
            3) Reverse order after 3 ticks from Enter PRice
            4) Stop loss and target = 20 ticks from Enter Price

            1),3),4) are ok but 2) the EnterLimit never enter at 10 ticks

            I can see recording a video:

            1) EnterShortLimit at 10 tick from price Enter/ Low it's ok
            http://screencast.com/t/GoHeDLdYDxU
            2) Finally the order enter near from Price, no at the real EnterShortLimit Price
            http://screencast.com/t/E1Jik7sJXZ7
            It's look like that it's enter at market price


            You can debug it with the print output window.
            Could you test the source code to fix it?

            Best Regards


            [Description("Sample strategy demonstrating a use case involving the OnOrderUpdate() method")]
            public class SampleOnOrderUpdate : Strategy
            {
            #region Variables
            private IOrder entryOrder = null; // This variable holds an object representing our entry order
            private IOrder stopOrder = null; // This variable holds an object representing our stop loss order
            private IOrder targetOrder = null; // This variable holds an object representing our profit target order

            private int reverse = 0;
            #endregion

            /// <summary>
            /// This method is used to configure the strategy and is called once before any strategy method is called.
            /// </summary>
            protected override void Initialize()
            {
            CalculateOnBarClose = true;
            }

            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
            if (CurrentBar <= BarsRequired)
            return;
            if (Historical)
            return;

            // Submit an entry limit order if we currently don't have an entry order open
            if (entryOrder == null && stopOrder == null && Close[0] > Open[0])
            {
            Print("Long: Pos:" + ((High[0] + (10 * TickSize))).ToString());
            entryOrder = EnterLongLimit(0, true, 1, (High[0] + (10 * TickSize)), "MyEntry");
            }
            if (entryOrder == null & stopOrder == null && Close[0] <= Open[0])
            {
            Print("Short: Pos:" + ((Low[0] - (10 * TickSize))).ToString());
            entryOrder = EnterShortLimit(0, true, 1, (Low[0] - (10 * TickSize)), "MyEntry");
            }
            if (reverse == 1)
            {
            reverse = 0;
            Print("Reverse Long: Pos:" + ((High[0] + (10 * TickSize))).ToString());
            entryOrder = EnterLongLimit(0, true, 1, (High[0] + (10 * TickSize)), "MyEntry");
            }
            if (reverse == -1)
            {
            Print("Reverse Short: Pos:" + ((Low[0] - (10 * TickSize))).ToString());
            entryOrder = EnterShortLimit(0, true, 1, (Low[0] - (10 * TickSize)), "MyEntry");
            reverse = 0;
            }

            // Checks to see if our Stop Order has been submitted already to reverse at 3 ticks
            //if (Position.MarketPosition == MarketPosition.Long && (Close[0] >= (Position.AvgPrice + (6 * (TickSize / 2)))))
            if (Position.MarketPosition != MarketPosition.Flat && ((Close[0] >= (Position.AvgPrice + (6 * (TickSize / 2))))
            || (Close[0] <= (Position.AvgPrice - (6 * (TickSize / 2))))))
            {
            //if (stopOrder != null && stopOrder.StopPrice < Position.AvgPrice)
            if (stopOrder != null && stopOrder.StopPrice != 0)
            {

            if (Position.MarketPosition == MarketPosition.Short)
            {
            Print("ExitShort");
            reverse = 1;
            ExitShort("MyEntry");
            }
            if (Position.MarketPosition == MarketPosition.Long)
            {
            Print("ExitLong");
            reverse = -1;
            ExitLong("MyEntry");
            }
            }
            }

            /*
            if (Position.MarketPosition == MarketPosition.Long && Close[0] >= Position.AvgPrice + (7 * (TickSize / 2)))
            {
            // Checks to see if our Stop Order has been submitted already
            if (stopOrder != null && stopOrder.StopPrice < Position.AvgPrice)
            {
            // Modifies stop-loss to breakeven
            stopOrder = ExitLongStop(0, true, stopOrder.Quantity, Position.AvgPrice, "MyStop", "MyEntry");
            }
            }
            */
            }

            /// <summary>
            /// Called on each incoming order event
            /// </summary>
            protected override void OnOrderUpdate(IOrder order)
            {
            // Handle entry orders here. The entryOrder object allows us to identify that the order that is calling the OnOrderUpdate() method is the entry order.
            if (entryOrder != null && entryOrder == order)
            {
            // Reset the entryOrder object to null if order was cancelled without any fill
            if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
            {
            entryOrder = null;
            }
            }
            }

            /// <summary>
            /// Called on each incoming execution
            /// </summary>
            protected override void OnExecution(IExecution execution)
            {
            /* We advise monitoring OnExecution to trigger submission of stop/target orders instead of OnOrderUpdate() since OnExecution() is called after OnOrderUpdate()
            which ensures your strategy has received the execution which is used for internal signal tracking. */
            if (entryOrder != null && entryOrder == execution.Order)
            {
            if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
            {
            if (Position.MarketPosition == MarketPosition.Long)
            {
            // Stop-Loss order 10 ticks below our entry price
            stopOrder = ExitLongStop(0, true, execution.Order.Filled, execution.Order.AvgFillPrice - 20 * TickSize, "MyStop", "MyEntry");

            // Target order 10 ticks above our entry price
            targetOrder = ExitLongLimit(0, true, execution.Order.Filled, execution.Order.AvgFillPrice + 20 * TickSize, "MyTarget", "MyEntry");
            }
            if (Position.MarketPosition == MarketPosition.Short)
            {
            // Stop-Loss order 10 ticks above our entry price
            stopOrder = ExitShortStop(0, true, execution.Order.Filled, execution.Order.AvgFillPrice + 20 * TickSize, "MyStop", "MyEntry");

            // Target order 10 ticks below our entry price
            targetOrder = ExitShortLimit(0, true, execution.Order.Filled, execution.Order.AvgFillPrice - 20 * TickSize, "MyTarget", "MyEntry");
            }
            // Resets the entryOrder object to null after the order has been filled
            if (execution.Order.OrderState != OrderState.PartFilled)
            {
            // Removed
            //entryOrder = null;
            Print("ENull OnExecution: " + execution.Order.OrderState.ToString());
            }
            }
            }

            // Reset our stop order and target orders' IOrder objects after our position is closed.
            if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
            {
            if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
            {
            stopOrder = null;
            targetOrder = null;
            // Added
            entryOrder = null;
            Print("ENull OnExecution: Stop & Target" + execution.Order.OrderState.ToString());
            }
            }
            }

            /// <summary>
            /// Called on each incoming position event
            /// </summary>
            protected override void OnPositionUpdate(IPosition position)
            {
            // Print our current position to the lower right hand corner of the chart
            DrawTextFixed("MyTag", position.ToString(), TextPosition.BottomRight);
            }

            #region Properties
            #endregion
            }

            Comment


              #7
              Hello davidgamo,

              While debugging your custom code is beyond the scope of the support we usually provide, after visually inspecting your modified code, I have noticed at least one path which can violate internal order handling rules, and which can prevent your trades from being entered, including until several ticks after you would like them to be entered. The one I noticed starts with the fact that this condition ...

              Code:
              if (entryOrder == null && stopOrder == null && Close[0] > Open[0])
              ... and this condition ...

              Code:
              if (reverse == -1)
              can both be true, since reverse is updated on the previous bar and entryOrder is nullified every time any entryOrder is filled. The following sequence of events is an example :

              • You place an enterLongLimit order, and set entryOrder to this order
              • You touch the market price due to a market jump and enter a long position
              • This order fills, and you nullify entryOrder
              • You are in a long position. You exit this position and set reverse to -1
              • On the next tick, all of the following are now true :
                • entryOrder == null
                • stopOrder == null
                • Close[0] > Open[0]
                • reverse == -1
              • You attempt to enter long and short at the same time, causing an error


              I recommend, as a debugging strategy, ensuring only one of entryOrder or stopOrder can be set per call to OnBarUpdate, then ensuring that entryOrder can only ever be set exactly once per OnBarUpdate call, and finally, providing the same guarantee for stopOrder . You can use Print statements on the line immediately following any place where entryOrder or stopOrder appears on the left side of an equals sign, along with an extra Print statement on the first line of OnBarUpdate, to ensure these guarantees are being met.
              Jessica P.NinjaTrader Customer Service

              Comment


                #8
                Hello Jessica P.

                Thanks for your visually inspecting of my modified code, but in real time never violate internal order handling rules because

                if (entryOrder == null && stopOrder == null && Close[0] > Open[0])
                ... and this condition ...
                if (reverse == -1)
                Never can both be true. You can test it on real time and you can see on the output window console something like:

                Short: Pos:9500
                ENull OnExecution: Filled
                ExitShort
                Reverse Long: Pos:9509
                ENull OnExecution: Filled
                ExitLong
                In the source code you can see the print statements on the line before any place where entryOrder or ExitOrder

                It's possible you test the strategy in realtime. If It's not possible or you don't know, could you send me the contact of other coworker that could help me.

                If you prefer you can test a simple versión of the code, with only the entry Limit order at 10 ticks. You can test the order never enter at 10 tick. The order always enter at market:


                [Description("Sample strategy demonstrating a use case involving the OnOrderUpdate() method")]
                public class SampleOnOrderUpdate_Limit : Strategy
                {
                #region Variables
                private IOrder entryOrder = null; // This variable holds an object representing our entry order
                private IOrder stopOrder = null; // This variable holds an object representing our stop loss order
                private IOrder targetOrder = null; // This variable holds an object representing our profit target order

                private int reverse = 0;
                #endregion

                /// <summary>
                /// This method is used to configure the strategy and is called once before any strategy method is called.
                /// </summary>
                protected override void Initialize()
                {
                CalculateOnBarClose = true;
                }

                /// <summary>
                /// Called on each bar update event (incoming tick)
                /// </summary>
                protected override void OnBarUpdate()
                {
                if (CurrentBar <= BarsRequired)
                return;
                if (Historical)
                return;

                // Submit an entry limit order if we currently don't have an entry order open
                if (entryOrder == null && stopOrder == null && Close[0] > Open[0])
                {
                Print("Long: Pos:" + ((High[0] + (10 * TickSize))).ToString());
                entryOrder = EnterLongLimit(0, true, 1, (High[0] + (10 * TickSize)), "MyEntry");
                }
                if (entryOrder == null & stopOrder == null && Close[0] <= Open[0])
                {
                Print("Short: Pos:" + ((Low[0] - (10 * TickSize))).ToString());
                entryOrder = EnterShortLimit(0, true, 1, (Low[0] - (10 * TickSize)), "MyEntry");
                }

                }

                /// <summary>
                /// Called on each incoming order event
                /// </summary>
                protected override void OnOrderUpdate(IOrder order)
                {
                // Handle entry orders here. The entryOrder object allows us to identify that the order that is calling the OnOrderUpdate() method is the entry order.
                if (entryOrder != null && entryOrder == order)
                {
                // Reset the entryOrder object to null if order was cancelled without any fill
                if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
                {
                Print("ENull OnOrderUpdate: " + order.OrderState.ToString());
                entryOrder = null;
                }
                }
                }

                /// <summary>
                /// Called on each incoming execution
                /// </summary>
                protected override void OnExecution(IExecution execution)
                {
                /* We advise monitoring OnExecution to trigger submission of stop/target orders instead of OnOrderUpdate() since OnExecution() is called after OnOrderUpdate()
                which ensures your strategy has received the execution which is used for internal signal tracking. */
                if (entryOrder != null && entryOrder == execution.Order)
                {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                {
                // Resets the entryOrder object to null after the order has been filled
                if (execution.Order.OrderState != OrderState.PartFilled)
                {
                // Removed
                //entryOrder = null;
                Print("ENull OnExecution: " + execution.Order.OrderState.ToString());
                }
                }
                }
                // Reset our stop order and target orders' IOrder objects after our position is closed.
                if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
                {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
                {
                stopOrder = null;
                targetOrder = null;
                // Added
                entryOrder = null;
                Print("ENull OnExecution: Stop & Target" + execution.Order.OrderState.ToString());
                }
                }
                }

                /// <summary>
                /// Called on each incoming position event
                /// </summary>
                protected override void OnPositionUpdate(IPosition position)
                {
                // Print our current position to the lower right hand corner of the chart
                DrawTextFixed("MyTag", position.ToString(), TextPosition.BottomRight);
                }

                #region Properties
                #endregion
                }

                Best Regards
                David

                Comment


                  #9
                  Hello David,

                  The sample you just sent me did not encounter any rules violations, however, it also did not place trades. During my backtesting I had encountered order handling rules violations with some of the earlier samples I received, but it is possible that I did not copy the code correctly. In the future, would it be possible for you to attach copies of your c# code as files? You can do so using the following procedure :

                  • Click reply, as usual
                  • If the option appears to "go advanced", please choose it
                  • In the toolbar on the top of the message window, there is a paperclip icon which will allow you to attach files.

                  Otherwise, if you surround code you paste in with [ code ] and [ /code ], it will preserve indentation and make it easier to copy and use.

                  I am attaching the code I tested with, along with a picture of the settings I used to test with. To bring up the Strategy Analyzer, you can visit File -> New -> Strategy Analyzer.

                  Your code did not place any trades for ES 09-16 or ES 06-16 data on any date between January of this year and today's date. If you would like us to test code for you, please submit a code sample which places trades in the strategy analyzer using these instruments and dates. Failing to place trades in the strategy analyzer should be treated the same way as a syntax or other compile time condition preventing your code from compiling.

                  I as well as any of my coworkers are capable of testing your code using several methods known to us, and if you can provide instructions should you test your code in other ways, we can follow those instructions as well. What we must do is set clear expectations as far as the services we will provide. We can answer any questions about how Ninja is designed to operate, provide code samples from the help guide or others designed for educational purposes, and test the NinjaTrader platform itself for bugs. In depth debugging of your code and new indicator or strategy development is outside the scope of the services we provide.

                  Once I can reproduce a limit order entering at an unexpected price the way yours are reliably on my end, I will be better equipped to answer questions as to why this is occurring in your code. If you can send me a copy of your code which places trades, I will be better able to reproduce what you were seeing on my end. Thank you for helping me provide the best assistance I can.
                  Attached Files
                  Jessica P.NinjaTrader Customer Service

                  Comment


                    #10
                    Hello Jessica P,

                    Thanks, the code did not place any trades because you can find in the code:

                    Code:
                    if (Historical)
                       return;
                    Please
                    1) Open a new chart no matter wich do you select.
                    2) Open the out put window console
                    3) On the strategy tab, run the strategy selecting the same chart of before

                    You can see only one trade on real time. Only one trade EnterLimit at 10 tick, but automatically it's close and enter at market.

                    1) EnterShortLimit at 10 tick from price Enter/ Low it's ok
                    http://screencast.com/t/GoHeDLdYDxU
                    2) Finally the order close and new order enter near from Price, no at the real EnterShortLimit Price
                    http://screencast.com/t/E1Jik7sJXZ7
                    It's look like that it's enter at market price

                    I attached again the same code

                    Best Regards
                    David
                    Attached Files

                    Comment


                      #11
                      Hi Jessica P,

                      I have fixed the code. I have changed:

                      Code:
                       entryOrder = EnterLongLimit(0, true, 1, (High[0] + (10 * TickSize)), "MyEntry");
                      for
                      Code:
                       entryOrder = EnterLongStop(0, true, 1, (High[0] + (10 * TickSize)), "MyEntry");
                      And the same change in the short entry

                      Thank you for helping me provide

                      Best Regards
                      David

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by forrestang, Today, 07:46 AM
                      0 responses
                      3 views
                      0 likes
                      Last Post forrestang  
                      Started by rainbow47, Today, 06:10 AM
                      1 response
                      10 views
                      0 likes
                      Last Post NinjaTrader_ChristopherD  
                      Started by oscsoft, Yesterday, 07:07 PM
                      1 response
                      14 views
                      0 likes
                      Last Post NinjaTrader_Jesse  
                      Started by pjsmith, Today, 03:28 AM
                      1 response
                      9 views
                      0 likes
                      Last Post NinjaTrader_Jesse  
                      Started by Leeroy_Jenkins, Today, 06:54 AM
                      0 responses
                      4 views
                      0 likes
                      Last Post Leeroy_Jenkins  
                      Working...
                      X