Example #1
0
        public override void PopulateExtendedIndicators(Entity.Indicator[] indArray)
        {
            double[]  close         = new double[indArray.Length];
            double?[] rsiOutput     = new double?[indArray.Length];
            double?[] rsiOutput_Acc = new double?[indArray.Length];
            for (int i = 0; i < indArray.Length; i++)
            {
                if (indArray[i].Close.HasValue)
                {
                    close[i] = indArray[i].Close.Value;
                }
                else
                {
                    close[i] = 0;
                }
            }

            RSI.Calculate(close, 2, rsiOutput);

            GenericHelper.GetAccumulate(rsiOutput, 2, 2, rsiOutput_Acc);

            for (int i = 0; i < indArray.Length; i++)
            {
                indArray[i].ExtendedIndicators = new Dictionary <string, double?>();

                indArray[i].ExtendedIndicators.Add("RSI2", rsiOutput[i]);
                indArray[i].ExtendedIndicators.Add("RSI2ACC", rsiOutput_Acc[i]);
            }
        }
Example #2
0
        public override bool OnExecution()
        {
            BinanceConnectorNode binanceConnector = this.InParameters["connection"].GetValue() as BinanceConnectorNode;
            var result = binanceConnector.Client.FuturesUsdt.Market.GetKlines(this.InParameters["symbol"].GetValue().ToString(), global::Binance.Net.Enums.KlineInterval.OneHour);

            RSI         rsi      = new RSI(30);
            List <Ohlc> ohlcList = new List <Ohlc>();

            foreach (var candle in result.Data)
            {
                ohlcList.Add(new Ohlc()
                {
                    Date     = candle.CloseTime,
                    Open     = (double)candle.Open,
                    High     = (double)candle.High,
                    Low      = (double)candle.Low,
                    Close    = (double)candle.Close,
                    Volume   = (double)candle.QuoteVolume,
                    AdjClose = 1
                });
            }
            rsi.Load(ohlcList);
            var serie = rsi.Calculate();

            this.OutParameters["RSI"].SetValue(serie.RSI.LastOrDefault());
            return(true);
        }
Example #3
0
        public void Less_Data_Then_Periods_Results_CollectionData_And_Empty_Current_Values(decimal[] input,
                                                                                           int numberOfPeriods)
        {
            RSI rsi = new RSI(numberOfPeriods);

            rsi.Calculate(input.AsTradesWitRates());

            Assert.True(rsi.CollectingData);
            Assert.Empty(rsi.Values);
        }
        public void RSI()
        {
            RSI rsi = new RSI(14);

            rsi.Load(Directory.GetCurrentDirectory() + "\\table.csv");
            RSISerie serie = rsi.Calculate();

            Assert.NotNull(serie);
            Assert.True(serie.RS.Count > 0);
            Assert.True(serie.RSI.Count > 0);
        }
Example #5
0
        private static RSISerie GetRsiSeries(RSI rsi, string stockName)
        {
            string downloadFolderName = ConfigurationManager.AppSettings["downloadLocation"];

            rsi.Load(downloadFolderName + stockName + ".ax.csv");

            RSISerie serie = rsi.Calculate();

            //ExcelUtilities.WriteMacdhistogramDataToExcel(serie, stockName);
            return(serie);
        }
Example #6
0
        public void RSI()
        {
            RSI rsi = new RSI(14);

            rsi.Load(OhlcList);
            RSISerie serie = rsi.Calculate();

            Assert.IsNotNull(serie);
            Assert.IsTrue(serie.RS.Count > 0);
            Assert.IsTrue(serie.RSI.Count > 0);
        }
Example #7
0
        public void RSI()
        {
            RSI rsi = new RSI(14);

            rsi.Load(Directory.GetCurrentDirectory() + "\\vas.csv");
            RSISerie serie = rsi.Calculate();

            Assert.IsNotNull(serie);
            //Assert.IsTrue(serie.rsiDataPoint.RS.Count > 0);
            //Assert.IsTrue(serie.rsiDataPoint.RSI.Count > 0);
        }
        public void RSI()
        {
            RSI rsi = new RSI(14);

            rsi.Load(csvPath);
            RSISerie serie = rsi.Calculate();

            Assert.NotNull(serie);
            Assert.True(serie.RS.Count > 0);
            Assert.True(serie.RSI.Count > 0);
        }
Example #9
0
        public void Calculate_Success_On_UpperTrend()
        {
            var periods     = 2;
            var inputStream = new decimal[4] {
                1, 2, 3, 4
            };
            var trades = inputStream.AsTradesWitRates();

            RSI rsi = new RSI(periods);

            for (var i = 0; i < trades.Length - periods; i++)
            {
                rsi.Calculate(trades.Slice(i, periods + 1));
            }
        }
Example #10
0
        public void TestCalculate()
        {
            double[] close = new double[] {
                44.34, 44.09, 44.15, 43.61, 44.33,
                44.83, 45.10, 45.42, 45.84, 46.08,
                45.89, 46.03, 45.61, 46.28, 46.28,
                46.00, 46.03, 46.41, 46.22, 45.64,
                46.21, 46.25, 45.71, 46.45, 45.78,
                45.35, 44.03, 44.18, 44.22, 44.57,
                43.42, 42.66, 43.13
            };

            double?[] outRSI = new double?[close.Length];

            RSI.Calculate(close, 14, outRSI);
        }
Example #11
0
        public void TestRSI()
        {
            double[] close = new double[] {
                44.34, 44.09, 44.15, 43.61, 44.33,
                44.83, 45.10, 45.42, 45.84, 46.08,
                45.89, 46.03, 45.61, 46.28, 46.28,
                46.00, 46.03, 46.41, 46.22, 45.64,
                46.21, 46.25, 45.71, 46.45, 45.78,
                45.35, 44.03, 44.18, 44.22, 44.57,
                43.42, 42.66, 43.13
            };

            double?[] outRSI = new double?[close.Length];

            RSI.Calculate(close, 14, outRSI);

            Console.WriteLine(ObjectHelper.ToJson(outRSI));
        }
Example #12
0
        public void Execute(Span <Trade> trades)
        {
            _rsi.Calculate(trades.Slice(0, _rsi._periods));

            if (_rsi.CollectingData)
            {
                return;
            }

            if (_rsi.Current.RSI > _overbought)
            {
                BuySignal();
            }
            else if (_rsi.Current.RSI < _oversold)
            {
                SellSignal();
            }
        }
Example #13
0
        public void TestCalculateRealData()
        {
            TickerBLL tbll = new TickerBLL(_unit);

            List <Ticker> tList = tbll.GetTickerListByShareDB(1585, null, 21100000);

            double[]  inputData = new double[tList.Count];
            double?[] outData   = new double?[tList.Count];

            var i = 0;

            foreach (var t in tList)
            {
                inputData[i] = t.Close;
                i++;
            }

            Result res = RSI.Calculate(inputData, 14, outData);
        }
Example #14
0
        public void Calculate_Success(decimal[] inputStream, int periods)
        {
            RSI rsi    = new RSI(periods);
            var trades = inputStream.AsTradesWitRates();

            for (var i = 0; i < trades.Length - periods; i++)
            {
                rsi.Calculate(trades.Slice(i, periods + 1));
            }

            Assert.False(rsi.CollectingData);

            RSI_INDEX firstIndexFromAvarage = new RSI_INDEX
            {
                AvgGain = 0.2384m,
                AvgLoss = 0.0996m,
                RS      = 2.3936m,
                RSI     = 70.5328m
            };

            RSI_INDEX secondCalculated = new RSI_INDEX
            {
                AvgGain = 0.2214m,
                AvgLoss = 0.1124m,
                RS      = 1.9690m,
                RSI     = 66.3186m
            };

            RSI_INDEX thirdCalculated = new RSI_INDEX
            {
                AvgGain = 0.2077m,
                AvgLoss = 0.1044m,
                RS      = 1.9895m,
                RSI     = 66.5498m
            };

            Assert.Equal(firstIndexFromAvarage, rsi.Values.ElementAt(rsi.Values.Count() - 1),
                         RSI_INDEX_Equality.Create(4));
            Assert.Equal(secondCalculated, rsi.Values.ElementAt(rsi.Values.Count() - 2), RSI_INDEX_Equality.Create(4));
            Assert.Equal(thirdCalculated, rsi.Values.ElementAt(rsi.Values.Count() - 3), RSI_INDEX_Equality.Create(4));
        }
        public async Task<IndSingleValueEntity[]> GetRSI(string code, int period = 14, int? start = 0, int? end = 0, string type = "day")
        {
            TickerEntity[] tickers = await base.getTickerEntityArray(code, start, end, type);
            List<IndSingleValueEntity> outList = new List<IndSingleValueEntity>();

            int len = tickers.Length;

            double[] close = tickers.Select(t => (double)t.C).ToArray();
            double?[] outRSI = new double?[len];

            RSI.Calculate(close, period, outRSI);

            for (int i = 0; i < len; i++)
            {
                outList.Add(new IndSingleValueEntity
                {
                    T = tickers[i].T,
                    P = tickers[i].P,
                    V = outRSI[i]
                });
            }

            return outList.Where(r => (start == 0 || r.P >= start) && (end == 0 || r.P <= end)).ToArray();
        }
    public StockPriceReaderModel ParsePrices(string file)
    {
        var stockPriceReaderModel = new StockPriceReaderModel();

        List <string>          row = new List <string>();
        List <StockPriceModel> s   = new List <StockPriceModel>();

        stockPriceReaderModel.name = "Stock: " + System.IO.Path.GetFileNameWithoutExtension(file);
        using (var reader = new CsvFileReader(file))
        {
            while (reader.ReadRow(row))
            {
                //Ignore premarket and aftermarket trading eg. before 0930AM and after 0400PM
                int time = int.Parse(row[1]);
                if (time >= 930 && time <= 1600)
                {
                    float open   = float.Parse(row[2]);
                    float high   = float.Parse(row[3]);
                    float low    = float.Parse(row[4]);
                    float close  = float.Parse(row[5]);
                    float volume = float.Parse(row[6]);

                    var stockPriceModel = new StockPriceModel(open, close, high, low, volume);
                    stockPriceReaderModel.prices.Add(stockPriceModel);
                }
            }
        }

        RSI.Calculate(stockPriceReaderModel.prices);
        SMA.Calculate(stockPriceReaderModel.prices);

        //identify and name patterns
        MyStrategy.Apply(stockPriceReaderModel.prices);

        return(stockPriceReaderModel);
    }
Example #17
0
        public Form1()
        {
            InitializeComponent();
            chart1.Series.Clear();
            Int32 timeStampStart = (Int32)(DateTime.UtcNow.AddMonths(-12).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            Int32 timeStampNow   = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            String yahooAPI = $"https://query1.finance.yahoo.com/v7/finance/download/BTC-EUR?period1={timeStampStart}&period2={timeStampNow}&interval=1d&events=history";

            using (var client = new WebClient())
            {
                client.DownloadFile(yahooAPI, "fileLOG");
            }

            String       csvFile  = @"fileLOG";
            List <Ohlc>  ohlcList = new List <Ohlc>();
            StreamReader r        = new StreamReader(csvFile);
            String       file     = r.ReadToEnd();

            String[] pricesClose = file.Split(new String[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            chart1.Series.Add("Price").ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastPoint;
            // chart1.Series["Price"].Color = Color.Black;
            int             j     = 0;
            List <DateTime> dates = new List <DateTime>();

            foreach (var s in pricesClose)
            {
                String[] pricesOscillation = s.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    int      index    = 0;
                    DateTime date     = DateTime.Parse(pricesOscillation[index++]);
                    double   open     = double.Parse(pricesOscillation[index++]);
                    double   high     = double.Parse(pricesOscillation[index++]);
                    double   low      = double.Parse(pricesOscillation[index++]);
                    double   close    = double.Parse(pricesOscillation[index++]);
                    double   adjClose = double.Parse(pricesOscillation[index++]);
                    double   volume   = double.Parse(pricesOscillation[index++]);

                    Ohlc newOhlc = new Ohlc();
                    newOhlc.Open     = open;
                    newOhlc.High     = high;
                    newOhlc.Low      = low;
                    newOhlc.Close    = close;
                    newOhlc.AdjClose = adjClose;
                    newOhlc.Volume   = volume;

                    ohlcList.Add(newOhlc);

                    dates.Add(date);
                    chart1.Series["Price"].Points.AddXY(date, close);
                }
                catch (Exception err)
                {
                }
            }


            BollingerBand bollingerBand = new BollingerBand();

            bollingerBand.Load(ohlcList);
            BollingerBandSerie serie = bollingerBand.Calculate();

            MACD macd = new MACD();

            macd.Load(ohlcList);
            MACDSerie macdserie = macd.Calculate();

            EMA ema = new EMA();

            ema.Load(ohlcList);
            SingleDoubleSerie singleDoubleSerie = ema.Calculate();


            RSI rsi = new RSI(14);

            rsi.Load(ohlcList);
            RSISerie serieRSI = rsi.Calculate();

            chart1.Series.Add("bUP").ChartType           = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            chart1.Series.Add("bDOWN").ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            chart1.Series.Add("bMIDDLE").ChartType       = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            chart1.Series.Add("RSI").ChartType           = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            chart1.Series.Add("EMA").ChartType           = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            chart1.Series.Add("MACD").ChartType          = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            chart1.Series.Add("MACDHistogram").ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;

            for (int i = 0; i < serie.BandWidth.Count; i++)
            {
                if (macdserie.MACDLine[i] != null)
                {
                    chart1.Series["MACD"].Points.AddXY(dates[i], macdserie.MACDLine[i]);
                }

                if (macdserie.MACDHistogram[i] != null)
                {
                    chart1.Series["MACDHistogram"].Points.AddXY(dates[i], macdserie.MACDHistogram[i]);
                }

                if (singleDoubleSerie.Values[i] != null)
                {
                    chart1.Series["EMA"].Points.AddXY(dates[i], singleDoubleSerie.Values[i]);
                }

                if (serie.UpperBand[i] != null)
                {
                    chart1.Series["bUP"].Points.AddXY(dates[i], serie.UpperBand[i]);
                }

                if (serie.MidBand[i] != null)
                {
                    chart1.Series["bMIDDLE"].Points.AddXY(dates[i], serie.MidBand[i]);
                }

                if (serie.LowerBand[i] != null)
                {
                    chart1.Series["bDOWN"].Points.AddXY(dates[i], serie.LowerBand[i]);
                }

                if (serieRSI.RSI[i] != null)
                {
                    chart1.Series["RSI"].Points.AddXY(dates[i], serieRSI.RSI[i]);
                }
            }
        }
        public void RSIWithHardCodedValues()
        {
            RSI         rsi      = new RSI(14);
            List <Ohlc> ohlcList = new List <Ohlc>
            {
                new Ohlc {
                    Close = 44.34
                },
                new Ohlc {
                    Close = 44.09
                },
                new Ohlc {
                    Close = 44.15
                },
                new Ohlc {
                    Close = 43.61
                },
                new Ohlc {
                    Close = 44.33
                },
                new Ohlc {
                    Close = 44.83
                },
                new Ohlc {
                    Close = 45.10
                },
                new Ohlc {
                    Close = 45.42
                },
                new Ohlc {
                    Close = 45.84
                },
                new Ohlc {
                    Close = 46.08
                },
                new Ohlc {
                    Close = 45.89
                },
                new Ohlc {
                    Close = 46.03
                },
                new Ohlc {
                    Close = 45.61
                },
                new Ohlc {
                    Close = 46.28
                },
                new Ohlc {
                    Close = 46.28
                },
                new Ohlc {
                    Close = 46.00
                },
                new Ohlc {
                    Close = 46.03
                },
                new Ohlc {
                    Close = 46.41
                },
                new Ohlc {
                    Close = 46.22
                },
                new Ohlc {
                    Close = 45.64
                }
            };

            rsi.Load(ohlcList);
            RSISerie serie = rsi.Calculate();

            Assert.NotNull(serie);

            Assert.True(serie.RS.Count > 0);

            Assert.True(Math.Round(serie.RS[14].Value, 2) == 2.39);
            Assert.True(Math.Round(serie.RS[15].Value, 2) == 1.96);
            Assert.True(Math.Round(serie.RS[16].Value, 2) == 1.98);
            Assert.True(Math.Round(serie.RS[17].Value, 2) == 2.26);
            Assert.True(Math.Round(serie.RS[18].Value, 2) == 1.97);
            Assert.True(Math.Round(serie.RS[19].Value, 2) == 1.38);

            Assert.True(serie.RSI.Count > 0);

            Assert.True(Math.Round(serie.RSI[14].Value, 2) == 70.46);
            Assert.True(Math.Round(serie.RSI[15].Value, 2) == 66.25);
            Assert.True(Math.Round(serie.RSI[16].Value, 2) == 66.48);
            Assert.True(Math.Round(serie.RSI[17].Value, 2) == 69.35);
            Assert.True(Math.Round(serie.RSI[18].Value, 2) == 66.29);
            Assert.True(Math.Round(serie.RSI[19].Value, 2) == 57.92);
        }
        public override List <IndicatorResult> Calculate(IIndicatorEntity indicator, List <QuotesModel> quotes)
        {
            Validate(indicator, quotes);

            return(_calculator.Calculate(quotes, ExtractPeriod(indicator)));
        }
Example #20
0
        public override void Calculate(IDataSet dataSet)
        {
            DataSet = dataSet;

            // Reading the parameters
            var basePrice       = (BasePrice)IndParam.ListParam[2].Index;
            var referencePeriod = (int)IndParam.NumParam[1].Value;
            int previous        = IndParam.CheckParam[0].Checked ? 1 : 0;

            // Calculation

            // ---------------------------------------------------------
            var rsi = new RSI();

            rsi.Initialize(SlotType);
            rsi.IndParam.ListParam[1].Index    = IndParam.ListParam[1].Index;
            rsi.IndParam.ListParam[2].Index    = IndParam.ListParam[2].Index;
            rsi.IndParam.NumParam[0].Value     = IndParam.NumParam[0].Value;
            rsi.IndParam.CheckParam[0].Checked = IndParam.CheckParam[0].Checked;
            rsi.Calculate(DataSet);

            double[] indicatorMa = MovingAverage(referencePeriod, previous, MAMethod.Simple, rsi.Component[0].Value);
            double[] marketMa    = MovingAverage(referencePeriod, previous, MAMethod.Simple, Price(basePrice));
            // ----------------------------------------------------------

            int firstBar = rsi.Component[0].FirstBar + referencePeriod + 2;
            var cd       = new double[Bars];

            if (IndParam.ListParam[0].Text == "Convergence")
            {
                for (int bar = firstBar; bar < Bars; bar++)
                {
                    cd[bar] = IsConvergence(indicatorMa, marketMa, bar);
                }
            }
            else if (IndParam.ListParam[0].Text == "Divergence")
            {
                for (int bar = firstBar; bar < Bars; bar++)
                {
                    cd[bar] = IsDivergence(indicatorMa, marketMa, bar);
                }
            }

            // Saving the components
            Component = new IndicatorComp[4];

            Component[0] = new IndicatorComp
            {
                CompName   = "RSI",
                DataType   = IndComponentType.IndicatorValue,
                ChartType  = IndChartType.Line,
                ChartColor = Color.Blue,
                FirstBar   = firstBar,
                Value      = rsi.Component[0].Value
            };

            Component[1] = new IndicatorComp
            {
                CompName   = "RSI MA",
                DataType   = IndComponentType.IndicatorValue,
                ChartType  = IndChartType.Line,
                ChartColor = Color.Red,
                FirstBar   = firstBar,
                Value      = indicatorMa
            };

            Component[2] = new IndicatorComp
            {
                ChartType = IndChartType.NoChart,
                FirstBar  = firstBar,
                Value     = cd
            };

            Component[3] = new IndicatorComp
            {
                ChartType = IndChartType.NoChart,
                FirstBar  = firstBar,
                Value     = cd
            };

            // Sets the Component's type
            if (SlotType == SlotTypes.OpenFilter)
            {
                Component[2].DataType = IndComponentType.AllowOpenLong;
                Component[2].CompName = "Is long entry allowed";
                Component[3].DataType = IndComponentType.AllowOpenShort;
                Component[3].CompName = "Is short entry allowed";
            }
            else if (SlotType == SlotTypes.CloseFilter)
            {
                Component[2].DataType = IndComponentType.ForceCloseLong;
                Component[2].CompName = "Close out long position";
                Component[3].DataType = IndComponentType.ForceCloseShort;
                Component[3].CompName = "Close out short position";
            }
        }