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

ATR in Ticks

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

    ATR in Ticks

    I have an ATR Indicator which plots ATR in a lower panel. I would like to have it plot the ATR in Ticks so it is easy to set my profit and stop targets based on what I see in ticks on the dom and chart. I just took the standard ATR indicator and modified it to adjust the atr reading up to a unit value (no decimals) corresponding to ticks, but when I adjust it, nothing prints out. If I remove the adjustment it works fine. I've tried the adjustment two ways, multiplying by a scaler, which I adjust to get values above 1, (in the case of Crude Oil, CL, the scaler is set to 100. I also tried multiplying the atr value by 1/TickSize which I think should do the same thing but it also doesn't work. Here is the program code which I am using and which doesn't work,

    Code:
    	public class ATRTicks : Indicator
    	{
    		#region Variables
    		private int			period		= 14;
    		private double		scaler		= 100;
    		#endregion
    
    		/// <summary>
    		/// This method is used to configure the indicator and is called once before any bar data is loaded.
    		/// </summary>
    		protected override void Initialize()
    		{
    			Add(new Plot(Color.Green, "ATRTicks"));
    		}
    
    		/// <summary>
    		/// Called on each bar update event (incoming tick)
    		/// </summary>
    		protected override void OnBarUpdate()
    		{
    			if (CurrentBar == 0)
    				Value.Set((High[0] - Low[0]) * 1/TickSize);
    			else
    			{
    				double trueRange = (High[0] - Low[0]);
    				trueRange = Math.Max(Math.Abs(Low[0] - Close[1]), Math.Max(trueRange, Math.Abs(High[0] - Close[1])));
    				Value.Set((((Math.Min(CurrentBar + 1, Period) - 1 ) * Value[1] + trueRange) / Math.Min(CurrentBar + 1, Period)) * 1/TickSize);
    			}
    		}
    
    		#region Properties
    		/// <summary>
    		/// </summary>
    		[Description("Numbers of bars used for calculations")]
    		[GridCategory("Parameters")]
    		public int Period
    		{
    			get { return period; }
    			set { period = Math.Max(1, value); }
    		}
    		[Description("Scaler to take convert calculation to ticks")]
    		[GridCategory("Parameters")]
    		public double Scaler
    		{
    			get { return scaler; }
    			set { scaler = Math.Max(1, value); }
    		}		
    		#endregion
    	}
    I am providing the code for the second case (multiply atr value by 1/TickSize). The first case I simply multiply the ATR result by Scaler. neither works. When I remove the multiplication portion of the code, it works fine.

    Thanks

    DaveN

    #2
    Hello daven,
    If I Print out the Plot values I am getting "Infinite" for some of the bars. You need to make sure the values are valid (i.e not dividing by 0 (zero) etc.

    For more debugging tips please refer to this post
    JoydeepNinjaTrader Customer Service

    Comment


      #3
      ATR in Ticks

      I put in print statements as your example showed and also so those infinite values, clearly I am dividing by zero somewhere but it isn't clear to me where that is occurring. I decided to try something a bit simpler and it too is proving to be a challenge. I think that what I am trying to do shouldn't be that tough. I just want to scale an output so that it is easier to read and understand in the heat of battle. The following code works, but when I try and take the range value, set it to an intermediate double value so that I can multiply it to scale it, the second version doesn't work.
      This compiles and runs:

      Code:
      				Value.Set(EMADN(Range(), 10)[0]);
      But this doesn't and I'm not sure why. Perhaps I need to turn the double variable intRange into a DataSeries?

      Code:
      				double intRange = Range()[0];
      				Print(CurrentBar + "  Range Value is:  " + intRange);
      				
      				Value.Set(EMA(intRange, 10)[0]);

      Comment


        #4
        Hello daven,
        The overload for an EMA is IDataSeries and integer. You are overloading it with an double and an integer and thus it is not compiling.
        JoydeepNinjaTrader Customer Service

        Comment


          #5
          ATRTicks Continued

          Thanks, I fixed it by converting the argument into a dataseries and it worked fine. I scaled it with the factor 1/TickSize so it would in theory anyway, self calibrate to the smallest tick value for the instrument, and again that seems to work. I( also added in a max and min for the tick value so I can see in the panel, what the variation of atr looks like on a per bar basis. Again, it all worked, I'm attaching a picture of the indicator so you can see, and better understand my next questions.

          Here's what the code looks like now:

          Code:
          		protected override void Initialize()
          		{
          			Add(new Plot(Color.Green, PlotStyle.Square, "ATRinTicks"));
          			Add(new Plot(Color.Cyan, PlotStyle.Line, "Max_ATR"));
          			Add(new Plot(Color.Magenta, PlotStyle.Line, "Min_ATR"));
          			
          			intRange = new DataSeries(this);
          		}
          
          		/// <summary>
          		/// Called on each bar update event (incoming tick)
          		/// </summary>
          		protected override void OnBarUpdate()
          		{
          			if(CurrentBar <= Period) return;
          
          				intRange.Set((High[0] - Low[0]) * 1/TickSize);
          				Print(CurrentBar + "  Range Value is:  " + intRange);
          				
          				Value.Set(EMA(intRange, Period)[0]);
          				Max_ATR.Set(MAX(intRange, Period)[0]);
          				Min_ATR.Set(MIN(intRange, Period)[0]);
          				
          				Print (CurrentBar + "  Average True Range is:  " + Value[0]);
          
          		}
          
          		#region Properties
          		/// <summary>
          		/// </summary>
          		[Description("Numbers of bars used for calculations")]
          		[GridCategory("Parameters")]
          		public int Period
          		{
          			get { return period; }
          			set { period = Math.Max(1, value); }
          		}
          //		[Description("Scaler to take convert calculation to ticks")]
          //		[GridCategory("Parameters")]
          //		public double Scaler
          //		{
          //			get { return scaler; }
          //			set { scaler = Math.Max(1, value); }
          //		}	
          		[Browsable(false)]
          		[XmlIgnore()]
          		public DataSeries ATRinTicks
          		{
          			get { return Values[0]; }
          		}
          		[Browsable(false)]
          		[XmlIgnore()]
          		public DataSeries Max_ATR
          		{
          			get { return Values[1]; }
          		}
          		[Browsable(false)]
          		[XmlIgnore()]
          		public DataSeries Min_ATR
          		{
          			get { return Values[2]; }
          		}
          		#endregion
          Is there a way to truncate the value so what displays for ATRTicks is an integer? If I do that, and then use this indicator in a strategy (that is my next step), will truncating it affect it's performance in a strategy? I plan on using ATRTicks as a proxy for both stops and profits. My intent is to make the strategy as self-adjusting to volatility as possible so I don't have to optimize things since that is often the source of my performance difficulties.

          Thanks

          DaveN
          Attached Files

          Comment


            #6
            Hello DaveN,
            Yes, you can. If you convert the EMA value to an integer you will get the values as integer (plots will still return a double value but it wont have the decimals).

            Code:
            Value.Set((int)EMA(intRange, Period)[0]);
            JoydeepNinjaTrader Customer Service

            Comment


              #7
              Originally posted by daven View Post
              Thanks, I fixed it by converting the argument into a dataseries and it worked fine. I scaled it with the factor 1/TickSize so it would in theory anyway, self calibrate to the smallest tick value for the instrument, and again that seems to work. I( also added in a max and min for the tick value so I can see in the panel, what the variation of atr looks like on a per bar basis. Again, it all worked, I'm attaching a picture of the indicator so you can see, and better understand my next questions.

              Here's what the code looks like now:

              Code:
                      protected override void Initialize()
                      {
                          Add(new Plot(Color.Green, PlotStyle.Square, "ATRinTicks"));
                          Add(new Plot(Color.Cyan, PlotStyle.Line, "Max_ATR"));
                          Add(new Plot(Color.Magenta, PlotStyle.Line, "Min_ATR"));
                          
                          intRange = new DataSeries(this);
                      }
              
                      /// <summary>
                      /// Called on each bar update event (incoming tick)
                      /// </summary>
                      protected override void OnBarUpdate()
                      {
                          if(CurrentBar <= Period) return;
              
                              intRange.Set((High[0] - Low[0]) * 1/TickSize);
                              Print(CurrentBar + "  Range Value is:  " + intRange);
                              
                              Value.Set(EMA(intRange, Period)[0]);
                              Max_ATR.Set(MAX(intRange, Period)[0]);
                              Min_ATR.Set(MIN(intRange, Period)[0]);
                              
                              Print (CurrentBar + "  Average True Range is:  " + Value[0]);
              
                      }
              
                      #region Properties
                      /// <summary>
                      /// </summary>
                      [Description("Numbers of bars used for calculations")]
                      [GridCategory("Parameters")]
                      public int Period
                      {
                          get { return period; }
                          set { period = Math.Max(1, value); }
                      }
              //        [Description("Scaler to take convert calculation to ticks")]
              //        [GridCategory("Parameters")]
              //        public double Scaler
              //        {
              //            get { return scaler; }
              //            set { scaler = Math.Max(1, value); }
              //        }    
                      [Browsable(false)]
                      [XmlIgnore()]
                      public DataSeries ATRinTicks
                      {
                          get { return Values[0]; }
                      }
                      [Browsable(false)]
                      [XmlIgnore()]
                      public DataSeries Max_ATR
                      {
                          get { return Values[1]; }
                      }
                      [Browsable(false)]
                      [XmlIgnore()]
                      public DataSeries Min_ATR
                      {
                          get { return Values[2]; }
                      }
                      #endregion
              Is there a way to truncate the value so what displays for ATRTicks is an integer? If I do that, and then use this indicator in a strategy (that is my next step), will truncating it affect it's performance in a strategy? I plan on using ATRTicks as a proxy for both stops and profits. My intent is to make the strategy as self-adjusting to volatility as possible so I don't have to optimize things since that is often the source of my performance difficulties.

              Thanks

              DaveN
              I presume you meant to say: "ATRinTicks is an integer" where you say: "ATRTicks is an integer"?

              The answer is yes and no. A DataSeries must have a double as input for setting, so you cannot use an integer. However, you can always truncate the value into an integer, then cast/convert it back into a double.

              Code:
              double ATRinTicksValue = (double)((int)(EMA(intRange, Period)[0]));
              Value.Set(ATRinTicksValue);
              Naturally, if it is not too confusing, with all that bracketing, you can do it all in one line, with the necessary substitution.

              It is just my style to separate the calculation from the Set operation: I find it easier to read when I come back a few months from now, and wonder what mushrooms I may have been eating when I wrote what is now looking like nonsense.

              Comment


                #8
                ATRTicks continued

                Thanks everyone for your help. I changed the code to reflect the last suggestion from JoyDeep, and the indicator now displays in integer values. I went ahead and did a strategy using the indicator for orginal order placement (entry limit offset by the ATR value, but in the direction of the prevailing trend). I then used the same ATR values for my profit and stop calculations, but am getting a funny result. The limit orders work just fine, but neither the profit nor the stops calculate properly. Here is the code I am using:

                if(goShort[0])
                {
                SetProfitTarget("SBlo_Band", CalculationMode.Ticks, ATRTicks(14).Min_ATR[0] * TickSize );
                SetStopLoss("SBlo_Band", CalculationMode.Ticks, ATRTicks(14).Max_ATR[0] * 2 * TickSize, false);
                EnterShortLimit(DefaultQuantity, Close[0] + ATRTicks(14).ATRinTicks[0] * TickSize, "SBlo_Band");
                }
                As I said, running the strategy with the above code, the limit orders calculate properly for initial entry but both the profit and stop orders end up being an offset of zero so when I look at the trades they are all small stops (essentially one tick or no tick offset). When I comment out the stops and rerun the strategy, all the trades are small losers with the profit target closing out at the entry price. Clearly there is a problem with my calculation but I'm hard pressed to see it. I tried reversing the order, limit entry followed by profit and stop calculations but I get the same results when I test it. Is there something funny I am doing with the profit and loss settings that isn't happening with the limit order settings because the limit entries are working precisely the way they should?
                Thanks
                DaveN

                Comment


                  #9
                  Hello DaveN,
                  You have already calculated the ticks, so no need for multiplying it with TickSize.

                  Please use the below code and see if you can get the correct value

                  Code:
                  SetProfitTarget("SBlo_Band", CalculationMode.Ticks, ATRTicks(14).Min_ATR[0] );
                  JoydeepNinjaTrader Customer Service

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by algospoke, Yesterday, 06:40 PM
                  2 responses
                  19 views
                  0 likes
                  Last Post algospoke  
                  Started by ghoul, Today, 06:02 PM
                  3 responses
                  14 views
                  0 likes
                  Last Post NinjaTrader_Manfred  
                  Started by jeronymite, 04-12-2024, 04:26 PM
                  3 responses
                  45 views
                  0 likes
                  Last Post jeronymite  
                  Started by Barry Milan, Yesterday, 10:35 PM
                  7 responses
                  21 views
                  0 likes
                  Last Post NinjaTrader_Manfred  
                  Started by AttiM, 02-14-2024, 05:20 PM
                  10 responses
                  181 views
                  0 likes
                  Last Post jeronymite  
                  Working...
                  X