Exemplo n.º 1
0
        private void ApplyProfitStrategy(Position position, bool onBar)
        {
            if (Params.ProfitStrategy == ProfitStrategy.TRAILING_ENVELOPE_50)
            {
                int    lastBar   = Robot.MarketSeries.Close.Count - 1;
                double lastPrice = Robot.MarketSeries.Close.LastValue;

                if (position.TakeProfit.HasValue)
                {
                    position.ModifyTakeProfitPrice(null);
                }

                if (position.TradeType == TradeType.Buy && onBar)
                {
                    EmaLow.Calculate(lastBar);
                    EmaHigh.Calculate(lastBar);
                    double emaLow  = EmaLow.Result[lastBar];
                    double emaHigh = EmaHigh.Result[lastBar];
                    if ((lastPrice - emaHigh) / Robot.Symbol.PipSize > 5 && !trailedPositions.Contains(position))
                    {
                        position.ModifyStopLossPrice(emaLow);
                        trailedPositions.Add(position);
                    }
                    if (trailedPositions.Contains(position))
                    {
                        position.ModifyStopLossPrice(emaLow);
                    }
                }
                if (position.TradeType == TradeType.Sell && onBar)
                {
                    EmaLow.Calculate(lastBar);
                    EmaHigh.Calculate(lastBar);
                    double emaLow  = EmaLow.Result[lastBar];
                    double emaHigh = EmaHigh.Result[lastBar];
                    if ((emaLow - lastPrice) / Robot.Symbol.PipSize > 5 && !trailedPositions.Contains(position))
                    {
                        position.ModifyStopLossPrice(emaHigh);
                        trailedPositions.Add(position);
                    }
                    if (trailedPositions.Contains(position))
                    {
                        position.ModifyStopLossPrice(emaHigh);
                    }
                }
            }
            if (Params.ProfitStrategy == ProfitStrategy.SIMPLE)
            {
                if (Params.ProfitVolume > 0)
                {
                    logger.Info(String.Format("Partial profit taken for {0}% of original volume of {1} units", Params.ProfitVolume, position.VolumeInUnits));
                    Robot.Print("Partial profit taken for {0}% of original volume of {1} units", Params.ProfitVolume, position.VolumeInUnits);
                    Robot.ModifyPosition(position, Robot.Symbol.NormalizeVolumeInUnits(position.VolumeInUnits * Params.ProfitVolume));
                }
            }
        }
Exemplo n.º 2
0
        protected override void OnTick()
        {
            ExponentialMovingAverage EMA20 = Indicators.ExponentialMovingAverage(null, 20);

            EMA20.Calculate(0);
            int x = EMA20.Result;

            x = x;
        }
        public void Calculate_YesterdayEma10AndTodayPrice10And9Days_10()
        {
            var calc         = new ExponentialMovingAverage();
            var yesterdayEma = 10;
            var today        = 10;
            var numberOfDays = 9;

            var result = calc.Calculate(yesterdayEma, today, numberOfDays);

            Assert.AreEqual(10, result);
        }
        public void Calculate_PointsIsNull_ArgumentExceptionThrown()
        {
            var calc = new ExponentialMovingAverage();

            try
            {
                calc.Calculate(null, 0);
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(ArgumentException));
            }
        }
        public void Calculate_PointsHasLessThanNumberOfDays_ArgumentExceptionThrown()
        {
            var calc   = new ExponentialMovingAverage();
            var points = new List <double>();

            try
            {
                calc.Calculate(points, -1);
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(ArgumentException));
            }
        }
Exemplo n.º 6
0
        public static double[] CalculateEMA(string symbol, int window, int period)
        {
            double[] closePrices = null;

            using (InvestmentAnalysisContext context = new InvestmentAnalysisContext())
            {
                closePrices = context.HistoricalDataBlocks
                              .Where(q => q.Symbol.Equals(symbol))
                              .OrderByDescending(q => q.RecordDate)
                              .Take(window)
                              .Select(c => (double)c.LastPrice)
                              .ToArray();
            }

            return(ExponentialMovingAverage.Calculate(closePrices.Reverse().ToArray(), period));
        }
        public void Calculate_20PointsAnd10Days_11DaysEMA()
        {
            var points = new List <double>()
            {
                22.2734,
                22.194,
                22.0847,
                22.1741,
                22.184,
                22.1344,
                22.2337,
                22.4323,
                22.2436,
                22.2933,
                22.1542,
                22.3926,
                22.3816,
                22.6109,
                23.3558,
                24.0519,
                23.753,
                23.8324,
                23.9516,
                23.6338
            };
            var calc = new ExponentialMovingAverage();

            var ema = calc.Calculate(points, 10);

            Assert.AreEqual(22.2119, Math.Round(ema[0], 4));
            Assert.AreEqual(22.2448, Math.Round(ema[1], 4));
            Assert.AreEqual(22.2697, Math.Round(ema[2], 4));
            Assert.AreEqual(22.3317, Math.Round(ema[3], 4));
            Assert.AreEqual(22.5179, Math.Round(ema[4], 4));
            Assert.AreEqual(22.7968, Math.Round(ema[5], 4));
            Assert.AreEqual(22.9707, Math.Round(ema[6], 4));
            Assert.AreEqual(23.1273, Math.Round(ema[7], 4));
            Assert.AreEqual(23.2772, Math.Round(ema[8], 4));
            Assert.AreEqual(23.3420, Math.Round(ema[9], 4));
        }
Exemplo n.º 8
0
        public static double[] CalculateEMA()
        {
            int period = 10;

            IList <double> data = new List <double>();

            data.Add(22.27);
            data.Add(22.19);
            data.Add(22.08);
            data.Add(22.17);
            data.Add(22.18);
            data.Add(22.13);
            data.Add(22.23);
            data.Add(22.43);
            data.Add(22.24);
            data.Add(22.29);
            data.Add(22.15);
            data.Add(22.39);
            data.Add(22.38);
            data.Add(22.61);

            return(ExponentialMovingAverage.Calculate(data.ToArray(), period));
        }
Exemplo n.º 9
0
        private static TotalTransactionInfo GetTotalTransactionInfo(string symbol, HistoricalDataBlock[] historicalDataBlocks, int fasterPeriod, int slowerPeriod, int window = 0)
        {
            Console.WriteLine("*********************************************");
            Console.WriteLine("SYMBOL = {0}, WINDOW = {1}, FASTER_PERIOD = {2}, SLOWER_PERIOD = {3}",
                              symbol, window, fasterPeriod, slowerPeriod);

            //HistoricalDataBlock[] historicalDataBlocks = HelperMethods.GetHistoricalDataBlock(symbol, window);
            double[] data      = historicalDataBlocks.Select(c => (double)c.LastPrice).ToArray();
            double[] emaFaster = ExponentialMovingAverage.Calculate(data, fasterPeriod).Skip(slowerPeriod - fasterPeriod).ToArray();
            double[] emaSlower = ExponentialMovingAverage.Calculate(data, slowerPeriod);

            //Console.WriteLine("BLOCK_LENGTH = {0}, DATA_LENGTH = {1}, EMA_FASTER_LENGTH = {2}, EMA_SLOWER_LENGTH = {3}",
            //    historicalDataBlocks.Length, data.Length, emaFaster.Length, emaSlower.Length);

            List <PositionInfo> _positionInfoList = new List <PositionInfo>();

            string previousSign       = string.Empty;
            string currentSign        = string.Empty;
            bool   longPosition       = false;
            bool   shortPosition      = false;
            bool   changePosition     = false;
            string positionChangeInfo = string.Empty;

            for (int i = 0; i < emaFaster.Length; i++)
            {
                if (emaFaster[i] > emaSlower[i])
                {
                    currentSign = "+";
                }
                else if (emaFaster[i] < emaSlower[i])
                {
                    currentSign = "-";
                }
                else
                {
                    currentSign = "=";
                }

                longPosition   = ("-".Equals(previousSign) || "=".Equals(previousSign)) && "+".Equals(currentSign);
                shortPosition  = ("+".Equals(previousSign) || "=".Equals(previousSign)) && "-".Equals(currentSign);
                changePosition = longPosition || shortPosition;

                HistoricalDataBlock historicalData = historicalDataBlocks[slowerPeriod + i - 1];

                positionChangeInfo = string.Empty;
                if (changePosition)
                {
                    string type = longPosition ? "LONG" : "SHORT";

                    positionChangeInfo = "*****" + " # " + historicalData.LastPrice.ToString("F") + " # " + type;

                    _positionInfoList.Add(new PositionInfo()
                    {
                        Type = type, Date = historicalData.RecordDate, Price = (double)historicalData.LastPrice
                    });
                }

                //Console.WriteLine(historicalData.RecordDate.ToString("yyyy-MM-dd") + " # "
                //    + string.Format("{0:F4}", emaFaster[i]) + " # " + string.Format("{0:F4}", emaSlower[i]) + " # "
                //    + currentSign + " # " + positionChangeInfo);

                previousSign = currentSign;
            }

            //Console.WriteLine("*********************************************");
            Console.WriteLine("TOTAL POSITION COUNT: " + _positionInfoList.Count);

            double _safe = 0.00;

            if (1 == _positionInfoList.Count % 2)
            {
                _positionInfoList.RemoveAt(_positionInfoList.Count - 1);
            }

            if (_positionInfoList.Count > 0)
            {
                double price = 0.00;

                for (int i = 0; i < _positionInfoList.Count; i++)
                {
                    //Console.WriteLine(positionInfoList[i].ToString());

                    price = _positionInfoList[i].Price;

                    if ("SHORT".Equals(_positionInfoList[i].Type))
                    {
                        price = (-1) * price;
                    }

                    _safe = _safe + price;
                }

                Console.WriteLine("TOTAL POSITION PROFIT / LOSS: " + _safe);
            }

            return(new TotalTransactionInfo {
                safe = _safe, positionInfoList = _positionInfoList, ratio = (((_safe) / (_positionInfoList[0].Price * 100)).ToString("F"))
            });

            //TotalTransactionInfo totalTransactionInfo = new TotalTransactionInfo();
            //x.positionInfoList = _positionInfoList;
            //x.safe = _safe;
            //x.ratio = (((_safe) / (_positionInfoList[0].Price * 100)).ToString("F")) ;


            //return _safe;

            //Console.WriteLine("*********************************************");
        }