Exemple #1
0
        public Instrument (Ticker ticker, TimeFrame timeFrame)
        {
            this.Ticker = ticker;
            this.TimeFrame = timeFrame;

            Candles = new List<Candle>();
        }
        public void BeginTest_HttpPost()
        {
            SessionHelper.session = new SessionStateMock();
            StrategyInfo strategyInfo = new StrategyInfo { Id = 1, Name = "Mock", TypeName = "RMarket.Examples.Strategies.StrategyMock, RMarket.Examples" };
            Ticker ticker = new Ticker { Id = 1, Code = "SBER" };
            TimeFrame timeFrame = new TimeFrame { Id = 11, Name = "1 day" };
            Instance instance = new Instance
            {
                Id = 1,
                GroupID = new Guid("a76dc9b4-8816-438e-aed3-c123374c2e3e"),
                StrParams = "[{\"FieldName\":\"withSleep\",\"FieldValue\":true}]",
                StrategyInfoId = strategyInfo.Id,
                StrategyInfo = strategyInfo,
                TickerId=ticker.Id,
                Ticker = ticker,
                TimeFrameId=timeFrame.Id,
                TimeFrame=timeFrame
            };
            Mock<IInstanceRepository> instanceRepoMock = new Mock<IInstanceRepository>();
            instanceRepoMock.Setup(m => m.Instances).Returns(new List<Instance>
            {
                instance
            }.AsQueryable());
            instanceRepoMock.Setup(m => m.Find(1)).Returns(instance);

            Mock<ICandleRepository> candleRepoMock = new Mock<ICandleRepository>();
            candleRepoMock.Setup(m => m.Candles).Returns(new List<Candle>
            {
                new Candle(ticker.Id,timeFrame.Id,new DateTime(2015,1,1),10m,15m,8m,11m,0),
                new Candle(ticker.Id,timeFrame.Id,new DateTime(2015,1,2),11m,15m,8m,11m,0),
                new Candle(ticker.Id,timeFrame.Id,new DateTime(2015,1,3),11m,16m,10m,15m,0),
            }.AsQueryable());

            TesterModel model = new TesterModel
            {
                InstanceId = 1,
                DateFrom=new DateTime(2015,1,1),
                DateTo=new DateTime(2015,2,1)
            };

            TesterController controller = CreateTestManagerController(instanceRepoMock.Object, candleRepoMock.Object);
           
            //Действие
            ActionResult result = controller.BeginTest(model);

            // Утверждение
            //1. В сесии есть объект результата
            List<TestResult> testResultCollection = (List<TestResult>)SessionHelper.session["TestResultCollection"];
            Assert.AreNotEqual(null, testResultCollection);

            //2. Проверка реквизитов сформированной стратегии
            IStrategy strategy = testResultCollection.FirstOrDefault(t => t.Id == 1).Strategy;
            Assert.AreEqual(ticker, strategy.Instr.Ticker);
            Assert.AreEqual(timeFrame, strategy.Instr.TimeFrame);

            //3. Стратегия стартована
            Assert.AreEqual(true, strategy.Manager.IsStarted);

        }
        public ICandleRepository candleRepository;//!!! = CurrentRepository.CandleRepository;

        public virtual int DownloadAndSave(DateTime dateFrom, DateTime dateTo, Ticker ticker, TimeFrame timeFrame)
        {
            int res = 0;

            IEnumerable<Candle> newCandles = DownloadCandles(dateFrom, dateTo, ticker, timeFrame);

            if (newCandles != null && newCandles.Count()>0)
            {
                //Удалить из базы данные
                IEnumerable<Candle> oldCandles = from c in candleRepository.Get()
                                          where c.TickerId == ticker.Id && c.TimeFrameId == timeFrame.Id && c.DateOpen >= dateFrom.Date && c.DateOpen < dateTo
                                          select c;
                candleRepository.RemoveRange(oldCandles);
                //

                candleRepository.AddRange(newCandles);

                res = newCandles.Count();
            }

            return res;

        }
Exemple #4
0
        public override IEnumerable<Candle> DownloadCandles(DateTime dateFrom, DateTime dateTo, Ticker ticker, TimeFrame timeFrame)
        {
            List<Candle> listCandles = new List<Candle>();

            //Пример: http://195.128.78.52/SBER_141008_141008.txt?market=1&em=3&code=SBER&df=8&mf=9&yf=2014&from=08.10.2014&dt=8&mt=9&yt=2014&to=08.10.2014&p=7&f=SBER_141008_141008&e=.txt&cn=SBER&dtf=1&tmf=1&MSOR=1&mstime=on&mstimever=1&sep=1&sep2=1&datf=1&at=1
            StringBuilder sb = new StringBuilder("http://195.128.78.52/SBER_141008_141008.txt?market=1");
            sb.Append("&em=" + ticker.CodeFinam); //Код тикера Финам
            sb.Append("&code=" + ticker.Code);
            sb.Append("&df=" + dateFrom.Day);
            sb.Append("&mf=" + (dateFrom.Month - 1));
            sb.Append("&yf=" + dateFrom.Year);
            sb.Append("&from=" + dateFrom.ToString("dd.MM.yyyy"));
            sb.Append("&dt=" + dateTo.Day);
            sb.Append("&mt=" + (dateTo.Month - 1));
            sb.Append("&yt=" + dateTo.Year);
            sb.Append("&to=" + dateTo.ToString("dd.MM.yyyy"));
            sb.Append("&p=" + timeFrame.CodeFinam); //Код интервала Финам
            sb.Append("&f=SBER_141008_141008"); //название выходного файла
            sb.Append("&e=.csv"); //.txt .csv
            sb.Append("&cn=" + ticker.Code);
            sb.Append("&dtf=1&tmf=1");
            sb.Append("&MSOR=0"); //0 - Время начало свечи, 1-окончания
            sb.Append("&mstime=on&mstimever=1&sep=1&sep2=1&datf=1&at=1");
            sb.Append("&fsp=1"); //Заполнять периоды без сделок
            WebRequest reqGet = WebRequest.Create(sb.ToString());

            WebResponse resp = reqGet.GetResponse();
            Stream stream = resp.GetResponseStream();
            StreamReader sr = new StreamReader(stream);

            if (sr.Peek() >= 0)
            {
                Dictionary<string, int> head = new Dictionary<string, int>();
                string strLine;
                int count = 0;

                while ((strLine = sr.ReadLine()) != null)
                {
                    string[] strArray = strLine.Split(new char[] { ',' });

                    count++;
                    if (count == 1) //Шапка
                    {
                        //Заполнить шапку
                        for (int i = 0; i < strArray.Length; i++)
                        {
                            //<TICKER>,<PER>,<DATE>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>
                            strArray[i] = Regex.Replace(strArray[i], "[<>]", "");
                            head.Add(strArray[i], i);
                        }
                        continue;
                    }

                    if (strArray.Length != head.Count)
                        continue; //бывают траблы(

                    //Сформировать свечу
                    DateTime dateOpen = DateTime.ParseExact(strArray[head["DATE"]] + strArray[head["TIME"]], "yyyyMMddHHmmss", null);
                    decimal OpenPrice = Convert.ToDecimal(strArray[head["OPEN"]], new CultureInfo("en-US"));
                    decimal HighPrice = Convert.ToDecimal(strArray[head["HIGH"]], new CultureInfo("en-US"));
                    decimal LowPrise = Convert.ToDecimal(strArray[head["LOW"]], new CultureInfo("en-US"));
                    decimal ClosePrice = Convert.ToDecimal(strArray[head["CLOSE"]], new CultureInfo("en-US"));
                    int Volume = Convert.ToInt32(strArray[head["VOL"]]);

                    //!!!Создает ticker и timeFrame                
                    Candle candle = new Candle(ticker.Id, timeFrame.Id, dateOpen, OpenPrice, HighPrice, LowPrise, ClosePrice, Volume);

                    listCandles.Add(candle);
                }
            }

            return listCandles;

        }
        public void CreateFirstGeneration()
        {
            //!!! Долго

            Ticker ticker = new Ticker
            {
                Id = 1,
                Name = "sber",
                Code = "sber",
            };
            TimeFrame timeFrame = new TimeFrame
            {
                Id = 10,
                Name = "10",
                ToMinute = 10
            };
            StrategyInfo strategyInfo = new StrategyInfo
            {
                Id = 20,
                Name = "Mock",
                TypeName = "RMarket.Examples.Strategies.StrategyMock, RMarket.Examples"
            };

            SelectionModel selection = new SelectionModel
            {
                Id = 30,
                Name = "TestSelection",
                TickerId = ticker.Id,
                Ticker = ticker,
                TimeFrameId = timeFrame.Id,
                TimeFrame=timeFrame,
                StrategyInfoId = strategyInfo.Id,
                StrategyInfo=strategyInfo,
                AmountResults = 10,
                Balance = 1000,
                CreateDate = new DateTime(2016, 1, 1),
                DateFrom = new DateTime(2016, 1, 1),
                DateTo = new DateTime(2016, 1, 10),
                Description = "for test",
                GroupID = new Guid("7ada9499-cb8e-44ad-862a-a93920ff4760"),
                Slippage = 0.01M,
                Rent = 0.1M,
                SelectionParams = new List<ParamSelection>
                {
                    new ParamSelection
                    {
                        FieldName="Param1",
                        TypeName = "System.Int32",
                        ValueMin = 6,
                        ValueMax=10
                    },
                    new ParamSelection
                    {
                        FieldName="Param2",
                        ValueMin = (byte)1,
                        TypeName = "System.Byte",
                        ValueMax=(byte)5
                    },
                    new ParamSelection
                    {
                        FieldName="OtherParam",
                        TypeName = "System.Boolean",
                        ValueMin = true,
                        ValueMax=true
                    }
                    //Добавить вещественный
                }
            };

            List<InstanceModel> instances1 = OptimizationHelper.CreateFirstGeneration(selection);

            Assert.AreEqual(10, instances1.Count);
            Assert.AreEqual(1, instances1[0].TickerId);
            Assert.AreEqual(10, instances1[0].TimeFrameId);
            Assert.AreEqual(20, instances1[0].StrategyInfoId);
            Assert.AreEqual(30, instances1[0].SelectionId);

            Assert.AreEqual(true, instances1[0].StrategyParams.Any(p=>p.FieldName== "OtherParam" && (bool)p.FieldValue==true));
            Assert.AreEqual(true, instances1[0].StrategyParams.Any(p=>p.FieldName== "Param1" && (int)p.FieldValue >= 6 && (int)p.FieldValue <= 10));
            Assert.AreEqual(true, instances1[0].StrategyParams.Where(p=>p.FieldName == "Param2").Single().FieldValue.GetType() == typeof(byte));

        }
        public void GetIndicatorList()
        {
            IStrategy strategy = new StrategyMock();
            Ticker ticker = new Ticker { Id = 1, Code = "SBER" };
            TimeFrame timeFrame = new TimeFrame { Id = 11, Name = "1 day" };
            strategy.Instr = new Instrument(ticker, timeFrame);

            strategy.Initialize();

            //Действие - Получение Коллекции индикаторов
            Dictionary<string, IIndicator> indicatorsDict = StrategyHelper.ExtractIndicatorsInStrategy(strategy);

            //Утверждение 
            //1. количество индикаторов
            Assert.AreEqual(2, indicatorsDict.Count);

            //2. Имена индикаторов
            Assert.IsTrue(indicatorsDict.ContainsKey("Индикатор1"));
            Assert.IsTrue(indicatorsDict.ContainsKey("ind2"));

        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="dateFrom">Учитывается дата</param>
 /// <param name="dateTo">Не включая!</param>
 /// <param name="ticker"></param>
 /// <param name="timeFrame"></param>
 /// <returns></returns>
 public abstract IEnumerable<Candle> DownloadCandles(DateTime dateFrom, DateTime dateTo, Ticker ticker, TimeFrame timeFrame);