Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Canceling a limit order after 2 bars - Code help, please

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

    Canceling a limit order after 2 bars - Code help, please

    I have the following:

    private int barNumberOfOrder=0;
    private double limitpricelong=0; // calculated later--working


    if ( <<conditions -- this code is working>>)
    {
    AtmStrategyCreate(OrderAction.Buy, OrderType.Limit, limitpricelong, 0,
    TimeInForce.Day, GetAtmStrategyUniqueId(), "ATM1",
    GetAtmStrategyUniqueId());
    barNumberOfOrder = CurrentBar;
    }

    and

    if (CurrentBar > barNumberOfOrder + 2)
    {AtmStrategyCancelEntryOrder("orderIdValue");}

    The problem is: orderIdValue --

    I thought this was what matched up to GetAtmStrategyUniqueId());

    But that is not the case... the order fires but the order does not cancel because "orderIdValue" does not exist.

    How do I cancel this order if it does not fill after 2 bars? I've researched the help topics and thought I had the right code...also not sure why the code GetAtmStrategyUniqueId()); is repeated, but that's how I saw it in the examples and the code works, expect for the cancel part.

    I am stuck. Thanks in advance.

    #2
    Where are you storing orderIdValue? What you've passed is just a sample string...

    The GetAtmStrategyUniqueID() will generate a unique number each time it's called.

    If you're calling GetAtmStrategyUniqueId() directly in your AtmStrategyCreate method, and then trying to reference it by calling GetAtmStrategyUniquieID() later, then passing it to your variable, the values will be different.

    Take a look at our SampleATMStrategy reference under Tools--> Edit NinjaScript--> Strategy

    You'll see that when the orderID and atmStrategyID are empty, we generate a new ID for each variable:

    Code:
    if (orderId.Length == 0 && atmStrategyId.Length == 0 && Close[0] > Open[0])
    			{
    				atmStrategyId = GetAtmStrategyUniqueId();
    				orderId = GetAtmStrategyUniqueId();
    Which is then passed to the ATMStrategyCreate()
    Code:
    AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "AtmStrategyTemplate", atmStrategyId);
    And can be reused later on if you wish to Cancel/Change, until the ATM has been reset.
    MatthewNinjaTrader Product Management

    Comment


      #3
      Missing order parameter

      Thanks... I have worked with the code and now my limit order will cancel...but after that cancel the strategy will not place any more orders. The error message is: Missing order parameter, which comes AFTER the cancel. So, it must be something with the reset. I copied the code exactly from the example, even though I don't follow some of it.

      I tried to add just this bit of code
      Code:
      // If the order state is terminal, reset the order id value
      if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
      {orderId = string.Empty;}
      but the word "status" was a problem... then I added it all...

      Code:
      if (orderId.Length > 0)
      {
      string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                      
      // If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
      if (status.GetLength(0) > 0)
      {
      // Print out some information about the order to the output window
      					Print("The entry order average fill price is: " + status[0]);
      					Print("The entry order filled amount is: " + status[1]);
      					Print("The entry order order state is: " + status[2]);
      
      // If the order state is terminal, reset the order id value
      if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
      orderId = string.Empty;
      }
      } // If the strategy has terminated reset the strategy id
      else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
      atmStrategyId = string.Empty;
      
      if (atmStrategyId.Length > 0)
      {
      // You can change the stop price
      if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
      AtmStrategyChangeStopTarget(0, Low[0] - 3 * TickSize, "STOP1", atmStrategyId);
      
      // Print some information about the strategy to the output window
      Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
      Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
      Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId));
      Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId));
      }
      No error messages when compiling, but why do I need all of this? And still I get the error message Missing order parameter after the pending order is cancelled.

      I think the minimum amount of code needed would be to reset the atmStrategyId and the orderId...when the atm is flat ...

      Could a varation of something like:
      Code:
      if (Cbi.MarketPosition.Flat)
      {orderId = string.Empty;
      atmStrategyId = string.Empty;}
      possible work??

      Thanks in advance (again)...

      Comment


        #4
        Hi,

        Nice work, glad to see you made some progress.

        Yes, something like that should work - here is what we do in our sample:

        Code:
        	else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
        atmStrategyId = string.Empty;
        MatthewNinjaTrader Product Management

        Comment


          #5
          I think I've taken a step backwards, with that last code modification the cancel order does not even work the first time...hmmm.

          So since I've taken a step back let's take another step back and look at this code:
          Code:
          atmStrategyId = GetAtmStrategyUniqueId();
          orderId = GetAtmStrategyUniqueId();
          AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, limitpricelong, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);
          If I am reading this correctly, the variable atmStrategyId and orderId are assigned the same value, then are referenced in the next line of code as if they are different..

          AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, limitpricelong, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);

          Why is this? and why does this code not work?

          Code:
          else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
          			{atmStrategyId = string.Empty;	
          			orderId = string.Empty;}
          The error I am receiving after the first bar updates is: AtmStrategyCancel Order() method error: Missing orderId parameter...

          I know we can do this...I just can't do it alone.

          Comment


            #6
            Originally posted by sarasotavince View Post
            I think I've taken a step backwards, with that last code modification the cancel order does not even work the first time...hmmm.

            So since I've taken a step back let's take another step back and look at this code:
            Code:
            atmStrategyId = GetAtmStrategyUniqueId();
            orderId = GetAtmStrategyUniqueId();
            AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, limitpricelong, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);
            If I am reading this correctly, the variable atmStrategyId and orderId are assigned the same value, then are referenced in the next line of code as if they are different..

            AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, limitpricelong, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);

            Why is this? and why does this code not work?

            Code:
            else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                        {atmStrategyId = string.Empty;    
                        orderId = string.Empty;}
            The error I am receiving after the first bar updates is: AtmStrategyCancel Order() method error: Missing orderId parameter...

            I know we can do this...I just can't do it alone.
            Sounds like you have a logic flow error. It seems that the logic of your code is trying to cancel an order using an orderID that is empty, (or null, as it is a string).

            One quick and dirty way is to try filtering for the null condition before you issue the cancellation order. A better way is to correct the logic flow to ensure that the cancellation order cannot be called if the orderID is null or an empty string. These two may well be the same. It is hard to say without seeing the code itself.
            Last edited by koganam; 02-14-2014, 03:58 PM.

            Comment


              #7
              I am posting the code (with stuff you don't need taken out)... When I run the strategy as is, it works one time. It submits the order, then cancels the order...but never sends another order.

              I thank koganam and Matthew for taking a look. The problem seems to be resetting the orderId and the atmStrategyId... no matter what I try, the code fails.

              Relevant Variables:
              Code:
              private int barNumberOfOrder=0;
              private string	atmStrategyId		= string.Empty;
              private string	orderId			= string.Empty;
              Code:
              if (
              			orderId.Length == 0 && atmStrategyId.Length == 0															
              			Blah Blah Blah (my stuff)
              			{
              			atmStrategyId = GetAtmStrategyUniqueId();
              			orderId = GetAtmStrategyUniqueId();
              			AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, limitpricelong, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);	
              			barNumberOfOrder = CurrentBar;
              			}
              			
              		if ( 
              			orderId.Length == 0 && atmStrategyId.Length == 0															
              			my stuff again
              			) 
              			{
              			atmStrategyId = GetAtmStrategyUniqueId();
              			orderId = GetAtmStrategyUniqueId();
              			AtmStrategyCreate(Cbi.OrderAction.Sell, OrderType.Limit, limitpriceshort, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);		
              			barNumberOfOrder = CurrentBar;
              			upScore=0;
              			downScore=1;
              			ok2Trade=0;
              			}
              			
              			if (CurrentBar > barNumberOfOrder + 1)
              				{AtmStrategyCancelEntryOrder(orderId);}
              So LONG or SHORT, first order,no problem...the cancel order for that order, no problem; after that, nothing...

              Comment


                #8
                Originally posted by sarasotavince View Post
                I am posting the code (with stuff you don't need taken out)... When I run the strategy as is, it works one time. It submits the order, then cancels the order...but never sends another order.

                I thank koganam and Matthew for taking a look. The problem seems to be resetting the orderId and the atmStrategyId... no matter what I try, the code fails.

                Relevant Variables:
                Code:
                private int barNumberOfOrder=0;
                private string    atmStrategyId        = string.Empty;
                private string    orderId            = string.Empty;
                Code:
                if (
                            orderId.Length == 0 && atmStrategyId.Length == 0                                                            
                            Blah Blah Blah (my stuff)
                            {
                            atmStrategyId = GetAtmStrategyUniqueId();
                            orderId = GetAtmStrategyUniqueId();
                            AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, limitpricelong, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);    
                            barNumberOfOrder = CurrentBar;
                            }
                            
                        if ( 
                            orderId.Length == 0 && atmStrategyId.Length == 0                                                            
                            my stuff again
                            ) 
                            {
                            atmStrategyId = GetAtmStrategyUniqueId();
                            orderId = GetAtmStrategyUniqueId();
                            AtmStrategyCreate(Cbi.OrderAction.Sell, OrderType.Limit, limitpriceshort, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);        
                            barNumberOfOrder = CurrentBar;
                            upScore=0;
                            downScore=1;
                            ok2Trade=0;
                            }
                            
                            if (CurrentBar > barNumberOfOrder + 1)
                                {AtmStrategyCancelEntryOrder(orderId);}
                So LONG or SHORT, first order,no problem...the cancel order for that order, no problem; after that, nothing...
                Looking ONLY at what you have written, once you nullify the orderId, this statement will be calling with a null reference the next time is is called. As written, it is being called unconditionally.
                Code:
                if (CurrentBar > barNumberOfOrder + 1)
                                {AtmStrategyCancelEntryOrder(orderId);}
                Yes, it will be called because, having made no other arrangements, (CurrentBar > barNumberOfOrder + 1) is true on every bar after it first becomes true, as CurrentBar is monotonically increasing.
                Last edited by koganam; 02-14-2014, 04:47 PM.

                Comment


                  #9
                  I am not sure I understand 100% of what you are saying... unconditional is bad, I take it. What can you suggest to "reset" the strategy so that it can take the next valid trade and cancel the order if not filled?

                  Comment


                    #10
                    Oh, I might have mislead you in the last post... only one condition can be true... the if statements are for a LONG and a SHORT...once a short trade fires, the long trade is next....and visa versa... then, once the order is in, the cancel line takes over if the order is not filled at the limitprice I set...

                    that's what the upScore, downScore stuff is all about...only one condition can be true at a time.

                    Comment


                      #11
                      Originally posted by sarasotavince View Post
                      Oh, I might have mislead you in the last post... only one condition can be true... the if statements are for a LONG and a SHORT...once a short trade fires, the long trade is next....and visa versa... then, once the order is in, the cancel line takes over if the order is not filled at the limitprice I set...

                      that's what the upScore, downScore stuff is all about...only one condition can be true at a time.
                      Unfortunately, not knowing what you are doing, I cannot really make suggestions. I understand totally that you do not want to disclose your secret sauce, but in this case, as you are seeking the mechanics of calling an ATM strategy, your secret sauce is not the issue. Replace your secret sauce with a simple entry condition (e.g, price crosses moving average), and post the entire code.

                      If you still object to that, then we can hope that NT will let you send in the code to them, so that they can help you.

                      Comment


                        #12
                        Thanks for understanding...here is all of the code,but not the variables...you have seen the strings in a prior post--the others don't matter to this example. I could not make sense of the atm example as there were too many lines of code I did not understand. If I don't understand it, I do not use it. I have tried to increase my ninjascript coding knowledge but so many things just don't make sense to me...I tried in another post to call a variable from an indicator into this strategy and it made my head spin. I still need to do that...it's where I get the value for ok2Trade, which for now I am adding manually...but let's save that for another day. I really appreciate your willingness to spread your knowledge.
                        Code:
                        //enters LONG trade
                        		if (
                        			orderId.Length == 0 && atmStrategyId.Length == 0															
                        			&& EMA(4)[0]> EMA(21)[0]
                        			&& ok2Trade==1)
                        			
                        			{
                        			atmStrategyId = GetAtmStrategyUniqueId();
                        			orderId = GetAtmStrategyUniqueId();
                        			AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, limitpricelong, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);	
                        			barNumberOfOrder = CurrentBar;
                        			upScore=1;
                        			downScore=0;
                        			ok2Trade=0;}
                        		//enters SHORT trade	
                        		if ( 
                        			orderId.Length == 0 && atmStrategyId.Length == 0															
                        			&& EMA(4)[0]< EMA(21)[0]
                        			&& downScore==0
                        			&& ok2Trade==1
                        			) 
                        			{
                        			atmStrategyId = GetAtmStrategyUniqueId();
                        			orderId = GetAtmStrategyUniqueId();
                        			AtmStrategyCreate(Cbi.OrderAction.Sell, OrderType.Limit, limitpriceshort, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);		
                        			barNumberOfOrder = CurrentBar;
                        			upScore=0;
                        			downScore=1;
                        			ok2Trade=0;
                        			}
                        			
                        			if (CurrentBar > barNumberOfOrder + 1)
                        				{AtmStrategyCancelEntryOrder(orderId);}
                        that's it....getting this to work twice in a row (a long and a short) has been several hours of trail and all errors. Again, thanks for taking a look.

                        Comment


                          #13
                          Originally posted by sarasotavince View Post
                          Thanks for understanding...here is all of the code,but not the variables...you have seen the strings in a prior post--the others don't matter to this example. I could not make sense of the atm example as there were too many lines of code I did not understand. If I don't understand it, I do not use it. I have tried to increase my ninjascript coding knowledge but so many things just don't make sense to me...I tried in another post to call a variable from an indicator into this strategy and it made my head spin. I still need to do that...it's where I get the value for ok2Trade, which for now I am adding manually...but let's save that for another day. I really appreciate your willingness to spread your knowledge.
                          Code:
                          //enters LONG trade
                                  if (
                                      orderId.Length == 0 && atmStrategyId.Length == 0                                                            
                                      && EMA(4)[0]> EMA(21)[0]
                                      && ok2Trade==1)
                                      
                                      {
                                      atmStrategyId = GetAtmStrategyUniqueId();
                                      orderId = GetAtmStrategyUniqueId();
                                      AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, limitpricelong, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);    
                                      barNumberOfOrder = CurrentBar;
                                      upScore=1;
                                      downScore=0;
                                      ok2Trade=0;}
                                  //enters SHORT trade    
                                  if ( 
                                      orderId.Length == 0 && atmStrategyId.Length == 0                                                            
                                      && EMA(4)[0]< EMA(21)[0]
                                      && downScore==0
                                      && ok2Trade==1
                                      ) 
                                      {
                                      atmStrategyId = GetAtmStrategyUniqueId();
                                      orderId = GetAtmStrategyUniqueId();
                                      AtmStrategyCreate(Cbi.OrderAction.Sell, OrderType.Limit, limitpriceshort, 0, TimeInForce.Day, orderId, "Atm1", atmStrategyId);        
                                      barNumberOfOrder = CurrentBar;
                                      upScore=0;
                                      downScore=1;
                                      ok2Trade=0;
                                      }
                                      
                                      if (CurrentBar > barNumberOfOrder + 1)
                                          {AtmStrategyCancelEntryOrder(orderId);}
                          that's it....getting this to work twice in a row (a long and a short) has been several hours of trail and all errors. Again, thanks for taking a look.
                          I do not see what else you are doing, so I cannot tell what may be causing your problem. To help you I will have to see the logic of the ENTIRE code, without you disclosing your secret sauce. I cannot really tell much from snippets of code that you think are the problem.

                          As I said, it seems to be a logic flow problem, so showing me isolated pieces of code that you think are the problem achieves nothing. In order to examine the logic flow of your problem, I need to see the entire program. Of course, with your secret sauce replaced with innocuous code. There is nothing wrong with the snippet of code that you have shown: your problem lies in something else that you are doing, and for which you are not accounting. Until I can see that, I cannot help.

                          Comment


                            #14
                            Other than the variables listed out, this is the entire code. Allow me to explain the LOGIC I am trying to achieve.

                            IF my secret sauce produces a buy or sell signal...

                            (and other conditions are favorable...[using ok2Trade from indicator Beta00--which I have manually set to YES (==1) in the strategy for now so a trade order will fire, then have changed to NO (=0) after a trade order fires to keep a new order from being submitted until the current order has finsihed])

                            I want to submit a limit order via a predetermined atm "atm1", give that order 2 bars to fill, if it does not fill, cancel the order, and be ready for the next trade, which in my tests will be a trade to the opposide direction--but in LIVE, could be either a buy or sell--again, depending on the value of ok2Trade--which is why it is so important to access this value from Beta00 as the final YES/NO to firing an order--but I'm willing to address that issue AFTER I can get unlimited back to back orders to fire, cancel or complete regardless of the overall market I filter using ok2Trade...

                            That's it. The variables are for the strings, upScore and downScore (which tells me a long or a short order is needed and not to fire multiple orders off the say signal), the bar counter... really, that's it.

                            If you have any other questions, please post.

                            Comment


                              #15
                              Originally posted by sarasotavince View Post
                              Other than the variables listed out, this is the entire code. Allow me to explain the LOGIC I am trying to achieve.

                              IF my secret sauce produces a buy or sell signal...

                              (and other conditions are favorable...[using ok2Trade from indicator Beta00--which I have manually set to YES (==1) in the strategy for now so a trade order will fire, then have changed to NO (=0) after a trade order fires to keep a new order from being submitted until the current order has finsihed])

                              I want to submit a limit order via a predetermined atm "atm1", give that order 2 bars to fill, if it does not fill, cancel the order, and be ready for the next trade, which in my tests will be a trade to the opposide direction--but in LIVE, could be either a buy or sell--again, depending on the value of ok2Trade--which is why it is so important to access this value from Beta00 as the final YES/NO to firing an order--but I'm willing to address that issue AFTER I can get unlimited back to back orders to fire, cancel or complete regardless of the overall market I filter using ok2Trade...

                              That's it. The variables are for the strings, upScore and downScore (which tells me a long or a short order is needed and not to fire multiple orders off the say signal), the bar counter... really, that's it.

                              If you have any other questions, please post.
                              It cannot be the entire code. Earlier you talked of resetting some variables. I do not see any such thing here. Moreover, I do not know the scope of the variables, as that is not disclosed either.

                              When you are ready to post the entire code, I will be able to help. Sorry, if you think that I am being obtuse, but I can only help resolve a logic flow problem if I can see the entire code; every last bit of it. When you are ready to disclose all the code, regardless of your assessment of its relevance, someone will be able to help you.

                              In times past, I have written entire code from scratch for free, but I have already sworn never to do so again, after the actions of multiple ingrates for whom I wrote such free code. Yes, I know that you have shown your gratitude multiple times. Unfortunately, my decision will not be revoked.

                              If I see your code, I may be able to correct your logic. If you will not post a version of the code that shows EVERYTHING, there is nothing more that I can do. Again, I do not want to see your secret sauce, just the entire logic of the code: every part of it; not just the snippets that you think are important.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by MacDad, 02-25-2024, 11:48 PM
                              7 responses
                              157 views
                              0 likes
                              Last Post loganjarosz123  
                              Started by Belfortbucks, Today, 09:29 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post Belfortbucks  
                              Started by zstheorist, Today, 07:52 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post zstheorist  
                              Started by pmachiraju, 11-01-2023, 04:46 AM
                              8 responses
                              151 views
                              0 likes
                              Last Post rehmans
                              by rehmans
                               
                              Started by mattbsea, Today, 05:44 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post mattbsea  
                              Working...
                              X