/** * Constructor. * @param indicator the indicator * @param timeFrame the time frame */ public MeanDeviationIndicator(IIndicator <decimal> indicator, int timeFrame) : base(indicator) { _indicator = indicator; _timeFrame = timeFrame; _sma = new SMAIndicator(indicator, timeFrame); }
/// <param name="series"> a time series </param> /// <returns> a 2-period RSI strategy </returns> public static Strategy BuildStrategy(TimeSeries series) { if (series == null) { throw new ArgumentException("Series cannot be null"); } var closePrice = new ClosePriceIndicator(series); var shortSma = new SMAIndicator(closePrice, 5); var longSma = new SMAIndicator(closePrice, 200); // We use a 2-period RSI indicator to identify buying // or selling opportunities within the bigger trend. var rsi = new RSIIndicator(closePrice, 2); // Entry rule // The long-term trend is up when a security is above its 200-period SMA. var entryRule = (new OverIndicatorRule(shortSma, longSma)).And(new CrossedDownIndicatorRule(rsi, Decimal.ValueOf(5))).And(new OverIndicatorRule(shortSma, closePrice)); // Signal 2 - Signal 1 - Trend // Exit rule // The long-term trend is down when a security is below its 200-period SMA. var exitRule = (new UnderIndicatorRule(shortSma, longSma)).And(new CrossedUpIndicatorRule(rsi, Decimal.ValueOf(95))).And(new UnderIndicatorRule(shortSma, closePrice)); // Signal 2 - Signal 1 - Trend return(new Strategy(entryRule, exitRule)); }
/** * Constructor. * @param indicator the indicator * @param timeFrame the time frame */ public VarianceIndicator(IIndicator <decimal> indicator, int timeFrame) : base(indicator) { _indicator = indicator; _timeFrame = timeFrame; _sma = new SMAIndicator(indicator, timeFrame); }
/** * Constructor. * @param series a time series * @param timeFrame the number of bars used to Calculate the average body height * @param bodyFactor the factor used when checking if a candle is Doji */ public DojiIndicator(ITimeSeries series, int timeFrame, decimal bodyFactor) : base(series) { _bodyHeightInd = new AbsoluteIndicator(new RealBodyIndicator(series)); _averageBodyHeightInd = new SMAIndicator(_bodyHeightInd, timeFrame); _factor = bodyFactor; }
public void BollingerBandWidthUsingSMAAndStandardDeviation() { SMAIndicator sma = new SMAIndicator(closePrice, 5); StandardDeviationIndicator standardDeviation = new StandardDeviationIndicator(closePrice, 5); BollingerBandsMiddleIndicator bbmSMA = new BollingerBandsMiddleIndicator(sma); BollingerBandsUpperIndicator bbuSMA = new BollingerBandsUpperIndicator(bbmSMA, standardDeviation); BollingerBandsLowerIndicator bblSMA = new BollingerBandsLowerIndicator(bbmSMA, standardDeviation); BollingerBandWidthIndicator bandwidth = new BollingerBandWidthIndicator(bbuSMA, bbmSMA, bblSMA); Assert.AreEqual(bandwidth.GetValue(0), 0.0M); Assert.AreEqual(bandwidth.GetValue(1), 36.363636363636363636363636360M); Assert.AreEqual(bandwidth.GetValue(2), 66.642313545610556218920998730M); Assert.AreEqual(bandwidth.GetValue(3), 60.244280375440064123683819780M); Assert.AreEqual(bandwidth.GetValue(4), 71.076741021144541578134348630M); Assert.AreEqual(bandwidth.GetValue(5), 69.939393317876184065428705400M); Assert.AreEqual(bandwidth.GetValue(6), 62.704283664302785713832632430M); Assert.AreEqual(bandwidth.GetValue(7), 56.017820550978806498453596730M); Assert.AreEqual(bandwidth.GetValue(8), 27.682979522960278118630842150M); Assert.AreEqual(bandwidth.GetValue(9), 12.649110640673517327995574180M); Assert.AreEqual(bandwidth.GetValue(10), 12.649110640673517327995574180M); Assert.AreEqual(bandwidth.GetValue(11), 24.295632895188751961975636990M); Assert.AreEqual(bandwidth.GetValue(12), 68.333165356240492140358775280M); Assert.AreEqual(bandwidth.GetValue(13), 85.14693182963200583066660912M); Assert.AreEqual(bandwidth.GetValue(14), 112.84810090360856581393406310M); Assert.AreEqual(bandwidth.GetValue(15), 108.16818718178015127023901017M); Assert.AreEqual(bandwidth.GetValue(16), 66.932802122726043838253762060M); Assert.AreEqual(bandwidth.GetValue(17), 56.519416526043901158871302720M); Assert.AreEqual(bandwidth.GetValue(18), 28.109134757052260728879053730M); Assert.AreEqual(bandwidth.GetValue(19), 32.536151189338620744206510720M); }
public void getValueWithCacheLengthIncrease() { decimal[] data = new decimal[200]; Arrays.fill(data, 10); SMAIndicator sma = new SMAIndicator(new ClosePriceIndicator(new MockTimeSeries(data)), 100); Assert.AreEqual(sma.GetValue(105), 10); }
public void ifCacheWorks() { SMAIndicator sma = new SMAIndicator(new ClosePriceIndicator(series), 3); decimal firstTime = sma.GetValue(4); decimal secondTime = sma.GetValue(4); Assert.AreEqual(firstTime, secondTime); }
/** * Constructor. * @param ref the indicator * @param timeFrame the time frame */ public SigmaIndicator(IIndicator <decimal> indicator, int timeFrame) : base(indicator) { _indicator = indicator; _timeFrame = timeFrame; _mean = new SMAIndicator(indicator, timeFrame); _sd = new StandardDeviationIndicator(indicator, timeFrame); }
/** * Constructor. * @param series a time series * @param timeFrame the number of bars used to Calculate the average upper shadow * @param factor the factor used when checking if a candle has a very short upper shadow */ public ThreeWhiteSoldiersIndicator(ITimeSeries series, int timeFrame, decimal factor) : base(series) { _series = series; _upperShadowInd = new UpperShadowIndicator(series); _averageUpperShadowInd = new SMAIndicator(_upperShadowInd, timeFrame); _factor = factor; }
public void setUp() { ITimeSeries data = new MockTimeSeries(1, 2, 3, 4, 3, 4, 5, 4, 3, 3, 4, 3, 2); timeFrame = 3; closePrice = new ClosePriceIndicator(data); sma = new SMAIndicator(closePrice, timeFrame); }
/** * Constructor. * @param series a time series * @param timeFrame the number of bars used to Calculate the average lower shadow * @param factor the factor used when checking if a candle has a very short lower shadow */ public ThreeBlackCrowsIndicator(ITimeSeries series, int timeFrame, decimal factor) : base(series) { _series = series; _lowerShadowInd = new LowerShadowIndicator(series); _averageLowerShadowInd = new SMAIndicator(_lowerShadowInd, timeFrame); _factor = factor; }
/** * Constructor. * @param indicator1 the first indicator * @param indicator2 the second indicator * @param timeFrame the time frame */ public CovarianceIndicator(IIndicator <decimal> indicator1, IIndicator <decimal> indicator2, int timeFrame) : base(indicator1) { _indicator1 = indicator1; _indicator2 = indicator2; _timeFrame = timeFrame; _sma1 = new SMAIndicator(indicator1, timeFrame); _sma2 = new SMAIndicator(indicator2, timeFrame); }
public void TimeSeries() { ClosePriceIndicator cp = new ClosePriceIndicator(series); Assert.AreEqual(series, cp.TimeSeries); SMAIndicator sma = new SMAIndicator(cp, 3); Assert.AreEqual(series, sma.TimeSeries); }
public void stochasticOscilatorDParam14UsingSMA3AndGenericConstructer() { StochasticOscillatorKIndicator sof = new StochasticOscillatorKIndicator(data, 14); SMAIndicator sma = new SMAIndicator(sof, 3); StochasticOscillatorDIndicator sos = new StochasticOscillatorDIndicator(sma); Assert.AreEqual(sma.GetValue(0), sos.GetValue(0)); Assert.AreEqual(sma.GetValue(1), sos.GetValue(1)); Assert.AreEqual(sma.GetValue(2), sos.GetValue(2)); }
public void valuesLessThanTimeFrameMustBeEqualsToSMAValues() { ZLEMAIndicator zlema = new ZLEMAIndicator(new ClosePriceIndicator(data), 10); SMAIndicator sma = new SMAIndicator(new ClosePriceIndicator(data), 10); for (int i = 0; i < 9; i++) { Assert.AreEqual(sma.GetValue(i), zlema.GetValue(i)); } }
public void bollingerBandsMiddleUsingSMA() { SMAIndicator sma = new SMAIndicator(new ClosePriceIndicator(data), 3); BollingerBandsMiddleIndicator bbmSMA = new BollingerBandsMiddleIndicator(sma); for (int i = 0; i < data.GetBarCount(); i++) { Assert.AreEqual(sma.GetValue(i), bbmSMA.GetValue(i)); } }
public void getValueWithOldResultsRemoval() { decimal[] data = new decimal[20]; Arrays.fill(data, 1); ITimeSeries timeSeries = new MockTimeSeries(data); SMAIndicator sma = new SMAIndicator(new ClosePriceIndicator(timeSeries), 10); Assert.AreEqual(sma.GetValue(5), 1); Assert.AreEqual(sma.GetValue(10), 1); timeSeries.SetMaximumBarCount(12); Assert.AreEqual(sma.GetValue(19), 1); }
public void TestAverageValidity() { var test = new[] { 1M, 2M, 3M, 4M, 5M, 6M, 7M, 8M, 9M, 10M }; var expected = new[] { 0M, 1.5M, 2.5M, 3.5M, 4.5M, 5.5M, 6.5M, 7.5M, 8.5M, 9.5M }; var target = new SMAIndicator(2); for (int i = 0; i < test.Length; i++) { target.Add(test[i]); Assert.AreEqual(expected[i], target.PeekLast()); } }
public void TestInitialization() { var target = new SMAIndicator(3); target.Add(1); Assert.False(target.IsInitialized); target.Add(2); Assert.False(target.IsInitialized); target.Add(3); Assert.True(target.IsInitialized); target.Add(4); Assert.True(target.IsInitialized); }
public void onlineExampleTest() { // throws exception // from http://cns.bu.edu/~gsc/CN710/fincast/Technical%20_indicators/Relative%20Strength%20Index%20(RSI).htm // which uses a different calculation of RSI than ta4j ITimeSeries series = new MockTimeSeries( 46.1250M, 47.1250M, 46.4375M, 46.9375M, 44.9375M, 44.2500M, 44.6250M, 45.7500M, 47.8125M, 47.5625M, 47.0000M, 44.5625M, 46.3125M, 47.6875M, 46.6875M, 45.6875M, 43.0625M, 43.5625M, 44.8750M, 43.6875M); // ta4j RSI uses MMA for average gain and loss // then uses simple division of the two for RS IIndicator <decimal> indicator = getIndicator(new ClosePriceIndicator( series), 14); IIndicator <decimal> close = new ClosePriceIndicator(series); IIndicator <decimal> gain = new GainIndicator(close); IIndicator <decimal> loss = new LossIndicator(close); // this site uses SMA for average gain and loss // then uses ratio of MMAs for RS (except for first calculation) IIndicator <decimal> avgGain = new SMAIndicator(gain, 14); IIndicator <decimal> avgLoss = new SMAIndicator(loss, 14); // first online calculation is simple division decimal onlineRs = avgGain.GetValue(14).DividedBy(avgLoss.GetValue(14)); Assert.AreEqual(0.5848214285714285714285714286M, avgGain.GetValue(14)); Assert.AreEqual(0.5446428571428571428571428571M, avgLoss.GetValue(14)); Assert.AreEqual(1.0737704918032786885245901641M, onlineRs); decimal onlineRsi = 100M - (100M / (1M + onlineRs)); // difference in RSI values: Assert.AreEqual(51.778656126482213438735177869M, onlineRsi); Assert.AreEqual(52.130477585417047385335308781M, indicator.GetValue(14)); // strange, online average gain and loss is not a simple moving average! // but they only use them for the first RS calculation // Assert.AreEqual(0.5430, avgGain.getValue(15)); // Assert.AreEqual(0.5772, avgLoss.getValue(15)); // second online calculation uses MMAs // MMA of average gain decimal dividend = avgGain.GetValue(14).MultipliedBy(13M).Plus(gain.GetValue(15)).DividedBy(14M); // MMA of average loss decimal divisor = avgLoss.GetValue(14).MultipliedBy(13M).Plus(loss.GetValue(15)).DividedBy(14M); onlineRs = dividend / divisor; Assert.AreEqual(0.940883977900552486187845304M, onlineRs); onlineRsi = 100M - (100M / (1M + onlineRs)); // difference in RSI values: Assert.AreEqual(48.477085112439510389980074014M, onlineRsi); Assert.AreEqual(47.37103140045740279363506511M, indicator.GetValue(15)); }
public void getValueOnResultsCalculatedFromRemovedBarsShouldReturnFirstRemainingResult() { ITimeSeries timeSeries = new MockTimeSeries(1, 1, 1, 1, 1); timeSeries.SetMaximumBarCount(3); Assert.AreEqual(2, timeSeries.GetRemovedBarsCount()); SMAIndicator sma = new SMAIndicator(new ClosePriceIndicator(timeSeries), 2); for (int i = 0; i < 5; i++) { Assert.AreEqual(1, sma.GetValue(i), $"failed for {i}"); } }
public void getValueWithNullTimeSeries() { ConstantIndicator <decimal> constant = new ConstantIndicator <decimal>(Decimals.TEN); Assert.AreEqual(Decimals.TEN, constant.GetValue(0)); Assert.AreEqual(Decimals.TEN, constant.GetValue(100)); Assert.IsNull(constant.TimeSeries); SMAIndicator sma = new SMAIndicator(constant, 10); Assert.AreEqual(Decimals.TEN, sma.GetValue(0)); Assert.AreEqual(Decimals.TEN, sma.GetValue(100)); Assert.IsNull(sma.TimeSeries); }
public void dpo() { DPOIndicator dpo = new DPOIndicator(series, 9); ClosePriceIndicator cp = new ClosePriceIndicator(series); SMAIndicator sma = new SMAIndicator(cp, 9); int timeShift = 9 / 2 + 1; for (int i = series.GetBeginIndex(); i <= series.GetEndIndex(); i++) { Assert.AreEqual(dpo.GetValue(i), cp.GetValue(i).Minus(sma.GetValue(i - timeShift))); } Assert.AreEqual(dpo.GetValue(9), 0.112M); Assert.AreEqual(dpo.GetValue(10), -0.02M); Assert.AreEqual(dpo.GetValue(11), 0.211428571428571428571428571M); Assert.AreEqual(dpo.GetValue(12), 0.17M); }
/// <param name="series"> a time series </param> /// <returns> a dummy strategy </returns> private static Strategy buildStrategy(TimeSeries series) { if (series == null) { throw new System.ArgumentException("Series cannot be null"); } ClosePriceIndicator closePrice = new ClosePriceIndicator(series); SMAIndicator sma = new SMAIndicator(closePrice, 12); // Signals // Buy when SMA goes over close price // Sell when close price goes over SMA Strategy buySellSignals = new Strategy(new OverIndicatorRule(sma, closePrice), new UnderIndicatorRule(sma, closePrice) ); return(buySellSignals); }
/// <summary> /// Initialization method /// </summary> public override void OnInitialize() { log.Debug("AryaStrategy onInitialize()"); // Adding a Stochastic indicator to strategy // (see http://stockcharts.com/help/doku.php?id=chart_school:technical_indicators:stochastic_oscillato) stochasticIndicator = new StochasticIndicator(Bars.Bars, (int)this.GetInputParameter("Stochastic Period")); this.AddIndicator("Stochastic Indicator", stochasticIndicator); // Adding an ADX indicator to strategy // (see http://www.investopedia.com/terms/a/adx.asp) adxIndicator = new ADXIndicator(Bars.Bars, (int)this.GetInputParameter("ADX Period")); this.AddIndicator("ADX Indicator", adxIndicator); // Adding a SMA indicator to strategy // (see http://www.investopedia.com/terms/s/sma.asp) smaIndicator = new SMAIndicator(Bars.Close, (int)this.GetInputParameter("SMA Period")); this.AddIndicator("SMA Indicator", smaIndicator); }
public void strategyExecutionOnCachedIndicatorAndLimitedTimeSeries() { ITimeSeries timeSeries = new MockTimeSeries(0, 1, 2, 3, 4, 5, 6, 7); SMAIndicator sma = new SMAIndicator(new ClosePriceIndicator(timeSeries), 2); // Theoretical values for SMA(2) cache: 0, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5 timeSeries.SetMaximumBarCount(6); // Theoretical values for SMA(2) cache: null, null, 2, 2.5, 3.5, 4.5, 5.5, 6.5 IStrategy strategy = new BaseStrategy( new OverIndicatorRule(sma, Decimals.THREE), new UnderIndicatorRule(sma, Decimals.THREE) ); // Theoretical shouldEnter results: false, false, false, false, true, true, true, true // Theoretical shouldExit results: false, false, true, true, false, false, false, false // As we return the first bar/result found for the removed bars: // -> Approximated values for ClosePrice cache: 2, 2, 2, 3, 4, 5, 6, 7 // -> Approximated values for SMA(2) cache: 2, 2, 2, 2.5, 3.5, 4.5, 5.5, 6.5 // Then enters/exits are also approximated: // -> shouldEnter results: false, false, false, false, true, true, true, true // -> shouldExit results: true, true, true, true, false, false, false, false Assert.IsFalse(strategy.ShouldEnter(0)); Assert.IsTrue(strategy.ShouldExit(0)); Assert.IsFalse(strategy.ShouldEnter(1)); Assert.IsTrue(strategy.ShouldExit(1)); Assert.IsFalse(strategy.ShouldEnter(2)); Assert.IsTrue(strategy.ShouldExit(2)); Assert.IsFalse(strategy.ShouldEnter(3)); Assert.IsTrue(strategy.ShouldExit(3)); Assert.IsTrue(strategy.ShouldEnter(4)); Assert.IsFalse(strategy.ShouldExit(4)); Assert.IsTrue(strategy.ShouldEnter(5)); Assert.IsFalse(strategy.ShouldExit(5)); Assert.IsTrue(strategy.ShouldEnter(6)); Assert.IsFalse(strategy.ShouldExit(6)); Assert.IsTrue(strategy.ShouldEnter(7)); Assert.IsFalse(strategy.ShouldExit(7)); }
public void TestTheSameData() { var test = new[] { 5M, 5M, 5M, 5M, 5M, 5M, 5M, 5M, 5M, 5M }; for (int i = 1; i < test.Length; i++) { var target = new SMAIndicator((uint)i); foreach (var item in test) { target.Add(item); if (target.IsInitialized) { Assert.AreEqual(5M, target.PeekLast()); } else { Assert.AreEqual(0M, target.PeekLast()); } } } }
/// <summary> /// Initialization method /// </summary> public override void OnInitialize() { log.Debug("AryaStrategy onInitialize()"); // Adding a Stochastic indicator to strategy // (see http://stockcharts.com/help/doku.php?id=chart_school:technical_indicators:stochastic_oscillato) stochasticIndicator = new StochasticIndicator(Bars.Bars, (int)this.GetInputParameter("Stochastic Period")); this.AddIndicator("Stochastic Indicator", stochasticIndicator); // Adding an ADX indicator to strategy // (see http://www.investopedia.com/terms/a/adx.asp) adxIndicator = new ADXIndicator(Bars.Bars, (int)this.GetInputParameter("ADX Period")); this.AddIndicator("ADX Indicator", adxIndicator); // Adding a SMA indicator to strategy // (see http://www.investopedia.com/terms/s/sma.asp) smaIndicator = new SMAIndicator(Bars.Close, (int)this.GetInputParameter("SMA Period")); this.AddIndicator("SMA Indicator", smaIndicator); }
public static void Main(string[] args) { /// <summary> /// Getting time series /// </summary> TimeSeries series = CsvTradesLoader.loadBitstampSeries(); /// <summary> /// Creating indicators /// </summary> // Close price ClosePriceIndicator closePrice = new ClosePriceIndicator(series); // Typical price TypicalPriceIndicator typicalPrice = new TypicalPriceIndicator(series); // Price variation PriceVariationIndicator priceVariation = new PriceVariationIndicator(series); // Simple moving averages SMAIndicator shortSma = new SMAIndicator(closePrice, 8); SMAIndicator longSma = new SMAIndicator(closePrice, 20); // Exponential moving averages EMAIndicator shortEma = new EMAIndicator(closePrice, 8); EMAIndicator longEma = new EMAIndicator(closePrice, 20); // Percentage price oscillator PPOIndicator ppo = new PPOIndicator(closePrice, 12, 26); // Rate of change ROCIndicator roc = new ROCIndicator(closePrice, 100); // Relative strength index RSIIndicator rsi = new RSIIndicator(closePrice, 14); // Williams %R WilliamsRIndicator williamsR = new WilliamsRIndicator(series, 20); // Average true range AverageTrueRangeIndicator atr = new AverageTrueRangeIndicator(series, 20); // Standard deviation StandardDeviationIndicator sd = new StandardDeviationIndicator(closePrice, 14); /// <summary> /// Building header /// </summary> StringBuilder sb = new StringBuilder("timestamp,close,typical,variation,sma8,sma20,ema8,ema20,ppo,roc,rsi,williamsr,atr,sd\n"); /// <summary> /// Adding indicators values /// </summary> //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int nbTicks = series.getTickCount(); int nbTicks = series.TickCount; for (int i = 0; i < nbTicks; i++) { sb.Append(series.getTick(i).EndTime.Millis / 1000d).Append(',').Append(closePrice.getValue(i)).Append(',').Append(typicalPrice.getValue(i)).Append(',').Append(priceVariation.getValue(i)).Append(',').Append(shortSma.getValue(i)).Append(',').Append(longSma.getValue(i)).Append(',').Append(shortEma.getValue(i)).Append(',').Append(longEma.getValue(i)).Append(',').Append(ppo.getValue(i)).Append(',').Append(roc.getValue(i)).Append(',').Append(rsi.getValue(i)).Append(',').Append(williamsR.getValue(i)).Append(',').Append(atr.getValue(i)).Append(',').Append(sd.getValue(i)).Append('\n'); } /// <summary> /// Writing CSV file /// </summary> System.IO.StreamWriter writer = null; try { writer = new System.IO.StreamWriter("indicators.csv"); writer.Write(sb.ToString()); } catch (IOException ioe) { //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: Logger.getLogger(typeof(IndicatorsToCsv).FullName).log(Level.SEVERE, "Unable to write CSV file", ioe); } finally { try { if (writer != null) { writer.Close(); } } catch (IOException) { } } }