/// <summary> /// Creates a new Stochastics Indicator from the specified periods. /// </summary> /// <param name="name">The name of this indicator.</param> /// <param name="period">The period given to calculate the Fast %K</param> /// <param name="kPeriod">The K period given to calculated the Slow %K</param> /// <param name="dPeriod">The D period given to calculated the Slow %D</param> public Stochastic(string name, int period, int kPeriod, int dPeriod) : base(name) { Maximum = new Maximum(name + "_Max", period); Mininum = new Minimum(name + "_Min", period); SumFastK = new Sum(name + "_SumFastK", kPeriod); SumSlowK = new Sum(name + "_SumD", dPeriod); FastStoch = new FunctionalIndicator<TradeBar>(name + "_FastStoch", input => ComputeFastStoch(period, input), fastStoch => Maximum.IsReady, () => Maximum.Reset() ); StochK = new FunctionalIndicator<TradeBar>(name + "_StochK", input => ComputeStochK(period, kPeriod, input), stochK => Maximum.IsReady, () => Maximum.Reset() ); StochD = new FunctionalIndicator<TradeBar>(name + "_StochD", input => ComputeStochD(period, kPeriod, dPeriod), stochD => Maximum.IsReady, () => Maximum.Reset() ); }
/// <summary> /// Initializes a new instance of the <see cref="MidPrice"/> class using the specified name and period. /// </summary> /// <param name="name">The name of this indicator</param> /// <param name="period">The period of the MIDPRICE</param> public MidPrice(string name, int period) : base(name) { _period = period; _maximum = new Maximum(period); _minimum = new Minimum(period); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { //mylog.Debug(transheader); mylog.Debug(ondataheader); //Initialize dates SetStartDate(2013, 10, 07); SetEndDate(2013, 10, 07); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute); maxHigh = new Maximum("MaxHigh", _period); minLow = new Minimum("MinLow", _period); value1 = new RollingWindow<IndicatorDataPoint>(_period); fish = new RollingWindow<IndicatorDataPoint>(_period); //wma = new LinearWeightedMovingAverage(5); // induces 2 bar lag //wwma = new RollingWindow<IndicatorDataPoint>(_period); //fishHigh = new Maximum("FishHigh", 400); //fishLow = new Minimum("FishLow", 400); fx = new FisherTransform(_symbol,_period); //fx = FT(_symbol, _period, Resolution.Minute); // Add a bars to initialize the RollingWindow value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); }
public void ComputesCorrectly() { var min = new Minimum(3); var reference = DateTime.UtcNow; min.Update(reference, 1m); Assert.AreEqual(1m, min.Current.Value); Assert.AreEqual(0, min.PeriodsSinceMinimum); min.Update(reference.AddDays(1), 2m); Assert.AreEqual(1m, min.Current.Value); Assert.AreEqual(1, min.PeriodsSinceMinimum); min.Update(reference.AddDays(2), -1m); Assert.AreEqual(-1m, min.Current.Value); Assert.AreEqual(0, min.PeriodsSinceMinimum); min.Update(reference.AddDays(3), 2m); Assert.AreEqual(-1m, min.Current.Value); Assert.AreEqual(1, min.PeriodsSinceMinimum); min.Update(reference.AddDays(4), 0m); Assert.AreEqual(-1m, min.Current.Value); Assert.AreEqual(2, min.PeriodsSinceMinimum); min.Update(reference.AddDays(5), 3m); Assert.AreEqual(0m, min.Current.Value); Assert.AreEqual(1, min.PeriodsSinceMinimum); min.Update(reference.AddDays(6), 2m); Assert.AreEqual(0m, min.Current.Value); Assert.AreEqual(2, min.PeriodsSinceMinimum); }
/// <summary> /// A Fisher Transform of Prices /// </summary> /// <param name="name">string - the name of the indicator</param> /// <param name="period">The number of periods for the indicator</param> public FisherTransform(string name, int period) : base(name) { _alpha = .33; // Initialize the local variables _medianMax = new Maximum("MedianMax", period); _medianMin = new Minimum("MedianMin", period); }
public void ResetsProperly() { var min = new Minimum(3); min.Update(DateTime.Today, 1m); min.Update(DateTime.Today.AddSeconds(1), 2m); min.Update(DateTime.Today.AddSeconds(2), 1m); Assert.IsTrue(min.IsReady); min.Reset(); Assert.AreEqual(0, min.PeriodsSinceMinimum); TestHelper.AssertIndicatorIsInDefaultState(min); }
/// <summary> /// Creates a new AroonOscillator from the specified up/down periods. /// </summary> /// <param name="name">The name of this indicator</param> /// <param name="upPeriod">The lookback period to determine the highest high for the AroonDown</param> /// <param name="downPeriod">The lookback period to determine the lowest low for the AroonUp</param> public AroonOscillator(string name, int upPeriod, int downPeriod) : base(name) { var max = new Maximum(name + "_Max", upPeriod); AroonUp = new FunctionalIndicator<IndicatorDataPoint>(name + "_AroonUp", input => ComputeAroonUp(upPeriod, max, input), aroonUp => max.IsReady ); var min = new Minimum(name + "_Min", downPeriod); AroonDown = new FunctionalIndicator<IndicatorDataPoint>(name + "_AroonDown", input => ComputeAroonDown(downPeriod, min, input), aroonDown => min.IsReady ); }
public void ResetsProperly() { var left = new Maximum("left", 2); var right = new Minimum("right", 2); var composite = new CompositeIndicator<IndicatorDataPoint>(left, right, (l, r) => l + r); left.Update(DateTime.Today, 1m); right.Update(DateTime.Today,-1m); left.Update(DateTime.Today.AddDays(1), -1m); right.Update(DateTime.Today.AddDays(1), 1m); Assert.AreEqual(left.PeriodsSinceMaximum, 1); Assert.AreEqual(right.PeriodsSinceMinimum, 1); composite.Reset(); TestHelper.AssertIndicatorIsInDefaultState(composite); TestHelper.AssertIndicatorIsInDefaultState(left); TestHelper.AssertIndicatorIsInDefaultState(right); Assert.AreEqual(left.PeriodsSinceMaximum, 0); Assert.AreEqual(right.PeriodsSinceMinimum, 0); }
public bool Equals(NodeValue other) => Minimum.Equals(other.Minimum) && Maximum.Equals(other.Maximum);
public override string ToString() => Minimum.AlmostEquals(Maximum, 1e-10) ? $"{Minimum}" : $"{Minimum} to {Maximum}";
void WriteMinimum(BinaryWriter writer, Minimum minimum) { writer.Write(minimum.UnitClass.ClassIndex); writer.Write(minimum.Percent); }
/// <summary> /// Initializes a new instance of the <see cref="DonchianChannel"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="period">The period.</param> public DonchianChannel(string name, int period) : base(name) { UpperBand = new Maximum(name + "_UpperBand", period); LowerBand = new Minimum(name + "_LowerBand", period); }
/// <summary>Determines if the range is valid.</summary> /// <returns>True if range is valid, else false</returns> public bool IsValid() { return(Minimum.CompareTo(Maximum) <= 0); }
public override string ToString() { return(String.Format("boundingbox[{0} -> {1}]", Minimum.ToString(), Maximum.ToString())); }
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.ToString"]/*' /> /// <devdoc> /// Returns a string representation for this control. /// </devdoc> /// <internalonly/> public override string ToString() { string s = base.ToString(); return(s + ", Minimum: " + Minimum.ToString(CultureInfo.CurrentCulture) + ", Maximum: " + Maximum.ToString(CultureInfo.CurrentCulture) + ", Value: " + Value.ToString(CultureInfo.CurrentCulture)); }
public bool Contains(T value) { return(Minimum.CompareTo(value) <= 0 && Maximum.CompareTo(value) >= 0); }
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.ToString"]/*' /> /// <devdoc> /// Returns a string representation for this control. /// </devdoc> /// <internalonly/> public override string ToString() { string s = base.ToString(); return(s + ", Minimum: " + Minimum.ToString() + ", Maximum: " + Maximum.ToString() + ", Value: " + Value.ToString()); }
/// <summary> /// Initialize the data and resolution you require for your strategy /// </summary> public override void Initialize() { //Initialize SetStartDate(2013, 1, 1); SetEndDate(2014, 12, 31); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: _symbol = AddSecurity(SecurityType.Equity, _ticker, Resolution.Daily).Symbol; //Add the Custom Data: _customSymbol = AddData <Quandl>(_customTicker, Resolution.Daily).Symbol; //Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object) _indicators = new Indicators { BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily), RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily), ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily), EMA = EMA(_symbol, 14, Resolution.Daily), SMA = SMA(_symbol, 14, Resolution.Daily), MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily), AROON = AROON(_symbol, 20, Resolution.Daily), MOM = MOM(_symbol, 20, Resolution.Daily), MOMP = MOMP(_symbol, 20, Resolution.Daily), STD = STD(_symbol, 20, Resolution.Daily), MIN = MIN(_symbol, 14, Resolution.Daily), // by default if the symbol is a tradebar type then it will be the min of the low property MAX = MAX(_symbol, 14, Resolution.Daily) // by default if the symbol is a tradebar type then it will be the max of the high property }; // Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator // These functions have a signature like the following: decimal Selector(BaseData baseData), and can be defined like: baseData => baseData.Value // We'll define these 'selector' functions to select the Low value // // For more information on 'anonymous functions' see: http://en.wikipedia.org/wiki/Anonymous_function // https://msdn.microsoft.com/en-us/library/bb397687.aspx // _selectorIndicators = new Indicators { BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily, Field.Low), RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, Field.Low), EMA = EMA(_symbol, 14, Resolution.Daily, Field.Low), SMA = SMA(_symbol, 14, Resolution.Daily, Field.Low), MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily, Field.Low), MOM = MOM(_symbol, 20, Resolution.Daily, Field.Low), MOMP = MOMP(_symbol, 20, Resolution.Daily, Field.Low), STD = STD(_symbol, 20, Resolution.Daily, Field.Low), MIN = MIN(_symbol, 14, Resolution.Daily, Field.High), // this will find the 14 day min of the high property MAX = MAX(_symbol, 14, Resolution.Daily, Field.Low), // this will find the 14 day max of the low property // ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar // before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, SelectorDoubleTradeBar), AROON = AROON(_symbol, 20, Resolution.Daily, SelectorDoubleTradeBar) }; //Custom Data Indicator: _rsiCustom = RSI(_customSymbol, 14, MovingAverageType.Simple, Resolution.Daily); _minCustom = MIN(_customSymbol, 14, Resolution.Daily); _maxCustom = MAX(_customSymbol, 14, Resolution.Daily); // in addition to defining indicators on a single security, you can all define 'composite' indicators. // these are indicators that require multiple inputs. the most common of which is a ratio. // suppose we seek the ratio of BTC to SPY, we could write the following: var spyClose = Identity(_symbol); var fbClose = Identity(_customSymbol); // this will create a new indicator whose value is FB/SPY _ratio = fbClose.Over(spyClose); // we can also easily plot our indicators each time they update using th PlotIndicator function PlotIndicator("Ratio", _ratio); }
/// <summary>Determines if the provided value is inside the range.</summary> /// <param name="value">The value to test</param> /// <returns>True if the value is inside Range, else false</returns> public bool ContainsValue(T value) { return(Minimum.CompareTo(value) <= 0 && value.CompareTo(Maximum) <= 0); }
/// <summary> /// 資料是否在指定範圍 /// </summary> /// <param name="value"></param> /// <returns></returns> public bool IsRange(T value) { bool result = Minimum.CompareTo(value) <= 0 && Maximum.CompareTo(value) >= 0; return(result); }
/// <summary> /// Creates a new IchimokuKinkoHyo indicator from the specific periods /// </summary> /// <param name="name">The name of this indicator</param> /// <param name="tenkanPeriod">The Tenkan-sen period</param> /// <param name="kijunPeriod">The Kijun-sen period</param> /// <param name="senkouAPeriod">The Senkou A Span period</param> /// <param name="senkouBPeriod">The Senkou B Span period</param> /// <param name="senkouADelayPeriod">The Senkou A Span delay</param> /// <param name="senkouBDelayPeriod">The Senkou B Span delay</param> public IchimokuKinkoHyo(string name, int tenkanPeriod = 9, int kijunPeriod = 26, int senkouAPeriod = 26, int senkouBPeriod = 52, int senkouADelayPeriod = 26, int senkouBDelayPeriod = 26) : base(name) { TenkanMaximum = new Maximum(name + "_TenkanMax", tenkanPeriod); TenkanMinimum = new Minimum(name + "_TenkanMin", tenkanPeriod); KijunMaximum = new Maximum(name + "_KijunMax", kijunPeriod); KijunMinimum = new Minimum(name + "_KijunMin", kijunPeriod); SenkouBMaximum = new Maximum(name + "_SenkouBMaximum", senkouBPeriod); SenkouBMinimum = new Minimum(name + "_SenkouBMinimum", senkouBPeriod); DelayedTenkanSenkouA = new Delay(name + "DelayedTenkan", senkouADelayPeriod); DelayedKijunSenkouA = new Delay(name + "DelayedKijun", senkouADelayPeriod); DelayedMaximumSenkouB = new Delay(name + "DelayedMax", senkouBDelayPeriod); DelayedMinimumSenkouB = new Delay(name + "DelayedMin", senkouBDelayPeriod); SenkouA = new FunctionalIndicator<TradeBar>( name + "_SenkouA", input => computeSenkouA(senkouAPeriod, input), senkouA => DelayedTenkanSenkouA.IsReady && DelayedKijunSenkouA.IsReady, () => { Tenkan.Reset(); Kijun.Reset(); }); SenkouB = new FunctionalIndicator<TradeBar>( name + "_SenkouB", input => computeSenkouB(senkouBPeriod, input), senkouA => DelayedMaximumSenkouB.IsReady && DelayedMinimumSenkouB.IsReady, () => { Tenkan.Reset(); Kijun.Reset(); }); Tenkan = new FunctionalIndicator<TradeBar>( name + "_Tenkan", input => ComputeTenkan(tenkanPeriod, input), tenkan => TenkanMaximum.IsReady && TenkanMinimum.IsReady, () => { TenkanMaximum.Reset(); TenkanMinimum.Reset(); }); Kijun = new FunctionalIndicator<TradeBar>( name + "_Kijun", input => ComputeKijun(kijunPeriod, input), kijun => KijunMaximum.IsReady && KijunMinimum.IsReady, () => { KijunMaximum.Reset(); KijunMinimum.Reset(); }); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { //Initialize dates SetStartDate(2015, 6, 15); SetEndDate(2015, 6, 15); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); #region "Init indicators" Price = new RollingWindow<IndicatorDataPoint>(samplesize); ema = new RollingWindow<IndicatorDataPoint>(samplesize); zema = new RollingWindow<IndicatorDataPoint>(samplesize); OptimalValue1 = new RollingWindow<IndicatorDataPoint>(samplesize); OmtimalValue2 = new RollingWindow<IndicatorDataPoint>(samplesize); OptimalTrackingFilter = new RollingWindow<IndicatorDataPoint>(samplesize); lambda = new RollingWindow<IndicatorDataPoint>(samplesize); alpha = new RollingWindow<IndicatorDataPoint>(samplesize); priceOptimalDiff = new RollingWindow<IndicatorDataPoint>(samplesize); priceOptimalSign = new RollingWindow<IndicatorDataPoint>(samplesize); priceOptimalCross = new RollingWindow<IndicatorDataPoint>(samplesize); fudge = new RollingWindow<IndicatorDataPoint>(samplesize); instantTrend = new RollingWindow<IndicatorDataPoint>(samplesize); instantTrendTrigger = new RollingWindow<IndicatorDataPoint>(samplesize); cyberCycle = new RollingWindow<IndicatorDataPoint>(samplesize); centerGravity = new RollingWindow<IndicatorDataPoint>(samplesize); cyberCycleSmooth = new RollingWindow<IndicatorDataPoint>(samplesize); rvi = new RelativeVigorIndex(8); rviHistory = new RollingWindow<IndicatorDataPoint>(samplesize); stochCenterGravityValue1 = new RollingWindow<IndicatorDataPoint>(8); stochCenterGravityValue2 = new RollingWindow<IndicatorDataPoint>(8); stochCyberCycleValue1 = new RollingWindow<IndicatorDataPoint>(8); stochCyberCycleValue2 = new RollingWindow<IndicatorDataPoint>(8); stochCyberCycleInverseFisher = new RollingWindow<IndicatorDataPoint>(8); stochCyberCycleFisher = new RollingWindow<IndicatorDataPoint>(8); stochRviHistoryValue1 = new RollingWindow<IndicatorDataPoint>(8); stochRviHistoryValue2 = new RollingWindow<IndicatorDataPoint>(8); ROC = new RateOfChange(4); maxCyberCycle = new Maximum(8); minCyberCycle = new Minimum(8); #endregion //mylog.Debug(transheader); mylog.Debug(ondataheader); string msg = "Security,Date,Day Profit,Day Fees, Day Net, Total Profit, Total Fees"; mylog.Debug(msg); mylog.Debug(tradeheader); }
/// <summary> /// AroonDown = 100 * (period - {periods since min})/period /// </summary> /// <param name="downPeriod">The AroonDown period</param> /// <param name="min">A Minimum indicator used to compute periods since min</param> /// <param name="input">The next input data</param> /// <returns>The AroonDown value</returns> private static decimal ComputeAroonDown(int downPeriod, Minimum min, IndicatorDataPoint input) { min.Update(input); return 100m * (downPeriod - min.PeriodsSinceMinimum) / downPeriod; }
/// <summary> /// Creates a new Williams %R. /// </summary> /// <param name="name">The name of this indicator</param> /// <param name="period">The lookback period to determine the highest high for the AroonDown</param> public WilliamsPercentR(string name, int period) : base(name) { Maximum = new Maximum(name + "_Max", period); Minimum = new Minimum(name + "_Min", period); }
/// <summary> /// 資料是否大於基準值 /// </summary> /// <param name="value"></param> /// <returns></returns> public bool IsGreater(T value) { bool result = Minimum.CompareTo(value) <= 0; return(result); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { #region logging var algoname = this.GetType().Name; mylog.Debug(algoname); mylog.Debug(ondataheader); dailylog.Debug(algoname); dailylog.Debug(dailyheader); _transactions = new List<OrderTransaction>(); var days = _endDate.Subtract(_startDate).TotalDays; MaxDailyProfit = new Maximum("MaxDailyProfit", (int)days); MinDailyProfit = new Minimum("MinDailyProfit", (int)days); #endregion //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(_portfolioAmount); //Add as many securities as you like. All the data will be passed into the event handler: //AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); // Initialize the Symbol indexed dictionaries foreach (string s in Symbols) { AddSecurity(SecurityType.Equity, s, Resolution.Minute); Strategy.Add(symbol, new MultiITStrategy(s, ITrendPeriod, this)); Tickets.Add(s, new List<OrderTicket>()); // Equal portfolio shares for every stock. ShareSize.Add(s, (maxLeverage * (1 - leverageBuffer)) / Symbols.Count()); LastOrderSent.Add(s, OrderSignal.doNothing); #region Logging stuff - Initializing Stock Logging //stockLogging.Add(new StringBuilder()); //stockLogging[i].AppendLine("Counter, Time, Close, ITrend, Trigger," + // "Momentum, EntryPrice, Signal," + // "TriggerCrossOverITrend, TriggerCrossUnderITrend, ExitFromLong, ExitFromShort," + // "StateFromStrategy, StateFromPorfolio, Portfolio Value"); //i++; #endregion Logging stuff - Initializing Stock Logging } // Indicators Price = new RollingWindow<IndicatorDataPoint>(14); // The price history // ITrend trend = new InstantaneousTrend("Main", 7, .25m); trendHistory = new RollingWindow<IndicatorDataPoint>(14); // The ITrendStrategy iTrendStrategy = new InstantTrendStrategy(symbol, 14, this); iTrendStrategy.ShouldSellOutAtEod = shouldSellOutAtEod; #region lists // Initialize the lists for the strategies trendList = new Dictionary<int, InstantaneousTrend>(); trendHistoryList = new Dictionary<int, RollingWindow<IndicatorDataPoint>>(); strategyList = new Dictionary<int, MultiITStrategy>(); entryPriceList = new Dictionary<int, decimal>(); int listIndex = 0; for (decimal d = .25m; d < .26m; d += .01m) { trendList.Add(listIndex, new InstantaneousTrend("ITrend_" + d, 7, d)); // eg ITrend.25, period 7, alpha .25 trendHistoryList.Add(listIndex, new RollingWindow<IndicatorDataPoint>(4)); strategyList.Add(listIndex, new MultiITStrategy(symbol, 7, this)); entryPriceList.Add(listIndex, 0); listIndex++; } #endregion #region Proforma _brokerSimulator = new BrokerSimulator(this); #endregion }
/// <summary> /// Initialize the data and resolution you require for your strategy /// </summary> public override void Initialize() { //Initialize SetStartDate(2013, 1, 1); SetEndDate(2014, 12, 31); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute); //Add the Custom Data: AddData<Bitcoin>("BTC"); //Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object) _indicators = new Indicators { BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily), RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily), ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily), EMA = EMA(_symbol, 14, Resolution.Daily), SMA = SMA(_symbol, 14, Resolution.Daily), MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily), AROON = AROON(_symbol, 20, Resolution.Daily), MOM = MOM(_symbol, 20, Resolution.Daily), MOMP = MOMP(_symbol, 20, Resolution.Daily), STD = STD(_symbol, 20, Resolution.Daily), MIN = MIN(_symbol, 14, Resolution.Daily), // by default if the symbol is a tradebar type then it will be the min of the low property MAX = MAX(_symbol, 14, Resolution.Daily) // by default if the symbol is a tradebar type then it will be the max of the high property }; // Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator // These functions have a signature like the following: decimal Selector(BaseData baseData), and can be defined like: baseData => baseData.Value // We'll define these 'selector' functions to select the Low value // // For more information on 'anonymous functions' see: http://en.wikipedia.org/wiki/Anonymous_function // https://msdn.microsoft.com/en-us/library/bb397687.aspx // _selectorIndicators = new Indicators { BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily, Field.Low), RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, Field.Low), EMA = EMA(_symbol, 14, Resolution.Daily, Field.Low), SMA = SMA(_symbol, 14, Resolution.Daily, Field.Low), MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily, Field.Low), MOM = MOM(_symbol, 20, Resolution.Daily, Field.Low), MOMP = MOMP(_symbol, 20, Resolution.Daily, Field.Low), STD = STD(_symbol, 20, Resolution.Daily, Field.Low), MIN = MIN(_symbol, 14, Resolution.Daily, Field.High), // this will find the 14 day min of the high property MAX = MAX(_symbol, 14, Resolution.Daily, Field.Low), // this will find the 14 day max of the low property // ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar // before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, SelectorDoubleTradeBar), AROON = AROON(_symbol, 20, Resolution.Daily, SelectorDoubleTradeBar) }; //Custom Data Indicator: _rsiCustom = RSI(_customSymbol, 14, MovingAverageType.Simple, Resolution.Daily); _minCustom = MIN(_customSymbol, 14, Resolution.Daily); _maxCustom = MAX(_customSymbol, 14, Resolution.Daily); // in addition to defining indicators on a single security, you can all define 'composite' indicators. // these are indicators that require multiple inputs. the most common of which is a ratio. // suppose we seek the ratio of BTC to SPY, we could write the following: var spyClose = Identity(_symbol); var btcClose = Identity(_customSymbol); // this will create a new indicator whose value is BTC/SPY _ratio = btcClose.Over(spyClose); // we can also easily plot our indicators each time they update using th PlotIndicator function PlotIndicator("Ratio", _ratio); }
/// <summary> /// Checks if an value falls within the inclusive bounds of the range. /// </summary> /// <param name="value">The value to check.</param> /// <returns><c>true</c> if the value falls within the inclusive bounds, or <c>false</c> otherwise.</returns> public bool InRange(T value) { return(Minimum.CompareTo(value) <= 0 && Maximum.CompareTo(value) >= 0); }
public override void CheckConstraints() { DateTime value = (DateTime)ValueDateTime; this._Value = value.ToDBDateTimeFormat(); DateTime min = DateTime.Now; if (string.IsNullOrEmpty(Minimum)) { goto CheckMax; } #region Checking Minimum if (!DateTime.TryParse(Minimum, out min)) { min = DateTime.Now; } if (Minimum.ToUpper().Equals("CURRENTDATETIME+")) { if (value < min) { this._ParseResult = new IdpeMessage(IdpeMessageCodes.IDPE_TYPE_DATA_VALIDATION_FAILED_MINIMUM_DATETIME_SERVER); this._ParseResult.Message = string.Format(this._ParseResult.Message, PrintRowColPosition(), Value, min); } } else if (Minimum.ToUpper().Equals("CURRENTDATETIME-")) { if (value > min) { this._ParseResult = new IdpeMessage(IdpeMessageCodes.IDPE_TYPE_DATA_VALIDATION_FAILED_MAXIMUM_DATETIME_SERVER); this._ParseResult.Message = string.Format(this._ParseResult.Message, PrintRowColPosition(), Value, min); } } else if (Minimum.ToUpper().Equals("CURRENTDATE+")) { DateTime d1 = (DateTime)value.ToShortDateString().ParseDateTime(); DateTime d2 = (DateTime)min.ToShortDateString().ParseDateTime(); if (d1 < d2) { this._ParseResult = new IdpeMessage(IdpeMessageCodes.IDPE_TYPE_DATA_VALIDATION_FAILED_MINIMUM_DATE_SERVER); this._ParseResult.Message = string.Format(this._ParseResult.Message, PrintRowColPosition(), Value, d2); } } else if (Minimum.ToUpper().Equals("CURRENTDATE-")) { DateTime d1 = (DateTime)value.ToShortDateString().ParseDateTime(); DateTime d2 = (DateTime)min.ToShortDateString().ParseDateTime(); if (d1 > d2) { this._ParseResult = new IdpeMessage(IdpeMessageCodes.IDPE_TYPE_DATA_VALIDATION_FAILED_MAXIMUM_DATE_SERVER); this._ParseResult.Message = string.Format(this._ParseResult.Message, PrintRowColPosition(), Value, d2); } } #endregion Checking Minimum CheckMax: if (string.IsNullOrEmpty(Maximum)) { return; //no need to check further } #region Checking Maximum DateTime max = DateTime.Now; if (!DateTime.TryParse(Maximum, out max)) { max = DateTime.Now; } //As we have both Minimum & Maximum, lets try a logical validation //logical validation starts if ((!string.IsNullOrEmpty(Minimum)) && (max <= min)) { throw new Exception(string.Format("Attribute {0} has some invalid configuration. Please check Minimum and Maximum, else contact administrator or read manual for more details.", ColumnName)); } //logical validation ends if (Maximum.ToUpper().Equals("CURRENTDATETIME+")) { if (value < max) { this._ParseResult = new IdpeMessage(IdpeMessageCodes.IDPE_TYPE_DATA_VALIDATION_FAILED_MINIMUM_DATETIME_SERVER); this._ParseResult.Message = string.Format(this._ParseResult.Message, PrintRowColPosition(), Value, max); } } else if (Maximum.ToUpper().Equals("CURRENTDATETIME-")) { if (value > max) { this._ParseResult = new IdpeMessage(IdpeMessageCodes.IDPE_TYPE_DATA_VALIDATION_FAILED_MAXIMUM_DATETIME_SERVER); this._ParseResult.Message = string.Format(this._ParseResult.Message, PrintRowColPosition(), Value, min); } } else if (Maximum.ToUpper().Equals("CURRENTDATE+")) { DateTime d1 = (DateTime)value.ToShortDateString().ParseDateTime(); DateTime d2 = (DateTime)max.ToShortDateString().ParseDateTime(); if (d1 < d2) { this._ParseResult = new IdpeMessage(IdpeMessageCodes.IDPE_TYPE_DATA_VALIDATION_FAILED_MINIMUM_DATE_SERVER); this._ParseResult.Message = string.Format(this._ParseResult.Message, PrintRowColPosition(), Value, d2); } } else if (Maximum.ToUpper().Equals("CURRENTDATE-")) { DateTime d1 = (DateTime)value.ToShortDateString().ParseDateTime(); DateTime d2 = (DateTime)max.ToShortDateString().ParseDateTime(); if (d1 > d2) { this._ParseResult = new IdpeMessage(IdpeMessageCodes.IDPE_TYPE_DATA_VALIDATION_FAILED_MAXIMUM_DATE_SERVER); this._ParseResult.Message = string.Format(this._ParseResult.Message, PrintRowColPosition(), Value, d2); } } #endregion Checking Maximum if (!((value >= min) && (value <= max))) { this._ParseResult = new IdpeMessage(IdpeMessageCodes.IDPE_TYPE_DATA_VALIDATION_FAILED_MINIMUM_MAXIMUM_DATE); this._ParseResult.Message = string.Format(this._ParseResult.Message, PrintRowColPosition(), value, min, max); } }
/// <summary> /// Serves as a hash of this type. /// </summary> /// <returns>A hash code for the current instance.</returns> public override int GetHashCode() => Minimum.GetHashCode() ^ Maximum.GetHashCode();