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

    #16
    koganam,

    I am away from my trader computer but I assure you I have showed all the code in the main section after OnBarUpdate, of course the variables are above that section.

    As for the reseting of some variables, I am referring to the upScore and the downScore...(and the ok2Trade from 1 to 0 after an order fires) since I only want one entry per "signal." After the long order is entered, for example, I change the upScore to "1" and the downScore to "0"...visa versa for a Short trade) that way after the next bar updates, since the upScore=1, the code won't show another opportunity for a trade ...early on without the upScore and downScore variables, the indicator code in Beta00 was showing an order entry opportunity after every bar that met the trade conditions...and the strategy code herein to enter an order mirrors the indicator code, that's why I want to "read" the ok2Trade variable from Beta00 and not manage it manually.


    Please realize I am not asking for you, or anyone, to write the code, just show me my mistakes (or fill the gaps in my understanding). As I stated earlier, I want to understand the code because when I trade it LIVE, I am responsible, no one else.

    So, before the end of the day, I am going to post the entire code, variables, everything, right on down to the last " } "and/or I can upload the indicator. Yes, I will strip out the "sauce" but I will make sure what I include is code that compiles and will launch an order. And, just to restate, the code at present will launch an order and cancel an order, but that it...no second order and/or no second cancellation. If I removed and reloaded the strategy after each trade opportunity it would work--but that's 10 to 15 times in a 3 hour period...kind of defeats the purpose and increases the odds of making a mistake.

    You will find I am most willing to learn and will comply with any reasonable requests--and you have been most reasonable and patient. Thank you. Stay tuned.

    Comment


      #17
      As promised: the entire code, 101 lines...if you want/need the .cs file just say the word. Just to recap....the strategy will run one time, then do nothing...if I remove and reload, it will run one time.

      Code:
      region Using declarations
      using System;
      using System.ComponentModel;
      using System.Diagnostics;
      using System.Drawing;
      using System.Drawing.Drawing2D;
      using System.Xml.Serialization;
      using NinjaTrader.Cbi;
      using NinjaTrader.Data;
      using NinjaTrader.Indicator;
      using NinjaTrader.Gui.Chart;
      using NinjaTrader.Strategy;
      #endregion
      
      // This namespace holds all strategies and is required. Do not change it.
      namespace NinjaTrader.Strategy
      {
          /// <summary>
          /// Coast to Coast
          /// </summary>
          [Description("Strategy1")]
          public class forPosting : Strategy
          {
              #region Variables
              // Wizard generated variables
      		private int upScore=0;
      		private int downScore=0;
      		private double limitpriceshort=0;
      		private double limitpricelong=0;
      		private int ok2Trade=1; // 0 = no, 1 = yes //manually set to 1 for now
      		private int barNumberOfOrder=0;
      		private string	atmStrategyId		= string.Empty;
      		private string	orderId				= string.Empty;
      		
      		
              // User defined variables (add any user defined variables below)
              #endregion
      
              /// <summary>
              /// This method is used to configure the strategy and is called once before any strategy method is called.
              /// </summary>
              protected override void Initialize()
              {
                  CalculateOnBarClose = true;
              }
      
              /// <summary>
              /// Called on each bar update event (incoming tick)
              /// </summary>
              protected override void OnBarUpdate()
              {
      		if (Historical)
      				return;	
      	
      		limitpriceshort= EMA(4)[0] - 1* TickSize;
      		limitpricelong= EMA(4)[0] + 1* TickSize;
      		
      		//enters LONG trade
      		if (
      			orderId.Length == 0 && atmStrategyId.Length == 0															
      			&& (CrossAbove(SMA(4), SMA(14), 1))
      			&& ok2Trade==1)//manually set to 1. Want to draw from Beta00 later
      			
      			{
      			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; can't use right now - all trades are approved
      			}
      		//enters SHORT trade	
      		if ( 
      			orderId.Length == 0 && atmStrategyId.Length == 0															
      			&& (CrossBelow(SMA(4), SMA(14), 1))
      			&& downScore==0
      			&& ok2Trade==1//manually set to 1. Want to draw from Beta00 later
      			) 
      			{
      			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; can't use right now - all trades are approved
      
      			}
      			
      			if (CurrentBar > barNumberOfOrder + 1)
      				{AtmStrategyCancelEntryOrder(orderId);}
      		
      			
              } // end of code
      
              #region Properties
              
              #endregion
          }
      }

      Comment


        #18
        Here is the first part of your entry condition:
        Code:
        If (orderId.Length == 0 && atmStrategyId.Length == 0 ...)
        Well, according to the code that you have posted, the only time that this is true is when you first apply the strategy, because after that first trade, your code never resets those objects to where their length is zero.

        At the very least, you will have to reset those entities at some point within your code. To do it in a robust manner, you want to check the status of your orders and act accordingly, at the correct place.

        How does adding this work?
        Code:
                    // Check for a pending entry order
                    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)
                        {
        
                            if (CurrentBar > barNumberOfOrder + 1 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                            {
                                AtmStrategyCancelEntryOrder(orderId); //cancel order if not filled after 2 bars
                            }
                            // If the order state is terminal, reset the order id value
                            if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
                                orderId = string.Empty; //reset orderId
                        }
                    } // If the strategy has terminated reset the strategy id
                    else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                        atmStrategyId = string.Empty; //reset atmStrategyId
        See how I moved your cancel order code?

        Comment


          #19
          koganam,

          You can see in post #3 I tried something like what you have posted. But it seemed like way more than I needed. What I'd like to understand for the moment is this line:
          Code:
          if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
          status does not appear to be a variable one must define beforehand... and what's with the [2] ? Does the 2 mean two bars including the order bar? I can see a time when I might want to cancel after 1 bar or 4 bars, so that could be a variable I might want to change based on market conditions.

          meanwhile I will adjust my code with your suggestions and do some testing.

          Comment


            #20
            Originally posted by sarasotavince View Post
            koganam,

            You can see in post #3 I tried something like what you have posted. But it seemed like way more than I needed. What I'd like to understand for the moment is this line:
            Code:
            if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
            status does not appear to be a variable one must define beforehand... and what's with the [2] ? Does the 2 mean two bars including the order bar? I can see a time when I might want to cancel after 1 bar or 4 bars, so that could be a variable I might want to change based on market conditions.

            meanwhile I will adjust my code with your suggestions and do some testing.
            This line defines status as an array of strings and populates it with the status of the order.
            Code:
            string[] status = GetAtmStrategyEntryOrderStatus(orderId);
            status[2] is the third member of the array, and contains the state of the order.

            Comment


              #21
              Ok...code is working...so, that's great and moves me to the next step. Thank You.

              I will research status[] more on my own but will leave the code as is for now.

              I think this thread can be considered closed but if anyone has any additional questions/comments I will do my best to answer.

              Comment


                #22
                Originally posted by sarasotavince View Post
                Ok...code is working...so, that's great and moves me to the next step. Thank You.

                I will research status[] more on my own but will leave the code as is for now.

                I think this thread can be considered closed but if anyone has any additional questions/comments I will do my best to answer.
                Read the comments in my code, and you will see that there is nothing special about status. It is just a an array of strings, declared to hold the status of the order, so that it can be examined. It is called "status" simply to make it meaningful for later reading. You could just have easily declared it as:
                Code:
                string[] WhyTheHellIsThisSo = GetAtmStrategyEntryOrderStatus(orderId);
                and query it as WhyTheHellIsThisSo[2] to get the order status.

                As you can see, one is much easier to understand than the other.

                Comment


                  #23
                  Actually, that would have been easier for me to understand :-)

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by GussJ, 03-04-2020, 03:11 PM
                  11 responses
                  3,229 views
                  0 likes
                  Last Post xiinteractive  
                  Started by andrewtrades, Today, 04:57 PM
                  1 response
                  14 views
                  0 likes
                  Last Post NinjaTrader_Manfred  
                  Started by chbruno, Today, 04:10 PM
                  0 responses
                  7 views
                  0 likes
                  Last Post chbruno
                  by chbruno
                   
                  Started by josh18955, 03-25-2023, 11:16 AM
                  6 responses
                  441 views
                  0 likes
                  Last Post Delerium  
                  Started by FAQtrader, Today, 03:35 PM
                  0 responses
                  12 views
                  0 likes
                  Last Post FAQtrader  
                  Working...
                  X