Lean  $LEAN_TAG$
FilteredIdentity.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 QuantConnect.Data;
18 using System;
19 
21 {
22  /// <summary>
23  /// Represents an indicator that is a ready after ingesting a single sample and
24  /// always returns the same value as it is given if it passes a filter condition
25  /// </summary>
26  public class FilteredIdentity : IndicatorBase<IBaseData>
27  {
28  private IBaseData _previousInput;
29  private readonly Func<IBaseData, bool> _filter;
30 
31  /// <summary>
32  /// Initializes a new instance of the FilteredIdentity indicator with the specified name
33  /// </summary>
34  /// <param name="name">The name of the indicator</param>
35  /// <param name="filter">Filters the IBaseData send into the indicator, if null defaults to true (x => true) which means no filter</param>
36  public FilteredIdentity(string name, Func<IBaseData, bool> filter)
37  : base(name)
38  {
39  // default our filter to true (do not filter)
40  _filter = filter ?? (x => true);
41  }
42 
43  /// <summary>
44  /// Gets a flag indicating when this indicator is ready and fully initialized
45  /// </summary>
46  public override bool IsReady => Samples > 0 && Current.Value > 0;
47 
48  /// <summary>
49  /// Computes the next value of this indicator from the given state
50  /// </summary>
51  /// <param name="input">The input given to the indicator</param>
52  /// <returns>A new value for this indicator</returns>
53  protected override decimal ComputeNextValue(IBaseData input)
54  {
55  if (_filter(input))
56  {
57  _previousInput = input;
58  return input.Value;
59  }
60 
61  if (_previousInput != null)
62  {
63  return _previousInput.Value;
64  }
65 
66  // if _previousInput is null, create an empty IBaseData object of the same type of the input
67  switch (input.DataType)
68  {
69  case MarketDataType.TradeBar:
70  _previousInput = new TradeBar();
71  break;
72  case MarketDataType.QuoteBar:
73  _previousInput = new QuoteBar();
74  break;
75  default:
76  _previousInput = new Tick();
77  break;
78  }
79 
80  return _previousInput.Value;
81  }
82  }
83 }