/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections; using System.Collections.Generic; namespace QuantConnect.Indicators { /// /// Provides a base class for types that maintain a rolling window history of values. /// This is the single source of truth for window logic shared between indicators and consolidators. /// /// The type of value stored in the rolling window public abstract class WindowBase : IEnumerable { private RollingWindow _window; /// /// The default number of values to keep in the rolling window history /// public static int DefaultWindowSize { get; } = 2; /// /// Initializes a new instance of the class. /// protected WindowBase() { } /// /// Initializes the rolling window with the given size. /// protected WindowBase(int windowSize) { _window = new RollingWindow(windowSize); } /// /// A rolling window keeping a history of values. The most recent value is at index 0. /// Uses lazy initialization to support Python subclasses that do not call base constructors. /// public virtual RollingWindow Window => _window ??= new RollingWindow(DefaultWindowSize); /// /// Gets the most recent value. The protected setter adds the value to the rolling window. /// public virtual T Current { get { return Window[0]; } protected set { Window.Add(value); } } /// /// Gets the previous value, or default if fewer than two values have been produced. /// public virtual T Previous => Window.Count > 1 ? Window[1] : default; /// /// Indexes the history window, where index 0 is the most recent value. /// /// The index /// The ith most recent value public T this[int i] => Window[i]; /// /// Returns an enumerator that iterates through the history window. /// public IEnumerator GetEnumerator() => Window.GetEnumerator(); /// /// Returns an enumerator that iterates through the history window. /// IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// /// Resets the rolling window, clearing all stored values. /// protected void ResetWindow() { _window?.Reset(); } } }