Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Problem with CancelOrder

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

    Problem with CancelOrder

    HI all!

    I have a problem trying to cancel orders submitted, but not filled in a Strategy designed for backtesting. I will explain the code I've pasted below:

    1.I add 1min bars to gain "granularity" to send the orders and try to approach the market more realistic because I use triggers in the 30min chart.
    2.In the primary bars (30min), if MarketPosition is flat and we are in the correct time (between hInicio and hFin), the strategy evaluates the triggers for long and short positions. If they are true, it puts an Stop Order entry and calculates targets and stops.
    3.In the secondary bars, the strategy manages orders. If the entry orders is filled, it puts the target and stop orders and if the time is past the hCierre hour, it closes positions.
    4. The problem comes in the last part of the code that is "commented" with //. If I leave it commented (without use) the strategy works fine with only one problem: It opens positions past hCierre and cancel them immediately. So I need to cancel the orders submitted but not filled. I tried the code commented, but the strategy doesn't work, it mades 0 trades.

    How can I cancel those orders? Is a better way to do that?

    Thanks in advance,

    This is the code
    Code:
    	protected override void Initialize()
            {
    			Add(PeriodType.Minute, 1);
                		CalculateOnBarClose = true;
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
    			
                if (BarsInProgress == 0)
    			{
    				if(Position.MarketPosition == MarketPosition.Flat)				
    				
    				{
    					if (ToTime(Time[0]) > ToTime(hInicio, 0, 0) && ToTime(Time[0]) < ToTime(hFin, 0, 0))	
    					{
    						// Condiciones para posible apertura de largos
    						if (triggerLong)
    						{					
    							PIVOTEL = High[0] + filtro * 10 * TickSize;									
    							OBJETIVOL = Instrument.MasterInstrument.Round2TickSize(PIVOTEL + TARGETL);
    							STOPL = Instrument.MasterInstrument.Round2TickSize(PIVOTEL - STOPL);
    							entryOrderLong=EnterLongStop(1,true,100000, PIVOTEL, "EntradaLargos");						
    						}
    						// Condiciones para la posibel apertura de cortos
    						if (triggerShort)
    						{
    							PIVOTEC = Low[0] - filtro * 10 * TickSize;									
    							OBJETIVOC = Instrument.MasterInstrument.Round2TickSize(PIVOTEC - TARGETS);
    							STOPC = Instrument.MasterInstrument.Round2TickSize(PIVOTEC + STOPS);	
    							entryOrderShort=EnterShortStop(1,true,100000, PIVOTEC, "EntradaCortos");						
    																
    						}
    					}
    				}
    			}
    			// When the OnBarUpdate() is called from the secondary bar series, manejamos STOPS y OBJETIVOS
    			else
    			{
    			// C.Manejando posiciones
    				if (Position.MarketPosition == MarketPosition.Long)		
    				{
    					if (ToTime(Time[0]) >= ToTime(hCierre, 0, 0))
    					{
    						ExitLong(0,100000,"CierreLargos","EntradaLargos");
    					}
    					else
    					{
    					ExitLongLimit(100000,OBJETIVOL, "ObjetivoLargos", "EntradaLargos");
    					ExitLongStop(100000,STOPL, "StopLargos", "EntradaLargos");
    					}
    					
    				}
    				else if	(Position.MarketPosition == MarketPosition.Short)		
    				{
    					if (ToTime(Time[0]) >= ToTime(hCierre, 0, 0))
    					{
    						ExitShort(0,100000,"CierreCortos","EntradaCortos");
    					}
    					else
    					{
    						ExitShortLimit(100000,OBJETIVOC, "ObjetivoCortos", "EntradaCortos");
    						ExitShortStop(100000,STOPC, "StopCortos", "EntradaCortos");
    					}
    					
    				}
    				else
    				{
    //				if (ToTime(Time[0]) >= ToTime(hCierre, 0, 0))
    //					{
    //						CancelOrder(entryOrderShort);
    //						CancelOrder(entryOrderLong);
    //						
    //					}
    					return;
    				}
    			}
    			
            }

    #2
    Hello sercava,

    Thank you for your post.

    You may want to add TraceOrders to your Initialize() section and bring up the Output Window to see what is occurring with the orders being submitted.

    TraceOrders = true;

    The OutputWindow can be found in Tools -> Output Window

    Try this with both commented and uncommented portion of the script.
    Cal H.NinjaTrader Customer Service

    Comment


      #3
      Did you declare the orders as an IOrder?
      Like: private IOrder entryOrderShort = null;
      Because I think thats needed for CancelOrder.

      Comment


        #4
        Originally posted by trail View Post
        Did you declare the orders as an IOrder?
        Like: private IOrder entryOrderShort = null;
        Because I think thats needed for CancelOrder.
        Thanks for helping, but yes, I've declared them:
        Code:
        private IOrder 	entryOrderLong 			= null;
        	private IOrder 	entryOrderShort			= null;
        Originally posted by NinjaTrader_Cal View Post

        You may want to add TraceOrders to your Initialize() section and bring up the Output Window to see what is occurring with the orders being submitted.(...)

        Try this with both commented and uncommented portion of the script.
        With the commented section (only an example) :
        Code:
        02/01/2014 19:30:00 Entered internal PlaceOrder() method at 02/01/2014 19:30:00: BarsInProgress=1 Action=Buy OrderType=Stop Quantity=0,1M LimitPrice=0 StopPrice=1,3675'8 SignalName='EntradaLargos' FromEntrySignal=''
        02/01/2014 23:00:00 Cancelled order due to end of session handling: BarsInProgress=1: Order='NT-00000/Backtest' Name='EntradaLargos' State=Working Instrument='$EURUSD' Action=Buy Limit price=0 Stop price=1,36758 Quantity=0,1M Strategy='DS' Type=Stop Tif=Gtc Oco='' Filled=0 Fill price=0 Token='4a80544a92a44c1fb88a98e4f1594642' Gtd='01/12/2099 0:00:00'
        06/01/2014 10:00:00 Entered internal PlaceOrder() method at 06/01/2014 10:00:00: BarsInProgress=1 Action=Buy OrderType=Stop Quantity=0,1M LimitPrice=0 StopPrice=1,3606'4 SignalName='EntradaLargos' FromEntrySignal=''
        06/01/2014 10:07:00 Entered internal PlaceOrder() method at 06/01/2014 10:07:00: BarsInProgress=1 Action=Sell OrderType=Limit Quantity=0,1M LimitPrice=1,3671'5 StopPrice=0 SignalName='ObjetivoLargos' FromEntrySignal='EntradaLargos'

        And now with the commented section available I get this error:

        Code:
        **NT** Error on calling 'OnBarUpdate' method for strategy 'DS/ade2841bb7e34b2490871742d54c565e': Referencia a objeto no establecida como instancia de un objeto.

        Comment


          #5
          Sercava,

          Try using a null check before submitting those cancel orders

          Code:
          if (ToTime(Time[0]) >= ToTime(hCierre, 0, 0))
          	{
                       if(entryOrderShort != null)
          		CancelOrder(entryOrderShort);
                       if(entryOrderLong != null)
          		CancelOrder(entryOrderLong);
          						
          	}
          This will ensure that the object exists for the IOrder before submitting the cancel order.
          Cal H.NinjaTrader Customer Service

          Comment


            #6
            Originally posted by NinjaTrader_Cal View Post
            Sercava,

            Try using a null check before submitting those cancel orders

            Code:
            if (ToTime(Time[0]) >= ToTime(hCierre, 0, 0))
            	{
                         if(entryOrderShort != null)
            		CancelOrder(entryOrderShort);
                         if(entryOrderLong != null)
            		CancelOrder(entryOrderLong);
            						
            	}
            This will ensure that the object exists for the IOrder before submitting the cancel order.
            That works!!! Thanks.

            Comment


              #7
              Keep in mind that cancelling or modifying orders sometimes can cost you money (fees), for example on the EUREX exchange.
              In my case: I traded the Eurostoxx50 futures (Estx50 or FESX) via IB with a strategy in Ninjatrader.
              Many orders are sent but also cancelled or modified with my strategy. I never knew this can give costs until I saw the fees later on a monthly overview :-(.
              So take care if your strategy cancels/modifies orders at the Eurex-exchange (and maybe there are more).
              See also:
              Leading online trading solutions for traders, investors and advisors, with direct global access to stocks, options, futures, currencies, bonds and funds. Transparent, low commissions and financing rates and support for best execution.

              Comment


                #8
                Great information and advise. Currently I have no fees charged when modifying or cancelling orders, but It's important to be aware of that when comparing brokers or backtesting strategies.

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                0 responses
                648 views
                0 likes
                Last Post Geovanny Suaza  
                Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                0 responses
                369 views
                1 like
                Last Post Geovanny Suaza  
                Started by Mindset, 02-09-2026, 11:44 AM
                0 responses
                108 views
                0 likes
                Last Post Mindset
                by Mindset
                 
                Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                0 responses
                572 views
                1 like
                Last Post Geovanny Suaza  
                Started by RFrosty, 01-28-2026, 06:49 PM
                0 responses
                574 views
                1 like
                Last Post RFrosty
                by RFrosty
                 
                Working...
                X