Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

IB and NT 7 - Strategy submitting multiple buy orders on accident?

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

    IB and NT 7 - Strategy submitting multiple buy orders on accident?

    Hi all,

    This might be one of this 'well, duh' questions, but I'll ask anyway.

    I tried out a new strategy yesterday with NT using IB as my broker. When running the strategy in Market Replay on a previously recorded day, the strategy executes and sends orders without a problem. However, when I try to use this same strategy with my IB paper account, it sends orders... lots of them, whenever a buy or sell short trigger is hit.

    In fact, it sends so many orders in a sort of weird, recursive loop that the exchange starts to cancel orders because it can't find enough securities (to short for instance). My strategy then disables shortly there after.

    Here's a printout of the log I'm looking at:

    --------------------------------------

    8/8/2012 8:52:04 AM Entered internal SubmitOrder() method at 8/8/2012 8:52:04 AM: Action=SellShort OrderType=Market Quantity=300 LimitPrice=0 StopPrice=0 OcoId='' Name='trendingShort'
    ----------------
    SHORT START: Flat Market Order
    ----------------
    stopPrice begins at (53.82)
    stopPriceBar (diamond) was placed on bar #1.
    ----------------
    8/8/2012 8:52:05 AM Entered internal SubmitOrder() method at 8/8/2012 8:52:05 AM: Action=SellShort OrderType=Market Quantity=300 LimitPrice=0 StopPrice=0 OcoId='' Name='trendingShort'
    ----------------
    SHORT START: Flat Market Order
    ----------------
    stopPrice begins at (53.82)
    stopPriceBar (diamond) was placed on bar #1.
    ----------------
    8/8/2012 8:52:05 AM Entered internal SubmitOrder() method at 8/8/2012 8:52:05 AM: Action=SellShort OrderType=Market Quantity=300 LimitPrice=0 StopPrice=0 OcoId='' Name='trendingShort'
    ----------------
    SHORT START: Flat Market Order
    ----------------
    stopPrice begins at (53.82)
    stopPriceBar (diamond) was placed on bar #1.
    ----------------
    8/8/2012 8:52:05 AM Entered internal SubmitOrder() method at 8/8/2012 8:52:05 AM: Action=SellShort OrderType=Market Quantity=300 LimitPrice=0 StopPrice=0 OcoId='' Name='trendingShort'
    ----------------

    and it just keeps going like this. It looks like it's sending an order on every tick.

    Here's the related code:
    Code:
    // Order relate code
    shortOrder = SubmitOrder(0, OrderAction.SellShort, OrderType.Market, numberofShares, 0, 0, "", "trendingShort");
    							shortOrder_start = true;
    
    /* Short Orders */
    protected override void OnExecution(IExecution execution)
    		{
    			if (shortOrder == execution.Order
    				&& shortOrder.OrderState == OrderState.Filled)
    				
    			{
    				
    				// Starts
    				if (shortOrder_start == true)
    				{
    					Print("Part 1 Hit");
    					DrawHorizontalLine("shortOrder", false, shortOrder.AvgFillPrice, Color.OrangeRed, DashStyle.Solid, 2);
    					breakEvenPrice = shortOrder.AvgFillPrice - breakEvenAmount;
    					shortOrder_start = false;
    				}
    				
    				// Reversals
    				else if (shortOrder_reversal == true && breakEvenAchieved == true)
    				{
    					Print("Part 2 Hit");
    					longOrder = SubmitOrder(0, OrderAction.Buy, OrderType.Market, numberofShares, 0, 0, "", "trendingLong");
    				}
    				
    				else if (longOrder_reversal == true && breakEvenAchieved == false)
    				{
    					Print("Part 3 Hit");
    					RemoveDrawObject("shortOrder");
    					shortOrder_reversal = false;
    					breakEvenAchieved = false;
    				}
    				
    				else if (longOrder_reversal == true)
    				{
    					Print("Part 4 Hit");
    					longOrder_reversal = false;
    					
    					breakEvenPrice = shortOrder.AvgFillPrice - breakEvenAmount;
    					breakEvenAchieved = false;
    					
    					DrawHorizontalLine("shortOrder", false, shortOrder.AvgFillPrice, Color.OrangeRed, DashStyle.Solid, 2);
    					RemoveDrawObject("longOrder");
    				}
    				
    				// Closing 
    				else if (shortOrder_close == true)
    				{
    					Print("Part 5 Hit");
    					shortOrder_close = false;
    					
    					// If a breakEven wasn't hit, install a 10 minute penalty.
    					if (breakEvenAchieved == false)
    					{	breakEven_penaltyTime = 10; }
    					
    					else 
    					{	breakEvenAchieved = false;  }
    					
    				}
    			}
    		}
    
    protected override void OnOrderUpdate(IOrder order)			
    		{
    			
    
    			// When we determine to stop our strategy all logic in the OnOrderUpdate() method will cease.
    			if (haltProcessing == true)
    				return;
    				
    			/* Handle our entry order here. If our entry order is cancelled or rejected we want to reset either longOrder or shortOrder
    			so we can enter the next time our entry signal appears. */
    			if (longOrder != null && longOrder == order)
    			{
    				if (longOrder.OrderState == OrderState.Cancelled
    					|| longOrder.OrderState == OrderState.Rejected)
    					
    				{	longOrder = null;  }
    				
    				//  For long orders trying to close.  Resubmit if cancelled or rejected.
    				else if (longOrder.OrderId == "closingLong" && longOrder.OrderState == OrderState.Cancelled
    					|| longOrder.OrderId == "closingLong" && longOrder.OrderState == OrderState.Rejected)
    					
    				{	
    					longOrder = SubmitOrder(0, OrderAction.Sell, OrderType.Market, numberofShares, 0, 0, "", "closingLong");
    				}
    			}
    			
    			else if (shortOrder != null && shortOrder == order)
    			{
    				if (shortOrder.OrderState == OrderState.Cancelled
    					|| shortOrder.OrderState == OrderState.Rejected)
    					
    				{	shortOrder = null;  }
    				
    				//  For short orders trying to close.  Resubmit if cancelled or rejected.
    				else if (shortOrder.OrderId == "closingShort" && shortOrder.OrderState == OrderState.Cancelled
    					|| shortOrder.OrderId == "closingShort" && shortOrder.OrderState == OrderState.Rejected)
    					
    				{	
    					shortOrder = SubmitOrder(0, OrderAction.BuyToCover, OrderType.Market, numberofShares, 0, 0, "", "closingShort");
    				}
    			}
    		}
    Might not be enough to go on, but any idea what might be happening with NT sending multiple orders, based on the above?

    Yours,
    Spider

    PS - Working in an unmanaged environment, with data feed confirmed to IB. Can manually close and open orders without any problems.

    #2
    Hi Spiderbird, so you execute to a IB Paper account or to the NT Sim101 with the live IB feed used? Do you run this on CalculateOnBarClose = false live, so with updates on each tick?

    If you don't limit the submission in the unmanaged mode it would just continue sending orders, but it looks like you've been attemptingt to do this via the shortOrder_start, right?
    BertrandNinjaTrader Customer Service

    Comment


      #3
      Following up!

      Hi Bertrand,

      Apologies for the late reply. I've been tooling with my strategy and wanted to experiment with a few solutions before re-submitting a response to your questions.

      *** Hi Spiderbird, so you execute to a IB Paper account or to the NT Sim101 with the live IB feed used?
      I execute to the IB paper account directly.

      *** Do you run this on CalculateOnBarClose = false live, so with updates on each tick?
      Correct. Which is what I think is the problem.

      *** If you don't limit the submission in the unmanaged mode it would just continue sending orders, but it looks like you've been attemptingt to do this via the shortOrder_start, right?

      The shortOrder_start section just outlines what's sent to IB (i.e. a short order), but your thought about the CalculateOnBarClose being false and sending orders with each tick update, is probably the root of the problem.

      I've been able to solve the problem I outlined, but it isn't elegant. It basically uses an int carrying a ToTime(Time[0] stamp, and a trade switch to turn on and off, depending on if the current time matches the timestamp. The whole mess looks like this.

      Code:
      if (order_Time != ToTime(Time[0]))   {	order_Check = true;  }
      				
      if (order_Check == true)
      	{  // submit order (long or short) }
      
      	// Modify loop variables to stop double counting
      	order_Check = false;
      	order_Time = ToTime(Time[0]);
      }
      -------------------------

      I originally tried to look for an order state with longOrder.OrderState and shortOrder.OrderState. I even outputted the OrderState for each to see what was going on (longOrder.OrderState.ToString()) .

      Unfortunately, every time I went to check on the OrderState, and the longOrder or shortOrder wasn't in play, it would throw back a 'variable not set to an instance of an object' error message. This happened when checking for longOrder != null && longOrder.OrderState == OrderState.Filled in the same if statement (since the latter didn't exist if the longOrder hadn't been executed).

      Is there a way to check for OrderState that won't throw up that instance error? If so, I can get rid of that other code that's more of a 'duct tape' solution (in that, I couldn't get out of a bad whipsaw for 60 seconds (if it occurred).

      Again, thanks in advance for any time you take to read and respond to this message!

      Yours,
      Spider

      Comment


        #4
        No worries Spider, glad to hear you could make progress via the code filter - for the order state - from which method were you printing it?
        BertrandNinjaTrader Customer Service

        Comment


          #5
          Hi Bertrand,

          I didn't include it in a method per se. I just had the code check to see if my position was flat, and print out the status as it unfolded. So the code looks like this:

          Code:
          if (Position.MarketPosition == MarketPosition.Flat
          	&& ToTime(Time[0]) >= 83500
          	&& tradeSwitch == true)
          {
          
          if (longOrder != null)
          	{Print("Long Order Status: " + longOrder.OrderState.ToString());}
          						
          if (shortOrder != null)
          	{Print("Short Order Status: " + shortOrder.OrderState.ToString());}
          
          // order code went here
          
          }
          ... from that, the output window would show:

          Long Order Status: submitted
          Long Order Status: filled
          Long Order Status: filled

          -----------------------

          But to re-ask the question I posed earlier:
          "Is there a way to check for OrderState that won't show a 'variable not set to an instance of an object' error?"

          I thought about going this route, but I'm thinking that if the code is running on every tick update, the longOrder check outlined here would still be true and submit another order anyway:

          Code:
          if (longOrder == null)
          {
          	if (longOrder.OrderState == null)
          	{
          		// Order code goes here
          	}
          }
          Would the above hypothetically work?
          Last edited by Spiderbird; 08-16-2012, 01:36 PM. Reason: Code in second part was done incorrectly...

          Comment


            #6
            Well, you have to work in some kind of method with the code, but from your script I take this was just the main OnBarUpdate()?

            The error message you got had let you know that you tried to access a property of an IOrder object while the object itself was null - http://www.ninjatrader.com/support/f...ead.php?t=4226

            Submitting the order only when the object is null is good practice and should do the trick for you. You would reset the object then to null and allow a new entry only if the previous order reached a terminal state.
            BertrandNinjaTrader Customer Service

            Comment


              #7
              Thanks! And to clarify...

              Hi Bertrand,

              You are correct. It was taken from OnBarUpdate().

              The code I implemented is below for reference. Checking to see if the LongOrder is null does the trick! But to clarify, when you typed "You would reset the object then to null and allow a new entry only if the previous order reached a terminal state", did you mean checking the Orderstate of longOrder (in this example) to see if it's OrderState.Cancelled, OrderState.Rejected, or OrderState.Filled?

              And then, setting LongOrder = null once that 'terminal' state was reported?

              Please let me know if that's correct.

              Code:
              private void StartLong()
              	{
              		if (longOrder == null)
              		{
              			//  Submit a long order to the market
              			longOrder = SubmitOrder(0, OrderAction.Buy, OrderType.Market, numberofShares, 0, 0, "", "trendingLong");
              			longOrder_start = true;
              			start_Long = false;
              							
              			StartLong_stopAmount();
              			Draw_stopPrice_stopPriceBar();
              				
              			StartLong_Order_Print();
              			Report_stopAmount_Print();
              				
              			ResetAllVariables();
              		}
              	}

              Comment


                #8
                Correct, those would be the terminal order states you can encounter.
                BertrandNinjaTrader Customer Service

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by proptrade13, Today, 11:06 AM
                1 response
                5 views
                0 likes
                Last Post NinjaTrader_Clayton  
                Started by quantismo, 04-17-2024, 05:13 PM
                4 responses
                32 views
                0 likes
                Last Post quantismo  
                Started by love2code2trade, 04-17-2024, 01:45 PM
                4 responses
                32 views
                0 likes
                Last Post love2code2trade  
                Started by cls71, Today, 04:45 AM
                2 responses
                10 views
                0 likes
                Last Post eDanny
                by eDanny
                 
                Started by kulwinder73, Today, 10:31 AM
                1 response
                10 views
                0 likes
                Last Post NinjaTrader_Erick  
                Working...
                X