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

target order doesnt execute with full Qty

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

    target order doesnt execute with full Qty

    my problem:
    the exit at target doesnt work. it exits with only the qty of the last entry.

    I have multiple ENTRY points in the strategy. ( entry1Order , entry2Order)
    and one target exit level .
    I have an option to use one stop level or to exit 2/3 of a position at target and later to use trailing mechanism I have created.. at this stage I dont use the trailing !!!

    looks like the order for target REPLACEs the previous order and not adding a new one with new qty.

    what am I doing wrong pls?

    (by the way, tried with canceling the order before creating a new on with a position.quantity , but sometimes it just cancels the target order entirely and I have no fill at target.)




    Code:
    	protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice, 
    			int quantity, int filled, double averageFillPrice, 
    			Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
    		{
    			
    			
    					
    			if (order.Name == "Long-0" || order.Name == "Short-0" )
        		{	
            		entry0Order = order;
    
                    // Reset the entryOrder object to null if order was cancelled without any fill
                    if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
    					entry0Order = null;
    			}
    			
    			if (order.Name == "Long-A" || order.Name == "Short-A" )
        		{	
            		entry1Order = order;
    
                    // Reset the entryOrder object to null if order was cancelled without any fill
                    if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
    					entry1Order = null;
    			}
    			
    			if (order.Name == "Long-B" || order.Name == "Short-B" )
        		{	
            		entry2Order = order;
    
                    // Reset the entryOrder object to null if order was cancelled without any fill
                    if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
    					entry2Order = null;
    			}
    				
    			
    		} //END of OnOrderUpdate()
    		
    //***********************************************************************************************************
    	
    		protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
    		{
    			
    		
    			if (entry0Order != null && entry0Order == execution.Order)
    			{			
    				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
    				{
    					//STOP LOSS
    //					stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 4 * TickSize, "MyStop", "MyEntry");
    					if (Position.MarketPosition == MarketPosition.Long )  
    						stopOrder = ExitLongStopMarket(1, true, Position.Quantity, HighOfRange - StopLossAmount, "MyStop", null);
    						
    					if (Position.MarketPosition == MarketPosition.Short ) 
    						stopOrder = ExitShortStopMarket(1, true, Position.Quantity, LowOfRange + StopLossAmount, "MyStop", null);	
    				}
    			}
    			
    			if (entry1Order != null && entry1Order == execution.Order)
    			{			
    				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
    				{
    					//STOP LOSS
    //					stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 4 * TickSize, "MyStop", "MyEntry");
    					if (Position.MarketPosition == MarketPosition.Long )  
    						stopOrder = ExitLongStopMarket(1, true, Position.Quantity, HighOfRange - StopLossAmount, "MyStop", null);
    						
    					if (Position.MarketPosition == MarketPosition.Short ) 
    						stopOrder = ExitShortStopMarket(1, true,  Position.Quantity, LowOfRange + StopLossAmount, "MyStop", null);		
    				}
    			}
    			
    			if (entry2Order != null && entry2Order == execution.Order)
    			{			
    				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
    				{
    					//STOP LOSS
    //					stopOrder = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - 4 * TickSize, "MyStop", "MyEntry");
    					if (Position.MarketPosition == MarketPosition.Long )  
    						stopOrder = ExitLongStopMarket(1, true, Position.Quantity, HighOfRange - StopLossAmount, "MyStop", null);
    						
    					if (Position.MarketPosition == MarketPosition.Short ) 
    						stopOrder = ExitShortStopMarket(1, true,  Position.Quantity, LowOfRange + StopLossAmount, "MyStop", null);			
    				}
    			}
    			
    			
    			//Target
    			//=============
    			if ((entry0Order != null && entry0Order == execution.Order) 
    				|| (entry1Order != null && entry1Order == execution.Order) 
    				|| (entry2Order != null && entry2Order == execution.Order))
    			{			
    				if (execution.Order.OrderState == OrderState.Filled  || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
    				{				
    					//if (targetOrder != null) CancelOrder(targetOrder);
    							
    					if (Position.MarketPosition == MarketPosition.Long)  
    					{
    						if (UseTrailingStop==false)
    							targetOrder = ExitLongMIT(1, true,  Convert.ToInt32(execution.Order.Filled), HighOfRange + InitialPartialTarget, "MyTarget", null);
    						else 
    						{
    							//if (targetOrder != null) CancelOrder(targetOrder);
    							targetOrder = ExitLongMIT(1, true,  Convert.ToInt32(Math.Floor(Convert.ToDouble(execution.Order.Filled)*2/3)) , HighOfRange + InitialPartialTarget, "MyTarget", null);
    						}
    					}
    					
    					if (Position.MarketPosition == MarketPosition.Short) 
    					{
    						if (UseTrailingStop==false)
    							targetOrder = ExitShortMIT(1, true, Convert.ToInt32(execution.Order.Filled), LowOfRange - InitialPartialTarget, "MyTarget", null);
    						else
    						{
    							//if (targetOrder != null) CancelOrder(targetOrder);
    							targetOrder = ExitShortMIT(1, true, Convert.ToInt32(Math.Floor(Convert.ToDouble(execution.Order.Filled) *2/3)), LowOfRange - InitialPartialTarget, "MyTarget", null);	
    						}
    					}
    				}
    			}
    			
    			
    			
    		
    			// Reset our orders' Order objects after our position is closed.
    			if ((stopOrder != null && stopOrder == execution.Order)
    				|| (targetOrder != null && targetOrder == execution.Order)
    				|| execution.Order.Name == "Sell" 
    				|| execution.Order.Name == "Buy to cover"
    				)
    			{
    				if (execution.Order.OrderState == OrderState.Filled ) // || execution.Order.OrderState == OrderState.PartFilled)
    				{
    					if (targetOrder != null && targetOrder == execution.Order) 	
    					{
    						todayTargetRangeReached = true;
    					}
    					
    					if (execution.Order.Name == "Sell" || execution.Order.Name == "Buy to cover") todayTargetRangeReached = false ;
    					
    					
    					CancelOrder(entry0Order);
    					CancelOrder(entry1Order);
    					CancelOrder(entry2Order);
    					CancelOrder(stopOrder);
    					CancelOrder(targetOrder);
    					stopOrder 	= null;
    					targetOrder = null;
    					entry0Order = null;
    					entry1Order = null;
    					entry2Order = null;
    					Order0ARMED = false;
    					Order1ARMED = false;
    					Order2ARMED = false;
    				}
    				
    			}
    			
    		} //End of OnExecutionUpdate()

    #2
    Hello dadarara,

    Thank you for the post.

    I see that you are currently using the Position quantity and the Executions quantity in your orders:

    Code:
    Convert.ToInt32(execution.Order.Filled)
    Position.Quantity
    I do not see that you are accounting for the first entries quantity in any way here. The Executions filled amount specifically will not include the first entry as you have two separate entries. You would need to account for the first filled quantity in some way if that should be amended to the overall quantity of the target.

    For the Position.Quantity, if this is also one of the affected targets you may try Printing the Position here to ensure the value is what you are expecting. If not, you may instead try using the execution filled quantities in addition to your first entry quantity.

    I Look forward to being of further assistance.
    JesseNinjaTrader Customer Service

    Comment


      #3
      Thanks for coming back

      I have several questions. and would like to ask what is the preferred way of doing it ALL ...
      I intentionally divided the question into 2 as I want to learn and understand.

      Part A:
      -----------
      lets for the sake of discussion simplify the original code and also not talk for a moment about the trailing order for the 1/3 of the position.(will get to it later)
      I have two options:
      1) issue new target order for each full or partial execution of any of the entry orders . In which case I expect a new target order for any of the FILLED qty. or unless I am mistaken and the NINJA will update/replace the original order with a new one, with an updated qty of shares.(which is it??)
      \
      //Target
      //=============
      if (( entry0Order != null && entry0Order == execution.Order)
      || (entry1Order != null && entry1Order == execution.Order)
      || (entry2Order != null && entry2Order == 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)
      {
      targetOrder = ExitLongMIT(1, true,Convert.ToInt32(execution.Order.Filled) , HighOfRange + InitialPartialTarget, "MyTarget", null);
      }

      .... same for the SHORT case...
      }
      2) cancel any open target order and issue a new order for the new full account position.
      in this case I force the cancellation of the previous open order and an issuance of a new updated order. I think my code bellow is not good. I get sometimes a cancellation of the TARGET order all together and the position stays ON.
      \
      //Target
      //=============
      if (( entry0Order != null && entry0Order == execution.Order)
      || (entry1Order != null && entry1Order == execution.Order)
      || (entry2Order != null && entry2Order == execution.Order))
      {
      if (execution.Order.OrderState == OrderState.Filled
      || execution.Order.OrderState == OrderState.PartFilled
      || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
      {
      if (targetOrder != null) CancelOrder(targetOrder);
      if (Position.MarketPosition == MarketPosition.Long)
      {
      targetOrder = ExitLongMIT(1, true,Convert.ToInt32(Position.Quantity) , HighOfRange + InitialPartialTarget, "MyTarget", null);
      }
      }
      Please review the above and advise what is the best way.


      Part B:
      ---------

      Now lets introduce the partial exit and trailing of the 1/3.
      I also have two options.
      Option1: to deal with each entry/partial execution of one individually by issue of a new target order


      if (( entry0Order != null && entry0Order == execution.Order)
      || (entry1Order != null && entry1Order == execution.Order)
      || (entry2Order != null && entry2Order == 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)
      {
      if (UseTrailingStop==false)
      targetOrder = ExitLongMIT(1, true, Convert.ToInt32(execution.Order.Filled), HighOfRange + InitialPartialTarget, "MyTarget", null);

      else
      {
      targetOrder = ExitLongMIT(1, true, Convert.ToInt32(Math.Floor(Convert.ToDouble(execut ion.Order.Filled)*2/3)) , HighOfRange + InitialPartialTarget, "MyTarget", null);
      }
      }
      Option2: to cancel any previous target order and issue a new one for the full QTY.

      if (( entry0Order != null && entry0Order == execution.Order)
      || (entry1Order != null && entry1Order == execution.Order)
      || (entry2Order != null && entry2Order == execution.Order))
      {
      if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
      {
      if (targetOrder != null) CancelOrder(targetOrder);
      if (Position.MarketPosition == MarketPosition.Long)
      {
      if (UseTrailingStop==false)
      targetOrder = ExitLongMIT(1, true, Convert.ToInt32(Position.Quantity), HighOfRange + InitialPartialTarget, "MyTarget", null);
      else
      {
      targetOrder = ExitLongMIT(1, true, Convert.ToInt32(Math.Floor(Convert.ToDouble(Positi on,Quantity)*2/3)) , HighOfRange + InitialPartialTarget, "MyTarget", null);
      }
      }


      what are your suggestions how people do the above ?

      Comment


        #4
        Hello dadarara,

        1). I would likely suggest using ChangeOrder here as you are using Order objects. This would allow you to update the existing order as you are using LiveUntilCancelled = true.


        2). If you feel the code is not good, you could revisit this and debug it further to your liking. I really couldn't comment on why this would not be good or more/less valid than your other attempt. The only item I can comment on here is that you are canceling an order but not waiting for a response. The logic should likely return once the order is canceled, and you could observe for the cancellation to be successful and then proceed to do the other actions. This would likely be a situation you could use prints and testing to see which approach works best for your goals.

        The second set of samples falls into the same category, I only see that you are adding the CancelOrder and not waiting on its response. For both sets of items you are asking about, these would be items you could test using ChangeOrder with and compare results.



        I look forward to being of further assistance.
        JesseNinjaTrader Customer Service

        Comment


          #5
          Jesse
          thanks for the advice.
          though its still not clear.
          if I use the following command with the "execution.Order.Filled" for every entry , does it mean that it updates the existing order ? is it like Change Order?
          OR it adds additional target command for the new Qty ?
          Its a managed approach so I thought the program will decide for me if it needs to change an existing order or create a new one...

          targetOrder = ExitLongMIT(1, true,Convert.ToInt32(execution.Order.Filled) , HighOfRange + InitialPartialTarget, "MyTarget", null);


          Aslo, for checking the actual CANCEL is done, am I right to do it in the OnOrderUpdate and NOT in OnExecutionUpdate?
          Last edited by dadarara; 08-24-2018, 03:16 AM.

          Comment


            #6
            Hello dadarara,

            These are good questions but would be best answered by testing this logic from either your script or a more simple test script.

            In this case, because you are only using a signal name and only using the execution quantity it would update an existing order to that specifically. This is not going to update the quantity in addition to what is already there, it will update to exactly what you supply to the order. For example, if the total quantity should be 2, but the execution quantity was 1 and you supplied 1 to the order method, it would update to 1 not 2. You would need to be specific on the quantities you supply to the order methods if you are going to have it update the quantity and not just submit an order.

            Regarding the cancel, you are correct to use OnOrderUpdate as that would not be considered an execution.


            I look forward to being of further assistance.
            JesseNinjaTrader Customer Service

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by lorem, Today, 09:18 AM
            1 response
            3 views
            0 likes
            Last Post lorem
            by lorem
             
            Started by bmartz, Today, 09:30 AM
            0 responses
            1 view
            0 likes
            Last Post bmartz
            by bmartz
             
            Started by GussJ, 03-04-2020, 03:11 PM
            14 responses
            3,244 views
            0 likes
            Last Post GussJ
            by GussJ
             
            Started by ArkansasClint, Today, 09:28 AM
            0 responses
            0 views
            0 likes
            Last Post ArkansasClint  
            Started by hazylizard, Today, 08:38 AM
            4 responses
            12 views
            0 likes
            Last Post hazylizard  
            Working...
            X