Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Position handling issue

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

    Position handling issue

    Hi All,
    I opened a similar discussion a few weeks ago, I thought I had solved my issue, but apparently it's still there.

    Below is the strategy I am running, and attached the trade log that shows the issue

    In summary I want the strategy to enter via limit order when a cross over occurs and exit at market when the cross over occurs in the opposite direction. The limit order is valid only for 2 bars after the cross over occurs. The code apparently works fine, BUT I noticed it duplicates my position when exit and new entry occur on the same bar session. I think this might be due to the fact that when the limit order is entered the market position is NOT flat, hence Ninjatrader enters the limit order equal to 2x default quantity in order to bring my position from long to short, ignoring the fact that i have a market order that would flat my position.

    if this is the case, is there anything I can do in the managed approach with CalculateOnBarClose = true; to avoid this strategy to double up my position?

    #region Variables
    private IOrder entryOrder = null;
    private int barNumberOfOrder = 0;
    #endregion

    protected override void Initialize()
    {
    EntryHandling = EntryHandling.UniqueEntries;
    CalculateOnBarClose = true;
    ExitOnClose = false;
    TraceOrders = true;
    }

    protected override void OnBarUpdate()
    {
    //Enter long
    if (entryOrder == null && CrossAbove(...))
    {
    entryOrder = EnterLongLimit(0, true, DefaultQuantity, Close[0] - 0.2 * (High[0] - Low[0]), "Long");
    barNumberOfOrder = CurrentBar;
    }

    //Enter short
    if (entryOrder == null && CrossBelow(...))
    {
    entryOrder = EnterShortLimit(0, true, DefaultQuantity, Close[0] + 0.2 * (High[0] - Low[0]),"Short");
    barNumberOfOrder = CurrentBar;
    }

    //Cancel limit order if not done within lookback period
    if(CurrentBar > barNumberOfOrder +1 && entryOrder != null)
    {
    CancelOrder(entryOrder);
    }

    //Exit long
    if (Position.MarketPosition == MarketPosition.Long && CrossBelow(...))
    {
    ExitLong(0,DefaultQuantity, "Exit Long On Cross", "Long");
    }

    //Exit short
    if (Position.MarketPosition == MarketPosition.Short && CrossAbove(...))
    {
    ExitShort(0,DefaultQuantity, "Exit Short On Cross", "Short");
    }
    }

    protected override void OnOrderUpdate(IOrder order)
    {
    if (entryOrder != null && entryOrder == order)
    {
    if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
    {
    entryOrder = null;
    }
    }
    }

    protected override void OnExecution(IExecution execution)
    {
    if (entryOrder != null && entryOrder == execution.Order)
    {
    if (execution.Order.OrderState != OrderState.PartFilled)
    {
    entryOrder = null;
    }
    }
    }
    Attached Files
    Last edited by sburtt; 05-14-2013, 01:46 PM.

    #2
    Hello sburtt,

    Thank you for your post.

    You should be able to add a MarketPosition.Flat check to the entry conditions to ensure you are flat before entering a new position.
    Code:
    if(Position.MarketPosition == MarketPosition.Flat)
    {
    if (entryOrder == null && CrossAbove(...))
    {
    entryOrder = EnterLongLimit(0, true, DefaultQuantity, Close[0] - 0.2 * (High[0] - Low[0]), "Long");
    barNumberOfOrder = CurrentBar;
    }
    
    //Enter short
    if (entryOrder == null && CrossBelow(...))
    {
    entryOrder = EnterShortLimit(0, true, DefaultQuantity, Close[0] + 0.2 * (High[0] - Low[0]),"Short");
    barNumberOfOrder = CurrentBar;
    }
    }
    For information on MarketPosition please visit the following link: http://www.ninjatrader.com/support/h...etposition.htm

    Please let me know if I may be of further assistance.

    Comment


      #3
      Originally posted by NinjaTrader_PatrickH View Post
      Hello sburtt,

      Thank you for your post.

      You should be able to add a MarketPosition.Flat check to the entry conditions to ensure you are flat before entering a new position.
      Code:
      if(Position.MarketPosition == MarketPosition.Flat)
      {
      if (entryOrder == null && CrossAbove(...))
      {
      entryOrder = EnterLongLimit(0, true, DefaultQuantity, Close[0] - 0.2 * (High[0] - Low[0]), "Long");
      barNumberOfOrder = CurrentBar;
      }
      
      //Enter short
      if (entryOrder == null && CrossBelow(...))
      {
      entryOrder = EnterShortLimit(0, true, DefaultQuantity, Close[0] + 0.2 * (High[0] - Low[0]),"Short");
      barNumberOfOrder = CurrentBar;
      }
      }
      For information on MarketPosition please visit the following link: http://www.ninjatrader.com/support/h...etposition.htm

      Please let me know if I may be of further assistance.
      Patrick,
      I want to have the flexibility to exit a postion and enter a new position via limit order in the same bar session. I am trading on 60 min bars, correctly if I am wrong, but I think the code you suggest wouldn't allow me to so.

      Just for example lets say it's 12:00 a CrossAbove occurs and I am running a short position. The market order will bring my position from short to flat at 12:00, but at the same time I want a long limit order to be activated immediately. The problem with my current code is that the long limit order for the first hour would be 2x default quantity.

      Comment


        #4
        Hello sburtt,

        Thank you for your response.

        In that case you could set your entries per direction to 1:
        Code:
            EntriesPerDirection = 1; 
            EntryHandling = EntryHandling.AllEntries;
        For information on EntryHandling please visit the following link: http://www.ninjatrader.com/support/h...ryhandling.htm

        Please let me know if you have any questions.

        Comment


          #5
          Originally posted by NinjaTrader_PatrickH View Post
          Hello sburtt,

          Thank you for your response.

          In that case you could set your entries per direction to 1:
          Code:
              EntriesPerDirection = 1; 
              EntryHandling = EntryHandling.AllEntries;
          For information on EntryHandling please visit the following link: http://www.ninjatrader.com/support/h...ryhandling.htm

          Please let me know if you have any questions.
          you mean by adding this code in the Initialize() section you think this will solve my problem?

          Please note that currently in the Initialize() section I have:
          EntryHandling = EntryHandling.UniqueEntries;
          isn't this the same thing?

          Comment


            #6
            Patrick, I would appreciate if you could answer to my last query.

            Furthermore, do you think I could reduce the degree of error by adding a shorter time frame, for example 1 minute, and executing the limit order on this? At the moment the limit order is sent to the primary bar session (60min) and for the first bar i risk duplicating my position. if the limit order is sent to the secondary bar session (1min) would this update the limit order every minute until the limit order is cancelled? If yes, i assume that i risk duplicating my position only for the 1st minute rather than 60min, if this is correct, this could sensibly diminish my degree of error.I am not 100% sure I fully understood how the processing occurs in MTF, but could this be the way to go in order to avoid the issue?
            Last edited by sburtt; 05-14-2013, 04:44 PM.

            Comment


              #7
              Hello sburtt,

              Thank you for your response.

              You have set EntryHandling but have you set EntriesPerDirection to 1?

              So if I fully understand this item, the CrossAbove or Below condition is true and what you are seeing is the position entered and exited on the same bar the condition was true on?

              Comment


                #8
                Originally posted by NinjaTrader_PatrickH View Post
                Hello sburtt,

                Thank you for your response.

                You have set EntryHandling but have you set EntriesPerDirection to 1?

                So if I fully understand this item, the CrossAbove or Below condition is true and what you are seeing is the position entered and exited on the same bar the condition was true on?
                NOT EXACTLY.

                Please review the code above, when the CrossBelow condition occurs I have both a ExitLong() and EnterShortLimit() order that are triggered in the same moment. The ExitLong() will flat my position, however the EnterShortLimit() currelty places 2 separate orders to Sell Default Quantity. One of this is to enter a short position, one is to flat my position. What I think happens is that because I am in a managed approach the EnterShortLimit() doesn't recognize the indipendent ExitLong() order and therefore first wants to flat my position. Do you understand, is my explanation clear?

                Comment


                  #9
                  Hello sburtt,

                  Thank you for your response.

                  This is happening for the exact reason you believe it is. The entry for the opposite direction tries to close the position before entering and yet an exit order is also sent.

                  If you wish to enter and exit on the same signal (enter long and exit short on CrossBelow() for example) then you do not need the use of the ExitLong or ExitShort, the entry for the opposite direction will close the position.

                  You could still use ExitLong and ExitShort but you will need to wait until they are filled before submitting a new entry order.

                  Please let me know if I may be of further assistance.

                  Comment


                    #10
                    Originally posted by NinjaTrader_PatrickH View Post
                    Hello sburtt,

                    Thank you for your response.

                    This is happening for the exact reason you believe it is. The entry for the opposite direction tries to close the position before entering and yet an exit order is also sent.

                    If you wish to enter and exit on the same signal (enter long and exit short on CrossBelow() for example) then you do not need the use of the ExitLong or ExitShort, the entry for the opposite direction will close the position.

                    You could still use ExitLong and ExitShort but you will need to wait until they are filled before submitting a new entry order.

                    Please let me know if I may be of further assistance.
                    That was my fear. So basically in the current environment I would be unable to exit a position at market and enter a limit position on the same bar session. Please confirm if this is right.

                    Furthermore, how could I find a way around this limitation? Do you think using MultiTimeFrame could help me overcome this issue?

                    I currently trade 60min bar sessions. I was thinking of using indications from 60min bar session as BarsArray[1] but effectively executing on 1min bar session and then using a Postion.MarketPosition == MarketPosition.Flat to check the status prior entering a new LimitOrder. Following my calculations, this should help me have a limit order for 59 min rather than 60min. Is this correct?

                    Comment


                      #11
                      Hello sburtt,

                      Thank you for your response.

                      You can use simply the entry order to close the position and enter in the new position.

                      For example, you are long the CrossBelow() condition returns true > the EnterShortLimit() is submitted > it will close your long position and then set the Short Limit order.

                      There would be no need to use a smaller time frame.

                      Comment


                        #12
                        Patrick, are you sure about this quote:
                        For example, you are long the CrossBelow() condition returns true > the EnterShortLimit() is submitted > it will close your long position and then set the Short Limit order.
                        Because according to me this doesn't happen. the EnterShortLimit() will enter 2 limit orders, the first to close my long position, the second to enter a short position, but both orders are entered as limit orders, whilst I want to exit with a market order, as I have no guarantee the limit will be reached.

                        Comment


                          #13
                          Hello sburtt,

                          Thank you for your response.

                          You are correct, it will use a limit order to exit the position.

                          So you will need to check that the exit order was filled and you are flat. With CalculateOnBarClose = True and the conditions to check for the entries in OnBarUpdate() we would not see the entry after the close until the next bar (which as you detailed is not what you want).

                          In this case there is a need to not only check that the exit order went through but also be able to then enter a new order on the same bar that recieved the condition to exit.

                          You could incorporate FirstTickOfBar and CalculateOnBarClose = false to achieve this to calculate the conditions to enter on bar close but be able to change positions (exit and enter) on the same bar. For a reference sample detailing this concept please visit the following link: http://www.ninjatrader.com/support/f...ad.php?t=19387

                          Please let me know if you have any questions.

                          Comment


                            #14
                            Originally posted by NinjaTrader_PatrickH View Post
                            Hello sburtt,

                            Thank you for your response.

                            You are correct, it will use a limit order to exit the position.

                            So you will need to check that the exit order was filled and you are flat. With CalculateOnBarClose = True and the conditions to check for the entries in OnBarUpdate() we would not see the entry after the close until the next bar (which as you detailed is not what you want).

                            In this case there is a need to not only check that the exit order went through but also be able to then enter a new order on the same bar that recieved the condition to exit.

                            You could incorporate FirstTickOfBar and CalculateOnBarClose = false to achieve this to calculate the conditions to enter on bar close but be able to change positions (exit and enter) on the same bar. For a reference sample detailing this concept please visit the following link: http://www.ninjatrader.com/support/f...ad.php?t=19387

                            Please let me know if you have any questions.
                            Thanks Patrick, I will have a look, I was not aware of this feature. Just out of curiosity, wouldn't I be able to achieve very similar results running a multi time frame strategy?
                            Basically looking for signals from the 60 min chart and executing orders on the 1 min chart? I tried programming this, where basically on the first minute of trading when a cross over occurs I exit at market via ExitLong and from the second minute of trading I would have a EnterLimitShort order, results are very similar, @but not the same@.

                            Comment


                              #15
                              Hello sburtt,

                              Thank you for your response.

                              That would be a possible route, using a smaller time frame or interval would give you an intra-bar granularity much like the backtesting sample for the same concept (link below).

                              Link to using intra-bar granularity in backtesting reference sample: http://www.ninjatrader.com/support/f...ead.php?t=6652
                              Last edited by NinjaTrader_PatrickH; 05-16-2013, 01:26 PM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              673 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              379 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              111 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              577 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              582 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X