Lean  $LEAN_TAG$
TrueRange.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
18 
20 {
21  /// <summary>
22  /// This indicator computes the True Range (TR).
23  /// The True Range is the greatest of the following values:
24  /// value1 = distance from today's high to today's low.
25  /// value2 = distance from yesterday's close to today's high.
26  /// value3 = distance from yesterday's close to today's low.
27  /// </summary>
29  {
30  private IBaseDataBar _previousInput;
31 
32  /// <summary>
33  /// Initializes a new instance of the <see cref="TrueRange"/> class using the specified name.
34  /// </summary>
35  public TrueRange()
36  : base("TR")
37  {
38  }
39 
40  /// <summary>
41  /// Initializes a new instance of the <see cref="TrueRange"/> class using the specified name.
42  /// </summary>
43  /// <param name="name">The name of this indicator</param>
44  public TrueRange(string name)
45  : base(name)
46  {
47  }
48 
49  /// <summary>
50  /// Gets a flag indicating when this indicator is ready and fully initialized
51  /// </summary>
52  public override bool IsReady => Samples > 1;
53 
54  /// <summary>
55  /// Required period, in data points, for the indicator to be ready and fully initialized.
56  /// </summary>
57  public int WarmUpPeriod => 2;
58 
59  /// <summary>
60  /// Computes the next value of this indicator from the given state
61  /// </summary>
62  /// <param name="input">The input given to the indicator</param>
63  /// <returns>A new value for this indicator</returns>
64  protected override decimal ComputeNextValue(IBaseDataBar input)
65  {
66  if (!IsReady)
67  {
68  _previousInput = input;
69  return 0m;
70  }
71 
72  var greatest = input.High - input.Low;
73 
74  var value2 = Math.Abs(_previousInput.Close - input.High);
75  if (value2 > greatest)
76  greatest = value2;
77 
78  var value3 = Math.Abs(_previousInput.Close - input.Low);
79  if (value3 > greatest)
80  greatest = value3;
81 
82  _previousInput = input;
83 
84  return greatest;
85  }
86  }
87 }