Exemplo n.º 1
0
 public void PowTrend()
 {
     Trend.Pow(new List <double>()
     {
         1, 2, 5, 6
     });
 }
Exemplo n.º 2
0
        public void CorrectUp()
        {
            var articlesFilePath = @"TestData\Index\MiddleTerm\Index.MiddleTerm.Up.xml";

            var macroWordsLoader = new MacroWordsLoader(@"AppData\MacroWords.xml");
            var patternsLoader   = new RawPatternsLoader(@"AppData\Up.xml", Trend.Up);


            var patternProvider = new PatternsProvider(patternsLoader.Patterns, macroWordsLoader.MacroWords);

            var classifier = new OpinionClassifier(patternProvider);

            var articles = new TestArticleLoader().LoadArticles(articlesFilePath);

            foreach (var article in articles)
            {
                if (String.IsNullOrEmpty(article.Title) && String.IsNullOrEmpty(article.Text))
                {
                    continue;
                }

                Trend result = classifier.Classify(article).Trend;

                Assert.AreEqual(Trend.Up, result, "Incorrect classification for: " + article.Id + " : " + article.Text);
            }
        }
Exemplo n.º 3
0
        public bool TryInitialize(int lastLineBar, Trend trend)
        {
            int bar      = bars.CurrentBar;
            int lookBack = 1;

            InterceptBar = lastLineBar;

            for ( ; bar > bars.CurrentBar - bars.Capacity && bar >= lastLineBar; bar--)
            {
                addBar(bar);
            }
            if (CountPoints > lookBack)
            {
                Calculate();
                UpdateEnds();
                // If new channel isn't in the direction expected
                // then forget it.
                if (trend == Trend.Up && !IsUp)
                {
                    return(false);
                }
                else if (trend == Trend.Down && !IsDown)
                {
                    return(false);
                }
                calcMaxDev();
                if (drawLines)
                {
                    DrawChannel();
                }
                return(true);
            }
            return(false);
        }
 public Schema()
     : base()
 {
     InstanceType = typeof(__Franchis1__);
     Properties.ClearExposed();
     Name = Add <__TString__>("Name");
     Name.DefaultValue = "";
     Name.SetCustomAccessors((_p_) => { return(((__Franchis1__)_p_).__bf__Name__); }, (_p_, _v_) => { ((__Franchis1__)_p_).__bf__Name__ = (System.String)_v_; }, false);
     Url = Add <__TString__>("Url");
     Url.DefaultValue = "";
     Url.SetCustomAccessors((_p_) => { return(((__Franchis1__)_p_).__bf__Url__); }, (_p_, _v_) => { ((__Franchis1__)_p_).__bf__Url__ = (System.String)_v_; }, false);
     Key = Add <__TString__>("Key");
     Key.DefaultValue = "";
     Key.SetCustomAccessors((_p_) => { return(((__Franchis1__)_p_).__bf__Key__); }, (_p_, _v_) => { ((__Franchis1__)_p_).__bf__Key__ = (System.String)_v_; }, false);
     SoldHomes = Add <__TLong__>("SoldHomes");
     SoldHomes.DefaultValue = 0L;
     SoldHomes.SetCustomAccessors((_p_) => { return(((__Franchis1__)_p_).__bf__SoldHomes__); }, (_p_, _v_) => { ((__Franchis1__)_p_).__bf__SoldHomes__ = (System.Int64)_v_; }, false);
     TotalComission = Add <__TLong__>("TotalComission");
     TotalComission.DefaultValue = 0L;
     TotalComission.SetCustomAccessors((_p_) => { return(((__Franchis1__)_p_).__bf__TotalComission__); }, (_p_, _v_) => { ((__Franchis1__)_p_).__bf__TotalComission__ = (System.Int64)_v_; }, false);
     AvgComission = Add <__TLong__>("AvgComission");
     AvgComission.DefaultValue = 0L;
     AvgComission.SetCustomAccessors((_p_) => { return(((__Franchis1__)_p_).__bf__AvgComission__); }, (_p_, _v_) => { ((__Franchis1__)_p_).__bf__AvgComission__ = (System.Int64)_v_; }, false);
     Trend = Add <__TLong__>("Trend");
     Trend.DefaultValue = 0L;
     Trend.SetCustomAccessors((_p_) => { return(((__Franchis1__)_p_).__bf__Trend__); }, (_p_, _v_) => { ((__Franchis1__)_p_).__bf__Trend__ = (System.Int64)_v_; }, false);
 }
Exemplo n.º 5
0
 public void ExpTrend()
 {
     Trend.Exp(new List <double>()
     {
         1, 2, 5, 6
     }, 0.5);
 }
Exemplo n.º 6
0
        public void PatchFollow_SavesChangesInTrend()
        {
            TrendPatchFollowDto trendPatchFollowDto = new TrendPatchFollowDto
            {
                Id        = Guid.Parse("3fa85f64-5717-4562-b3fc-2c963f66afa6"),
                CreatorId = Guid.Parse("2fa85f64-5717-4562-b3fc-2c963f66afa6"),
                Type      = "Not Follow"
            };
            TrendFollow trendFollow = new TrendFollow
            {
                TrendId = trendPatchFollowDto.Id,
                UserId  = trendPatchFollowDto.CreatorId
            };
            Trend trend = new Trend
            {
                FollowersCount = 10
            };

            trendFollowRepositoryMock.Setup(x => x.GetByFilter(tf => tf.UserId == trendPatchFollowDto.CreatorId && tf.TrendId == trendPatchFollowDto.Id)).Returns(trendFollow);
            trendRepositoryMock.Setup(x => x.GetById(trendPatchFollowDto.Id)).Returns(trend);

            systemUnderTest.PatchFollow(trendPatchFollowDto);
            trend.FollowersCount -= 1;

            trendRepositoryMock.Verify(m => m.SaveChanges(), Times.Once);
        }
Exemplo n.º 7
0
        public void PatchFollow_TrendFollowCountIncreasesAfterInsert()
        {
            TrendPatchFollowDto trendPatchFollowDto = new TrendPatchFollowDto
            {
                Id        = Guid.Parse("3fa85f64-5717-4562-b3fc-2c963f66afa6"),
                CreatorId = Guid.Parse("2fa85f64-5717-4562-b3fc-2c963f66afa6"),
                Type      = "Follow"
            };
            TrendFollow trendFollow = new TrendFollow
            {
                TrendId = trendPatchFollowDto.Id,
                UserId  = trendPatchFollowDto.CreatorId
            };
            Trend trend = new Trend
            {
                FollowersCount = 0
            };

            trendFollowRepositoryMock.Setup(x => x.GetByFilter(tf => tf.UserId == trendPatchFollowDto.CreatorId && tf.TrendId == trendPatchFollowDto.Id)).Returns(() => null);
            trendRepositoryMock.Setup(x => x.GetById(trendPatchFollowDto.Id)).Returns(trend);

            systemUnderTest.PatchFollow(trendPatchFollowDto);
            trend.FollowersCount += 1;

            trendRepositoryMock.Verify(m => m.Update(trend), Times.Once);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Получить тренд минутных данных заданного канала за сутки
        /// </summary>
        /// <remarks>Возвращаемый тренд после загрузки не изменяется экземпляром данного класса,
        /// таким образом, чтение его данных является потокобезопасным.
        /// Метод всегда возвращает объект, не равный null</remarks>
        public Trend GetMinTrend(DateTime date, int cnlNum)
        {
            Trend trend = new Trend(cnlNum);

            try
            {
                if (serverComm.ReceiveTrend(SrezAdapter.BuildMinTableName(date), date, trend))
                {
                    trend.LastFillTime = DateTime.UtcNow; // единообразно с часовыми данными и событиями
                }
                else
                {
                    throw new ScadaException(Localization.UseRussian ?
                                             "Не удалось принять тренд." :
                                             "Unable to receive trend.");
                }
            }
            catch (Exception ex)
            {
                log.WriteException(ex, Localization.UseRussian ?
                                   "Ошибка при получении тренда минутных данных за {0}" :
                                   "Error getting minute data trend for {0}", date.ToLocalizedDateString());
            }

            return(trend);
        }
Exemplo n.º 9
0
 public Schema()
     : base()
 {
     InstanceType = typeof(__Franchis__);
     Properties.ClearExposed();
     Html = Add <__TString__>("Html");
     Html.DefaultValue = "/Ahsan/Corporation/FranchiseJson.html";
     Html.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__Html__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__Html__ = (System.String)_v_; }, false);
     Name = Add <__TString__>("Name");
     Name.DefaultValue = "";
     Name.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__Name__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__Name__ = (System.String)_v_; }, false);
     AverageCommision = Add <__TLong__>("AverageCommision");
     AverageCommision.DefaultValue = 0L;
     AverageCommision.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__AverageCommision__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__AverageCommision__ = (System.Int64)_v_; }, false);
     NumberOfHomesSold = Add <__TLong__>("NumberOfHomesSold");
     NumberOfHomesSold.DefaultValue = 0L;
     NumberOfHomesSold.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__NumberOfHomesSold__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__NumberOfHomesSold__ = (System.Int64)_v_; }, false);
     TotalCommission = Add <__TLong__>("TotalCommission");
     TotalCommission.DefaultValue = 0L;
     TotalCommission.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__TotalCommission__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__TotalCommission__ = (System.Int64)_v_; }, false);
     Trend = Add <__TLong__>("Trend");
     Trend.DefaultValue = 0L;
     Trend.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__Trend__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__Trend__ = (System.Int64)_v_; }, false);
     ObjectId = Add <__TString__>("ObjectId", bind: "ObjectId");
     ObjectId.DefaultValue = "";
     ObjectId.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__ObjectId__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__ObjectId__ = (System.String)_v_; }, false);
 }
Exemplo n.º 10
0
 public void LineTrend()
 {
     Trend.Line(new List <double>()
     {
         1, 2, 5, 6
     });
 }
Exemplo n.º 11
0
        public IActionResult Register(LoginWrapper WrappedUser)
        {
            User user = WrappedUser.NewUser;

            if (dbContext.Users.Any(u => u.Email == user.Email))
            {
                ModelState.AddModelError("NewUser.Email", "Email already in use!");
            }
            if (ModelState.IsValid)
            {
                PasswordHasher <User> Hasher = new PasswordHasher <User>();
                user.Password = Hasher.HashPassword(user, user.Password);
                dbContext.Add(user);
                dbContext.SaveChanges();
                Trend CurrentTrend  = new Trend();
                Trend LastWeekTrend = new Trend();
                CurrentTrend.TrendOwner  = user;
                LastWeekTrend.TrendOwner = user;
                dbContext.Add(CurrentTrend);
                dbContext.Add(LastWeekTrend);
                dbContext.SaveChanges();
                HttpContext.Session.SetInt32("LoggedInUserID", user.UserId);
                return(RedirectToAction("Dashboard"));
            }
            else
            {
                return(View("Index"));
            }
        }
Exemplo n.º 12
0
 public Entry(DateTime timestamp, float value, Unit unit, Trend trend)
 {
     Timestamp = timestamp;
     Value     = value;
     Digits    = GetDigits(Value, unit);
     Trend     = trend;
 }
Exemplo n.º 13
0
        /// <summary>
        /// Fills chart data for the time range specified as an argument.
        /// </summary>
        public void FillData(TimeRange timeRange)
        {
            ArgumentNullException.ThrowIfNull(timeRange, nameof(timeRange));
            singleTrend = null;
            trendBundle = null;
            int cnlCnt = options.CnlNums.Length;

            try
            {
                if (cnlCnt == 1)
                {
                    singleTrend = scadaClient.GetTrend(options.ArchiveBit, timeRange, options.CnlNums[0]);
                }
                else if (cnlCnt > 1)
                {
                    trendBundle = scadaClient.GetTrends(options.ArchiveBit, timeRange, options.CnlNums);
                }
            }
            catch (Exception ex)
            {
                throw new ScadaException(Locale.IsRussian ?
                                         "Ошибка при получении одного или нескольких трендов" :
                                         "Error getting one or several trends", ex);
            }
        }
Exemplo n.º 14
0
        TrendGetAllDto ITrendBusinessLogic.Create(TrendCreateDto trend)
        {
            Trend createdTrend = mapper.Map <Trend>(trend);

            ImageGetDto image = imageService.Create(new ImageCreateDto()
            {
                Image  = trend.Image,
                Prefix = "trends"
            });

            CreateContentScanTaskDto createContentScanTaskDto = new CreateContentScanTaskDto()
            {
                ImageUrl                                     = image != null?imageService.GetFullImageUrl(image.Url) : null,
                                                 Text        = trend.Description,
                                                 CallbackUrl = $"/api/v1/trends/{createdTrend.Id}/content-scan-result"
            };

            contentScanTaskService.CreateTask(createContentScanTaskDto);

            createdTrend.ImageUrl = image != null ? image.Url : imageService.GetDefaultImageUrl();
            trendRepository.Insert(createdTrend);
            trendRepository.SaveChanges();

            return(mapper.Map <TrendGetAllDto>(createdTrend));
        }
        private bool GetSignalUp(double crtdr, double rsi, Trend trend)
        {
            if (trend == Trend.Up)
            {
                if (crtdr * 100 + rsi <= LongLimitUp)
                {
                    return(true);
                }
            }
            else if (trend == Trend.Down)
            {
                if (crtdr * 100 + rsi <= LongLimitDown)
                {
                    return(true);
                }
            }
            else
            {
                if (crtdr * 100 + rsi <= LongLimitFlat)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 16
0
        private void LoadTrendCore(List <IDataPoint> trend)
        {
            if (trend != null)
            {
                trend.Clear();
            }
            const int timeRes = 25;
            var       r       = new Random();
            int       g       = r.Next(100);

            if (g == 0)
            {
                g = 99;
            }
            double P    = r.Next(100) / 100.0;
            double amp  = r.NextDouble() - 0.5;
            double y    = r.NextDouble() - 0.5;
            int    mode = r.Next(10) - 5;

            if (mode > 0)
            {
                for (int i = 0; i < 100000; i++)
                {
                    Trend.Add(new DataPointSimple(y + Math.Sin(4.0 * Math.PI / 100000.0 * i + P) * amp * 1.0 * i / 10000.0, new DateTime(timeRes * i), true, 0, null));
                }
            }
            else
            {
                for (int i = 0; i < 100000; i++)
                {
                    Trend.Add(new DataPointSimple(y + Math.Exp(i / 100000.0) * amp * 0.05 * i / 10000.0, new DateTime(timeRes * i), true, 0, null));
                }
            }
            IsTrendLoaded = true;
        }
Exemplo n.º 17
0
        private bool GetSignalUp(double crtdr, double rsi, Trend trend)
        {
            if (trend == Trend.Up)
            {
                if (crtdr * 100 + rsi <= LongLimitUp)
                {
                    LogThrottled("Signal up because crtdr {0} * 100 + rsi {1} <= LongLimitUp {2}", crtdr, rsi, LongLimitUp);
                    return(true);
                }
            }
            else if (trend == Trend.Down)
            {
                if (crtdr * 100 + rsi <= LongLimitDown)
                {
                    LogThrottled("Signal up because crtdr {0} * 100 + rsi {1} <= LongLimitDown {2}", crtdr, rsi, LongLimitDown);
                    return(true);
                }
            }
            else
            {
                if (crtdr * 100 + rsi <= LongLimitFlat)
                {
                    LogThrottled("Signal up because crtdr {0} * 100 + rsi {1} <= LongLimitFlat {2}", crtdr, rsi, LongLimitFlat);
                    return(true);
                }
            }

            LogThrottled("No signal up because with crtdr {0}, rsi {1}, LongLimitUp {2}, LongLimitDown {3}, LongLimitFlat {4}", crtdr, rsi, LongLimitUp, LongLimitDown, LongLimitFlat);
            return(false);
        }
Exemplo n.º 18
0
 private void AddChartValues(Trend _trend, DateTime now)
 {
     Console.WriteLine(CpuSeries);
     CpuSeries.Values.Add(new MeasureModel {
         DateTime = now, Value = _trend.Cpu
     });
     GpuSeries.Values.Add(new MeasureModel {
         DateTime = now, Value = _trend.Gpu
     });
     MemorySeries.Values.Add(new MeasureModel {
         DateTime = now, Value = _trend.Memory
     });
     DiskSeries.Values.Add(new MeasureModel {
         DateTime = now, Value = _trend.Disk
     });
     NetworkSeries.Values.Add(new MeasureModel {
         DateTime = now, Value = _trend.Network
     });
     CpuTempSeries.Values.Add(new MeasureModel {
         DateTime = now, Value = _trend.CpuTemp
     });
     GpuTempSeries.Values.Add(new MeasureModel {
         DateTime = now, Value = _trend.GpuTemp
     });
 }
Exemplo n.º 19
0
        public void DeletestringById(int id)
        {
            Trend oldtrend = _trendContext.Trends.FirstOrDefault(trend => trend.Id == id);

            _trendContext.Trends.Remove(oldtrend);
            _trendContext.SaveChanges();
        }
Exemplo n.º 20
0
        public DMITrendElement(Random rand)
        {
            var n = 2 * rand.Next(2) - 1;

            trend        = (Trend)n;
            SymbolString = "DMITrend == " + trend.GetString() + "?";
        }
Exemplo n.º 21
0
        void ITrendBusinessLogic.PatchFollow(TrendPatchFollowDto trendPatchFollowDto)
        {
            TrendFollow trendFollow = trendFollowRepository.GetByFilter(
                tf => tf.UserId == trendPatchFollowDto.CreatorId && tf.TrendId == trendPatchFollowDto.Id);
            bool doFollow = trendPatchFollowDto.Type == "Follow";

            int followsDelta = 0;

            if (trendFollow == null && doFollow)
            {
                trendFollow = new TrendFollow
                {
                    TrendId = trendPatchFollowDto.Id,
                    UserId  = trendPatchFollowDto.CreatorId
                };
                trendFollowRepository.Insert(trendFollow);
                trendFollowRepository.SaveChanges();
                ++followsDelta;
            }
            else if (trendFollow != null && !doFollow)
            {
                trendFollowRepository.Delete(trendFollow.Id);
                trendFollowRepository.SaveChanges();
                --followsDelta;
            }
            if (followsDelta != 0)
            {
                Trend trend = trendRepository.GetById(trendPatchFollowDto.Id);
                trend.FollowersCount += followsDelta;
                trendRepository.Update(trend);
                trendRepository.SaveChanges();
            }
        }
Exemplo n.º 22
0
        private void monitorPriceTrend(int index)
        {
            currentPrice = (double)SimulationHouse.shareTable.Rows[index]["BidClose"];
            lastMA       = currentMA;

            currentMA.M5   = Cal_MA(index, 5);
            currentMA.M10  = Cal_MA(index, 10);
            currentMA.M20  = Cal_MA(index, 20);
            currentMA.M30  = Cal_MA(index, 30);
            currentMA.M60  = Cal_MA(index, 60);
            currentMA.M120 = Cal_MA(index, 120);
            currentMA.M240 = Cal_MA(index, 240);

            lastMATrend = currentMATrend;
            currentMATrend.M5_SlopeRatio   = currentMA.M5 - lastMA.M5;
            currentMATrend.M10_SlopeRatio  = currentMA.M10 - lastMA.M10;
            currentMATrend.M20_SlopeRatio  = currentMA.M20 - lastMA.M20;
            currentMATrend.M30_SlopeRatio  = currentMA.M30 - lastMA.M30;
            currentMATrend.M60_SlopeRatio  = currentMA.M60 - lastMA.M60;
            currentMATrend.M120_SlopeRatio = currentMA.M120 - lastMA.M120;
            currentMATrend.M240_SlopeRatio = currentMA.M240 - lastMA.M240;

            lastPriceTrend = currentPriceTrend;
            if (currentMA.M5 > currentMA.M10)
            {
                this.currentPriceTrend = Trend.Ascend;
            }
            else if (currentMA.M5 < currentMA.M10)
            {
                this.currentPriceTrend = Trend.Descend;
            }
        }
Exemplo n.º 23
0
 public void LogTrend()
 {
     Trend.Log(new List <double>()
     {
         1, 2, 5, 6
     });
 }
Exemplo n.º 24
0
        /// <summary>
        /// Gets the trend of the specified channel.
        /// </summary>
        public override Trend GetTrend(TimeRange timeRange, int cnlNum)
        {
            try
            {
                stopwatch.Restart();
                conn.Open();

                Trend            trend  = new Trend(cnlNum, 0);
                NpgsqlCommand    cmd    = CreateTrendCommand(timeRange, cnlNum);
                NpgsqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    trend.Points.Add(new TrendPoint(
                                         reader.GetDateTimeUtc(0),
                                         reader.GetDouble(1),
                                         reader.GetInt32(2)));
                }

                stopwatch.Stop();
                arcLog?.WriteAction(ServerPhrases.ReadingTrendCompleted,
                                    trend.Points.Count, stopwatch.ElapsedMilliseconds);
                return(trend);
            }
            finally
            {
                conn.Close();
            }
        }
Exemplo n.º 25
0
        public Simulation(string argName, TestParam argTestParam, ref PersonForm view, ref UInt32 currentThreadNum)
        {
            currentThreadNum++;
            name          = argName;
            testParam     = argTestParam;
            currentStatus = PositionStatus.None;
            currentPosition.closePrice = 0.0;
            tradeTimes        = 0;
            badTradeTimes     = 0;
            goodTradeTimes    = 0;
            profit            = 0;
            simulationIndex   = 0;
            currentPriceTrend = Trend.None;
            lastPriceTrend    = Trend.None;
            TradeDt           = new DataTable();
            MAs = new List <MA>(8);
            MAs.Add(new MA(5));
            MAs.Add(new MA(10));
            MAs.Add(new MA(20));
            MAs.Add(new MA(30));
            MAs.Add(new MA(60));
            MAs.Add(new MA(120));
            MAs.Add(new MA(240));


            updateCurrentStatusDelegate    = new Model.Simulation.UpdateCurrentStatusDelegate(view.updateCurrentStatus);
            updateTradeLogParallelDelegate = new Model.Simulation.UpdateTradeLogParallelDelegate(view.updateTradeLogParallelTextBox);
        }
 public void ReturnsCorrectResult(
     decimal fastSMA,
     decimal slowSMA,
     Trend expectedResult)
 {
     Assert.AreEqual(expectedResult, Service.GetTrend(fastSMA, slowSMA));
 }
Exemplo n.º 27
0
        public void ProcessResults_Handles_Available()
        {
            var trendReqProc = new TrendRequestProcessor <Trend> {
                Type = TrendType.Available
            };

            List <Trend> trendList = trendReqProc.ProcessResults(TestAvailableOrClosestQueryResponse);

            Assert.IsNotNull(trendList);
            Trend trends = trendList.SingleOrDefault();

            Assert.IsNotNull(trends);
            List <Location> locations = trends.Locations;

            Assert.IsNotNull(locations);
            Assert.AreEqual(2, locations.Count);
            Location location = locations[0];

            Assert.AreEqual("Country", location.PlaceTypeName);
            Assert.AreEqual(12, location.PlaceTypeNameCode);
            Assert.AreEqual("Turkey", location.Name);
            Assert.AreEqual("http://where.yahooapis.com/v1/place/23424969", location.Url);
            Assert.AreEqual(23424969, location.WoeID);
            Assert.AreEqual("TR", location.CountryCode);
            Assert.AreEqual("1", location.ParentID);
            Assert.AreEqual("Turkey", location.Country);
        }
Exemplo n.º 28
0
        public void ProcessResults_Handles_Closest()
        {
            var trendReqProc = new TrendRequestProcessor <Trend> {
                Type = TrendType.Closest
            };

            List <Trend> trendList = trendReqProc.ProcessResults(TestAvailableOrClosestQueryResponse);

            Assert.IsNotNull(trendList);
            Trend trends = trendList.SingleOrDefault();

            Assert.IsNotNull(trends);
            List <Location> locations = trends.Locations;

            Assert.IsNotNull(locations);
            Assert.AreEqual(2, locations.Count);
            Location location = locations[1];

            Assert.IsNotNull(location);
            Assert.AreEqual("Town", location.PlaceTypeName);
            Assert.AreEqual(7, location.PlaceTypeNameCode);
            Assert.AreEqual("Birmingham", location.Name);
            Assert.AreEqual("http://where.yahooapis.com/v1/place/2364559", location.Url);
            Assert.AreEqual(2364559, location.WoeID);
            Assert.AreEqual("US", location.CountryCode);
            Assert.AreEqual("23424977", location.ParentID);
            Assert.AreEqual("United States", location.Country);
        }
Exemplo n.º 29
0
        public void ProcessResults_Parses_Location()
        {
            var trendProc = new TrendRequestProcessor <Trend> {
                Type = TrendType.Place
            };

            List <Trend> trendList = trendProc.ProcessResults(TestTrendQueryResponse);

            Assert.IsNotNull(trendList);
            Trend trends = trendList.FirstOrDefault();

            Assert.IsNotNull(trends);
            List <Location> locations = trends.Locations;

            Assert.IsNotNull(locations);
            Assert.AreEqual(1, locations.Count);
            Location location = locations[0];

            Assert.AreEqual("Worldwide", location.Name);
            Assert.AreEqual(1, location.WoeID);
            Assert.AreEqual(3700, trends.TweetVolume);
            Assert.AreEqual("%22Julianna%20Margulies%22", trends.Query);
            Assert.AreEqual("Julianna Margulies", trends.Name);
            Assert.IsNull(trends.PromotedContent);
            Assert.AreEqual("http://twitter.com/search/%22Julianna%20Margulies%22", trends.SearchUrl);
            Assert.IsNull(trends.Events);
            Assert.AreEqual(new DateTime(2011, 9, 19, 2, 4, 39), trends.AsOf);
            Assert.AreEqual(new DateTime(2011, 9, 19, 2, 0, 17), trends.CreatedAt);
        }
Exemplo n.º 30
0
 public Schema()
     : base()
 {
     InstanceType = typeof(__Franchis__);
     Properties.ClearExposed();
     Name = Add <__TString__>("Name$");
     Name.DefaultValue = "";
     Name.Editable     = true;
     Name.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__Name__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__Name__ = (System.String)_v_; }, false);
     SoldHomes = Add <__TString__>("SoldHomes");
     SoldHomes.DefaultValue = "";
     SoldHomes.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__SoldHomes__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__SoldHomes__ = (System.String)_v_; }, false);
     TotalComission = Add <__TString__>("TotalComission");
     TotalComission.DefaultValue = "";
     TotalComission.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__TotalComission__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__TotalComission__ = (System.String)_v_; }, false);
     AvgComission = Add <__TString__>("AvgComission");
     AvgComission.DefaultValue = "";
     AvgComission.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__AvgComission__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__AvgComission__ = (System.String)_v_; }, false);
     Trend = Add <__TString__>("Trend");
     Trend.DefaultValue = "";
     Trend.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__Trend__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__Trend__ = (System.String)_v_; }, false);
     AddTrigger = Add <__TString__>("AddTrigger$");
     AddTrigger.DefaultValue = "";
     AddTrigger.Editable     = true;
     AddTrigger.SetCustomAccessors((_p_) => { return(((__Franchis__)_p_).__bf__AddTrigger__); }, (_p_, _v_) => { ((__Franchis__)_p_).__bf__AddTrigger__ = (System.String)_v_; }, false);
     AddTrigger.AddHandler((Json pup, Property <String> prop, String value) => { return(new Input.AddTrigger()
         {
             App = (FranchiseOfficeListJson)pup, Template = (TString)prop, Value = value
         }); }, (Json pup, Starcounter.Input <String> input) => { ((FranchiseOfficeListJson)pup).Handle((Input.AddTrigger)input); });
 }
Exemplo n.º 31
0
 public MACDIndicator(int shortEMAPeriod, int longEMAPeriod, int signalPeriod, double buyThreshold, double sellThreshold)
 {
     _shortEMAPeriod = shortEMAPeriod;
     _longEMAPeriod = longEMAPeriod;
     _buyThreshold = buyThreshold;
     _sellThreshold = sellThreshold;
     _signalPeriod = signalPeriod;
     _trend = new Trend { Direction = TrendDirection.None };
 }
Exemplo n.º 32
0
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            if(upperChannel==0.0) {
                upperChannel = Close[0]+channelTicks*this.TickSize;
                lowerChannel = Close[0]-channelTicks*this.TickSize;
            }

            // default background
            backColor = Color.White;

            // Set initial trend.
            if(trend==Trend.None) {
                if(Close[1] > upperChannel) {
                    trend=Trend.Up;
                }
                if(Close[1] < lowerChannel) {
                    trend=Trend.Down;
                }
            }

            if(trend==Trend.Up) {
                if(Close[1] < lowerChannel) {
                    DrawArrowDown("Down"+CurrentBar.ToString(),true,0,Close[1],Color.Crimson);
                    trend=Trend.Down;
                    upperChannel=Close[1]+channelTicks*this.TickSize;
                } else if(Close[1]-channelTicks*this.TickSize > lowerChannel) {
                    lowerChannel = Close[1]-channelTicks*this.TickSize;
                    DrawDot("Lower"+CurrentBar.ToString(),true,0,lowerChannel,Color.Crimson);
                }
            }
            if(trend==Trend.Down) {
                if(Close[1] > upperChannel) {
                    DrawArrowUp("Up"+CurrentBar.ToString(),true,0,Close[1],Color.Lime);
                    trend=Trend.Up;
                    lowerChannel=Close[1]-channelTicks*this.TickSize;
                } else if(Close[1]+channelTicks*this.TickSize < upperChannel) {
                    upperChannel = Close[1]+channelTicks*this.TickSize;
                    DrawDot("Upper"+CurrentBar.ToString(),true,0,upperChannel,Color.Lime);
                }
            }

            BackColor = backColor;
            BarColor = barColor;

            // Debug Message to the Output Window
            if(outMsg != "") {
                this.PrintWithTimeStamp(outMsg);
            }
        }
Exemplo n.º 33
0
        public static MarketStepReturn MarketStep(MarketStepInput input)
        {
            Trend calcTrend = new Trend();
            calcTrend = TrendCalc(input.mid, input.curTrend, input.curLowThreshold, input.curHighThreshold);

            Threshold calcThreshold = new Threshold();
            calcThreshold = ThresholdCalc(calcTrend, input.mid, input.percent, input.curLowThreshold, input.curHighThreshold);

            string calcEventText = EventText(calcTrend, calcThreshold);

            MarketStepReturn outValue = new MarketStepReturn()
            {
                percent = input.percent,
                newTrend = calcTrend.newTrend,
                newLowThreshold = calcThreshold.newLowThreshold,
                newHighThreshold = calcThreshold.newHighThreshold,
                trendOvershoot = calcTrend.trendOvershoot,
                trendReversal = calcTrend.trendReversal,
                eventText = calcEventText
            };
            return outValue;
        }
Exemplo n.º 34
0
        public static string EventText(Trend uTrend, Threshold uThresholds)
        {
            string retString = "";

            if (NoTrendEvent(uTrend))
            {
                retString = "NO EVENT";
            }
            else if (uTrend.trendOvershoot == iTRUE)
            {
                if (uTrend.newTrend == iTREND_UP)
                {
                    retString = "TREND: UP OVERSHOOT NLOW: " + uThresholds.newLowThreshold + " NHIGH: " + uThresholds.newHighThreshold;
                }
                else
                {
                    retString = "TREND: DOWN OVERSHOOT NLOW: " + uThresholds.newLowThreshold + " NHIGH: " + uThresholds.newHighThreshold;
                }

            }
            else if (uTrend.trendReversal == iTRUE)
            {
                if (uTrend.newTrend == iTREND_UP)
                {
                    retString = "REVERSAL NEW TREND: UP OVERSHOOT NLOW: " + uThresholds.newLowThreshold + " NHIGH: " + uThresholds.newHighThreshold;
                }
                else
                {
                    retString = "REVERSAL NEW TREND: DOWN OVERSHOOT NLOW: " + uThresholds.newLowThreshold + " NHIGH: " + uThresholds.newHighThreshold;
                }
            }
            else
            {
                retString = "ERROR INVALID STATE";
            }
            return retString;
        }
Exemplo n.º 35
0
        /// <summary>
        /// �������� (�����������) ������ ��� ������ ������� �� SCADA-��������
        /// ��� ��������� ����� �������� ���������� �� SCADA-��������
        /// </summary>
        private void RefrServerComm()
        {
            if (settFileName != "")
            {
                DateTime dateTime = GetLastWriteTime(settFileName);
                if (dateTime > DateTime.MinValue && dateTime != settModTime)
                {
                    settModTime = dateTime;
                    CommSettings commSettings = new CommSettings();
                    commSettings.LoadFromFile(settFileName, AppData.Log);
                    if (serverComm == null || !serverComm.CommSettings.Equals(commSettings))
                    {
                        if (serverComm != null)
                        {
                            serverComm.Close();

                            tblCur = new SrezTableLight();
                            for (int i = 0; i < HourCacheSize; i++)
                                hourTableCache[i] = null;
                            for (int i = 0; i < EventCacheSize; i++)
                                eventTableCache[i] = null;
                            hourTableIndex = 0;
                            eventTableIndex = 0;
                            trend = null;

                            baseModTime = DateTime.MinValue;
                            baseFillTime = DateTime.MinValue;
                        }
                        serverComm = new ServerComm(commSettings);
                    }
                }
            }
        }
Exemplo n.º 36
0
 public static bool NoTrendEvent(Trend inTrend)
 {
     return (inTrend.trendOvershoot == iFALSE && inTrend.trendReversal == iFALSE);
 }
 private void CalculateTrend()
 {
     Trend = new Trend(LastWeight, TodaysWeight);
 }
Exemplo n.º 38
0
        public static Threshold ThresholdCalc(Trend uNewTrend, double curMid, double curPercent, double curLowThreshold, double curHighThreshold)
        {
            Threshold retThreshold = new Threshold();

            if (NoTrendEvent(uNewTrend))
            {
                if (uNewTrend.newTrend == iTREND_UP)
                {
                    retThreshold.newHighThreshold = curHighThreshold;
                    retThreshold.newLowThreshold = Math.Max(curLowThreshold, curMid * (1 - curPercent));
                }
                else  // this is newtrend == trend_down
                {
                    retThreshold.newLowThreshold = curLowThreshold;
                    retThreshold.newHighThreshold = Math.Min(curHighThreshold, curMid * (1 + curPercent));
                }
            }
            else
            {
                retThreshold.newLowThreshold = curMid * (1 - curPercent);
                retThreshold.newHighThreshold = curMid * (1 + curPercent);
            }
            return retThreshold;
        }
Exemplo n.º 39
0
 /// <summary>
 /// Заполнить тренд trend канала cnlNum из файла или потока
 /// </summary>
 public void Fill(Trend trend)
 {
     FillObj(trend);
 }
Exemplo n.º 40
0
 public static Trend TrendCalc(double mid, int curTrend, double lowThres, double highThres)
 {
     Trend retTrend = new Trend
     {
         trendOvershoot = iFALSE,
         trendReversal = iFALSE
     };
     if( (mid > highThres) && (curTrend == iTREND_UP) )
     {
         retTrend.trendOvershoot = iTRUE;
         retTrend.newTrend = curTrend;
     }
     else if ((mid > highThres) && (curTrend == iTREND_DOWN))
     {
         retTrend.trendReversal = iTRUE;
         retTrend.newTrend = iTREND_UP;
     }
     else if ((mid < lowThres) && (curTrend == iTREND_DOWN))
     {
         retTrend.trendOvershoot = iTRUE;
         retTrend.newTrend = curTrend;
     }
     else if ((mid < lowThres) && (curTrend == iTREND_UP))
     {
         retTrend.trendReversal = iTRUE;
         retTrend.newTrend = iTREND_DOWN;
     }
     else
     {
         retTrend.newTrend = curTrend;
     }
     return retTrend;
 }
Exemplo n.º 41
0
 /// <summary>
 /// �������� ������ ������ ��������� ����� �� �����
 /// </summary>
 public Trend GetMinData(int cnlNum, DateTime date)
 {
     Monitor.Enter(cnlDataLock);
     try
     {
         string minTableName = "m" + date.ToString("yyMMdd") + ".dat";
         if (trend == null || trend.CnlNum != cnlNum || trend.TableName != minTableName)
         {
             trend = new Trend(cnlNum);
             trend.FileModTime = serverComm.ReceiveTrend(minTableName, date, trend) ?
                 serverComm.ReceiveFileAge(ServerComm.Dirs.Min, minTableName) : DateTime.MinValue;
         }
         else
         {
             DateTime minModTime = serverComm.ReceiveFileAge(ServerComm.Dirs.Min, minTableName);
             if ((DateTime.Now - minModTime).TotalSeconds > MinSrezValidTime /*������ ��������*/ &&
                 minModTime != trend.FileModTime /*���� ������ ������*/)
             {
                 trend = new Trend(cnlNum);
                 trend.FileModTime = serverComm.ReceiveTrend(minTableName, date, trend) ?
                     minModTime : DateTime.MinValue;
             }
         }
         return trend;
     }
     finally
     {
         Monitor.Exit(cnlDataLock);
     }
 }
        public void process()
        {
            if (movements.Count < 2)
                return;

            if (movements.Count == 2)
                return; //todo later

            Console.WriteLine("********Here*********");
            foreach (var movement in movements)
            {
                Console.WriteLine(movement.Value + "    " + movement.Position.ToString());
            }

            var start = movements[0];

            this.movementTrend = start.Value < this.movements[1].Value ? Trend.Out : Trend.In;

            var lastVal = this.movements[1].Value;
            for (int i = 2; i < this.movements.Count; i++)
            {
                var movement = this.movements[i];

                switch (movementTrend)
                {
                    case Trend.In:
                        if (lastVal <= movement.Value)
                        {
                            TimeSpan span = movement.Position - start.Position;
                            if (span.TotalMilliseconds < 100)
                                break;

                            var startInMilli = start.Position.TotalMilliseconds;

                            HapticEvent evt = new HapticEvent();
                            evt.Start = (int)startInMilli;
                            evt.Duration = (int)span.TotalMilliseconds;
                            evt.Magnitude = 200;
                            evt.Direction = HapticEvent.DirectionType.In;

                            start = movements[i];

                            AppViewModel.DataViewModel.TopAxisData.AddNewEvent(evt);

                            if (i != movements.Count)
                            {
                                for (int j = i; j < movements.Count; j++ )
                                {
                                    if (!nearlyEqual((float)start.Value, (float)this.movements[j].Value, 0.00001f))
                                    {
                                        this.movementTrend = start.Value < this.movements[j].Value ? Trend.Out : Trend.In;
                                    }
                                }
                            }
                        }
                        break;
                    case Trend.Out:
                        if (lastVal >= movement.Value)
                        {
                            TimeSpan span = movement.Position - start.Position;

                            if (span.TotalMilliseconds < 100)
                                break;

                            var startInMilli = start.Position.TotalMilliseconds;

                            HapticEvent evt = new HapticEvent();
                            evt.Start = (int)startInMilli;
                            evt.Duration = (int)span.TotalMilliseconds;
                            evt.Magnitude = 200;
                            evt.Direction = HapticEvent.DirectionType.Out;

                            start = movements[i];

                            AppViewModel.DataViewModel.TopAxisData.AddNewEvent(evt);

                            if (i != movements.Count)
                            {
                                for (int j = i; j < movements.Count; j++)
                                {
                                    if (!nearlyEqual((float)start.Value, (float)this.movements[j].Value, 0.00001f))
                                    {
                                        this.movementTrend = start.Value < this.movements[j].Value ? Trend.Out : Trend.In;
                                    }
                                }
                            }
                        }
                        break;
                }
                lastVal = movement.Value;
            }

            movements.Clear();
        }
        /// <summary>
        /// Metoda testująca znalezioną najlepszą sieć neuronową.
        /// </summary>
        public void TestNet()
        {
            StringReader reader;

            try
            {
                reader = new StringReader(File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\networks\\LowestMSENetwork.xml"));
            }
            catch
            {
                return;
            }
            XmlSerializer serializer = new XmlSerializer(typeof(NetworkMSE));
            NetworkMSE lowesMSE = (NetworkMSE)serializer.Deserialize(reader);
            NeuralNet net = new NeuralNet();
            if (!net.CreateFromFile("networks\\" + lowesMSE.NetworkFileName))
            {
                return;
            }
            uint numberOfInputs = net.GetNumInput();
            uint numberOfPeriods = (numberOfInputs + 1) / 2;
            DateTime date = new DateTime(2009, 12, 13);
            DateTime iterationDate = date;
            date = DataProvider.Instance.GetNextExchangeQuotationDate(date, 0);
            DateTime endDate = new DateTime(2011, 12 , 13);
            Trend up = new Trend(), down = new Trend(), side = new Trend();
            int predictionDownCount = 0;
            int predictionSidewaysCount = 0;
            int predictionUpCount = 0;
            int predictionDownTrue = 0;
            int predictionSidewaysTrue = 0;
            int predictionUpTrue = 0;
            while (date <= endDate)
            {
                List<ExchangePeriod> periods = DataProvider.Instance.GetExchangePeriodsMergedByMovementDirectoryFromEndDate((int)numberOfPeriods, date, this.firstExchangeQuotationDate, 1);
                List<ExchangePeriod> testPeriods = DataProvider.Instance.GetExchangePeriodsMergedByMovementDirectoryFromStartDate((int)numberOfPeriods, DataProvider.Instance.GetNextExchangeQuotationDate(DateTime.Now, 0), date, 1);
                TrendDirection truTrend = GetTrendDirection(testPeriods, 0);
                double[] inputs = new double[numberOfInputs];
                for (int i = 0; i < numberOfPeriods; i += 2)
                {
                    inputs[i] = periods[i].PercentageChange;
                    if (i + 1 < periods.Count)
                    {
                        inputs[i + 1] = (periods[i + 1].PublicTrading - periods[i].PublicTrading) / periods[i].PublicTrading;
                    }
                }
                double[] result = net.Run(inputs);
                double sum = 0;
                foreach (double r in result)
                {
                    if (r > 0)
                    {
                        sum += r;
                    }
                }

                for (int i = 0; i < result.Length; i++)
                {
                    TrendDirectionWithPropability td = new TrendDirectionWithPropability();
                    if (result[i] > 0)
                    {
                        result[i] = result[i] * 100 / sum;
                    }
                    else
                    {
                        result[i] = 0;
                    }
                }

                switch (result.ToList().IndexOf(result.Max()))
                {
                    case 0:
                        predictionDownCount++;
                        if (truTrend == TrendDirection.Down)
                        {
                            predictionDownTrue++;
                        }
                        break;
                    case 1:
                        predictionSidewaysCount++;
                        if (truTrend == TrendDirection.Sideways)
                        {
                            predictionSidewaysTrue++;
                        }
                        break;
                    case 2:
                        predictionUpCount++;
                        if (truTrend == TrendDirection.Up)
                        {
                            predictionUpTrue++;
                        }
                        break;
                }

                switch (truTrend)
                {
                    case TrendDirection.Down:
                        down.count++;
                        down.avgDown += result[0];
                        down.avgSide += result[1];
                        down.avgUp += result[2];
                        break;
                    case TrendDirection.Sideways:
                        side.count++;
                        side.avgDown += result[0];
                        side.avgSide += result[1];
                        side.avgUp += result[2];
                        break;
                    case TrendDirection.Up:
                        up.count++;
                        up.avgDown += result[0];
                        up.avgSide += result[1];
                        up.avgUp += result[2];
                        break;
                }

              //  iterationDate = iterationDate.AddDays(7);
              //  date = DataProvider.Instance.GetNextExchangeQuotationDate(iterationDate, 0);
                date = DataProvider.Instance.GetNextExchangeQuotationDate(date, 1);
            }
            down.avgUp = down.avgUp/(double) down.count;
            down.avgDown = down.avgDown/(double) down.count;
            down.avgSide = down.avgSide / (double)down.count;
            up.avgUp = up.avgUp / (double)up.count;
            up.avgDown = up.avgDown / (double)up.count;
            up.avgSide = up.avgSide / (double)up.count;
            side.avgUp = side.avgUp / (double)side.count;
            side.avgDown = side.avgDown / (double)side.count;
            side.avgSide = side.avgSide / (double)side.count;
            List<string> fileContent = new List<string>();
            fileContent.Add("Trend Name \t Sample Count \t Up \t Side \t Down ");
            fileContent.Add(TrendDirection.Up.ToString() + " \t " + up.count.ToString() + " \t " + up.avgUp.ToString() + " \t " + up.avgSide.ToString() + " \t " + up.avgDown.ToString());
            fileContent.Add(TrendDirection.Sideways.ToString() + " \t " + side.count.ToString() + " \t " + side.avgUp.ToString() + " \t " + side.avgSide.ToString() + " \t " + side.avgDown.ToString());
            fileContent.Add(TrendDirection.Down.ToString() + " \t " + down.count.ToString() + " \t " + down.avgUp.ToString() + " \t " + down.avgSide.ToString() + " \t " + down.avgDown.ToString());
            fileContent.Add("");
            fileContent.Add(TrendDirection.Up.ToString() + " \t " + (predictionUpTrue/(double)predictionUpCount).ToString());
            fileContent.Add(TrendDirection.Sideways.ToString() + " \t " + (predictionSidewaysTrue / (double)predictionSidewaysCount).ToString());
            fileContent.Add(TrendDirection.Down.ToString() + " \t " + (predictionDownTrue / (double)predictionDownCount).ToString());
            fileContent.Add("");
            File.AppendAllLines(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\test result.txt", fileContent);
        }
Exemplo n.º 44
0
        public static void Update(Skeleton skel, double ts)
        {
            if (null == GestureTracker.last_hand_r)
            {
                GestureTracker.last_hand_r = skel.Joints[JointType.HandRight].Position;
                GestureTracker.last_ts = ts;
                Reset();
                return;
            }

            SkeletonPoint hand_r = skel.Joints[JointType.HandRight].Position;
            SkeletonPoint elbow_r = skel.Joints[JointType.ElbowRight].Position;

            //right hand moving upward
            if (hand_r.Y > last_hand_r.Y)
            {
                double velocity = Dist(hand_r, last_hand_r) / (ts - last_ts);
                //System.Diagnostics.Debug.WriteLine(ts+"~"+last_ts+":"+velocity);

                if (GestureTracker.trend == Trend.Up && velocity>0.003)
                {
                    GestureTracker.counter++;
                }
                else
                {
                    Reset();
                    GestureTracker.trend = Trend.Up;
                }
            }
            //right hand moving downward
            else if (hand_r.Y < last_hand_r.Y)
            {
                double velocity = Dist(hand_r, last_hand_r) / (ts - last_ts);
                //System.Diagnostics.Debug.WriteLine(dist);
                if (GestureTracker.trend == Trend.Down && velocity > 0.003)
                {
                    GestureTracker.counter++;
                }
                else
                {
                    Reset();
                    GestureTracker.trend = Trend.Down;
                }
            }
            else
            {
                Reset();
            }

            GestureTracker.last_hand_r = hand_r;
            GestureTracker.last_ts = ts;
        }
 private void figureMovementTrend()
 {
     for (int j = 0; j < movements.Count; j++)
     {
         if (!nearlyEqual((float)this.movements[0].Value, (float)this.movements[j].Value, 0.00001f))
         {
             this.movementTrend = this.movements[0].Value < this.movements[j].Value ? Trend.Out : Trend.In;
             break;
         }
     }
 }
Exemplo n.º 46
0
        public Advice GetAdvice(IList<OHLC> candles)
        {
            var shortMA = Analysis.MovingAverages.CalculateEMA(candles, _shortEMAPeriod);
            var longMA = Analysis.MovingAverages.CalculateEMA(candles, _longEMAPeriod);


            if (shortMA == null || longMA == null)
            {
                return Advice.None;
            }

            int firstIndex = _longEMAPeriod - 1;
            if (candles.Count < _longEMAPeriod + _signalPeriod - 1)
            {
                return Advice.None;
            }

            int i = candles.Count - 1;

            var emaDiff = new OHLC[i - firstIndex + 1];
            for (int k = firstIndex; k <= i; k++)
            {
                emaDiff[k - firstIndex] = new OHLC
                    {
                        Close = (decimal)shortMA.Output[k - shortMA.Begin] - (decimal)longMA.Output[k - longMA.Begin]
                    };
            }

            var signal = Analysis.MovingAverages.CalculateEMA(emaDiff, _signalPeriod);
            if (signal == null)
            {
                return Advice.None;
            }

            var macdDiff = shortMA.Output[i - shortMA.Begin] - longMA.Output[i - longMA.Begin] - signal.Output[i - firstIndex - signal.Begin];


            if (macdDiff > 0.025/* settings.thresholds.up*/)
            {

                // new trend detected
                if (this._trend.Direction != TrendDirection.Up)
                    // reset the state for the new trend
                    this._trend = new Trend
                    {
                        Duration = 0,
                        Persisted = false,
                        Direction = TrendDirection.Up,
                        Adviced = false
                    };

                this._trend.Duration++;

                //log.debug('In uptrend since', this.trend.duration, 'candle(s)');

                if (this._trend.Duration >= 1/*settings.thresholds.persistence*/)
                    this._trend.Persisted = true;

                if (this._trend.Persisted && !this._trend.Adviced)
                {
                    this._trend.Adviced = true;
                    return Advice.Buy;
                }
                else return Advice.None;

            }
            else if (macdDiff < -0.025/* settings.thresholds.down*/)
            {

                // new trend detected
                if (this._trend.Direction != TrendDirection.Down)
                    // reset the state for the new trend
                    this._trend = new Trend
                    {
                        Duration = 0,
                        Persisted = false,
                        Direction = TrendDirection.Down,
                        Adviced = false
                    };

                this._trend.Duration++;

                //log.debug('In downtrend since', this.trend.duration, 'candle(s)');

                if (this._trend.Duration >= 1/*settings.thresholds.persistence*/)
                {
                    this._trend.Persisted = true;
                }

                if (this._trend.Persisted && !this._trend.Adviced)
                {
                    this._trend.Adviced = true;
                    return Advice.Sell;
                }
                else
                    return Advice.None;

            }
            else
            {
                return Advice.None;
            }

        }
Exemplo n.º 47
0
        private Trend trend; // ��������� ���������� �������� �����

        #endregion Fields

        #region Constructors

        /// <summary>
        /// �����������
        /// </summary>
        public MainData()
        {
            serverComm = null;
            settFileName = "";
            settModTime = DateTime.MinValue;

            tblCur = new SrezTableLight();
            hourTableCache = new SrezTableLight[HourCacheSize];
            eventTableCache = new EventTableLight[EventCacheSize];
            for (int i = 0; i < HourCacheSize; i++)
                hourTableCache[i] = null;
            for (int i = 0; i < EventCacheSize; i++)
                eventTableCache[i] = null;
            hourTableIndex = 0;
            eventTableIndex = 0;
            trend = null;
            nfi = new NumberFormatInfo();
            defDecSep = Localization.Culture.NumberFormat.NumberDecimalSeparator;
            defGrSep = Localization.Culture.NumberFormat.NumberGroupSeparator;

            baseModTime = DateTime.MinValue;
            baseFillTime = DateTime.MinValue;
            tblInCnl = new DataTable("InCnl");
            tblCtrlCnl = new DataTable("CtrlCnl");
            tblObj = new DataTable("Obj");
            tblKP = new DataTable("KP");
            tblRole = new DataTable("Role");
            tblUser = new DataTable("User");
            tblInterface = new DataTable("Interface");
            tblRight = new DataTable("Right");
            tblEvType = new DataTable("EvType");
            tblParam = new DataTable("Param");
            tblUnit = new DataTable("Unit");
            tblCmdVal = new DataTable("CmdVal");
            tblFormat = new DataTable("Format");

            baseTblArr = new DataTable[13];
            baseTblArr[0] = tblInCnl;
            baseTblArr[1] = tblCtrlCnl;
            baseTblArr[2] = tblObj;
            baseTblArr[3] = tblKP;
            baseTblArr[4] = tblRole;
            baseTblArr[5] = tblUser;
            baseTblArr[6] = tblInterface;
            baseTblArr[7] = tblRight;
            baseTblArr[8] = tblEvType;
            baseTblArr[9] = tblParam;
            baseTblArr[10] = tblUnit;
            baseTblArr[11] = tblCmdVal;
            baseTblArr[12] = tblFormat;

            cnlPropsArr = null;
            maxCnlCnt = 0;

            refrLock = new Object();
            baseLock = new Object();
            cnlPropLock = new Object();
            cnlDataLock = new Object();
            eventLock = new Object();
        }
Exemplo n.º 48
0
		private void CalculateKagiBar(Bars bars, double o, double h, double l, double c, DateTime barTime, long volume, bool isRealtime)
		{
			switch (trend)
			{
				case Trend.Up:
					if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice - reversalPoint) <= 0)
					{
						AddBar(bars, anchorPrice, anchorPrice, bars.LastPrice, bars.LastPrice, barTime, volumeCount, isRealtime);
						anchorPrice		= bars.LastPrice;
						trend			= Trend.Down;
					}
					else if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice) > 0)
					{
						UpdateBar(bars, o, bars.LastPrice, l, bars.LastPrice, barTime, volumeCount, isRealtime);
						anchorPrice = bars.LastPrice;
					}
					else
						UpdateBar(bars, o, h, l, c, barTime, volumeCount, isRealtime);
					break;
				case Trend.Down:
					if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice + reversalPoint) >= 0)
					{
						AddBar(bars, anchorPrice, bars.LastPrice, anchorPrice, bars.LastPrice, barTime, volumeCount, isRealtime);
						anchorPrice = bars.LastPrice;
						trend = Trend.Up;
					}
					else if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice) < 0)
					{
						UpdateBar(bars, o, h, bars.LastPrice, bars.LastPrice, barTime, volumeCount, isRealtime);
						anchorPrice = bars.LastPrice;
					}
					else
						UpdateBar(bars, o, h, l, c, barTime, volumeCount, isRealtime);
					break;
				default:
					UpdateBar(bars, o, bars.LastPrice, bars.LastPrice, bars.LastPrice, barTime, volumeCount, isRealtime);
					anchorPrice = bars.LastPrice;
					trend		= bars.Instrument.MasterInstrument.Compare(bars.LastPrice, o) < 0 ? Trend.Down
								: bars.Instrument.MasterInstrument.Compare(bars.LastPrice, o) > 0 ? Trend.Up : Trend.Undetermined;
					break;
			}
			volumeCount = volume;
		}
        public void Add(double val)
        {
            var m = new Movement
                        {
                            Value = val,
                            Position = AppViewModel.VideoViewModel.Position
                        };
            movements.Add(m);

            if (movements.Count<2)
                return;

            if (movementTrend == Trend.None)
                figureMovementTrend();

            if (movementTrend == Trend.None)
                return;

            if (movementTrend == Trend.In)
            {
                //value decreasing
                if (val > movements[movements.Count-2].Value)
                {
                    //changing trend
                    TimeSpan span = m.Position - movements[0].Position;
                    if (span.TotalMilliseconds < 100)
                        return;

                    var startInMilli = movements[0].Position.TotalMilliseconds;

                    HapticEvent evt = new HapticEvent();
                    evt.Start = (int)startInMilli;
                    evt.Duration = (int)span.TotalMilliseconds;
                    evt.Magnitude = 200;
                    evt.Direction = HapticEvent.DirectionType.In;

                    AppViewModel.DataViewModel.TopAxisData.AddNewEvent(evt);
                }
                else
                {
                    return;
                }
            }

            if (movementTrend == Trend.Out)
            {
                //value increasing
                if (val < movements[movements.Count - 2].Value)
                {
                    //changing trend
                    TimeSpan span = m.Position - movements[0].Position;
                    if (span.TotalMilliseconds < 100)
                        return;

                    var startInMilli = movements[0].Position.TotalMilliseconds;

                    HapticEvent evt = new HapticEvent();
                    evt.Start = (int)startInMilli;
                    evt.Duration = (int)span.TotalMilliseconds;
                    evt.Magnitude = 200;
                    evt.Direction = HapticEvent.DirectionType.Out;

                    AppViewModel.DataViewModel.TopAxisData.AddNewEvent(evt);
                }
                else
                {
                    return;
                }
            }

            movementTrend = Trend.None;
            movements.Clear();
        }
Exemplo n.º 50
0
		private void CalculatePfBar(Bars bars, double o, double h, double l, double c, DateTime barTime, DateTime tTime, bool isRealtime)
		{
			if (bars.Period.PointAndFigurePriceType == PointAndFigurePriceType.Close)
			{
				switch (trend)
				{
					case Trend.Up:
						if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice - reversalSize) <= 0)
						{
							double newHigh	= anchorPrice - boxSize;
							double newLow	= anchorPrice - reversalSize;
							while (bars.Instrument.MasterInstrument.Compare(newLow - boxSize, bars.LastPrice) >= 0) newLow -= boxSize;
							newHigh			= bars.Instrument.MasterInstrument.Round2TickSize(newHigh);
							newLow			= bars.Instrument.MasterInstrument.Round2TickSize(newLow);
							anchorPrice		= newLow;
							trend			= Trend.Down;
							AddBar(bars, newHigh, newHigh, newLow, newLow, barTime, volumeCount, isRealtime);
						}
						else
							if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice + boxSize) >= 0)
							{
								double newHigh	= anchorPrice + boxSize;
								while (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, newHigh + boxSize) >= 0) newHigh += boxSize;
								newHigh			= bars.Instrument.MasterInstrument.Round2TickSize(newHigh);
								anchorPrice		= newHigh;
								UpdateBar(bars, o, newHigh, l, newHigh, barTime, volumeCount, isRealtime);
							}
							else
								UpdateBar(bars, o, h, l, c, barTime, volumeCount, isRealtime);
						break;
					case Trend.Down:
						if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice + reversalSize) >= 0)
						{
							double newLow	= anchorPrice + boxSize;
							double newHigh	= anchorPrice + reversalSize;
							while (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, newHigh + boxSize) >= 0) newHigh += boxSize;
							newHigh			= bars.Instrument.MasterInstrument.Round2TickSize(newHigh);
							newLow			= bars.Instrument.MasterInstrument.Round2TickSize(newLow);
							anchorPrice		= newHigh;
							trend			= Trend.Up;
							AddBar(bars, newLow, newHigh, newLow, newHigh, barTime, volumeCount, isRealtime);
						}
						else
							if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice - boxSize) <= 0)
							{
								double newLow	= anchorPrice - boxSize;
								while (bars.Instrument.MasterInstrument.Compare(newLow - boxSize, bars.LastPrice) >= 0) newLow -= boxSize;
								newLow			= bars.Instrument.MasterInstrument.Round2TickSize(newLow);
								anchorPrice		= newLow;
								UpdateBar(bars, o, h, newLow, newLow, barTime, volumeCount, isRealtime);
							}
							else
								UpdateBar(bars, o, h, l, c, barTime, volumeCount, isRealtime);
						break;
					default:
						if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice + boxSize) >= 0)
						{
							double newHigh	= anchorPrice + boxSize;
							while (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, newHigh + boxSize) >= 0) newHigh += boxSize;
							newHigh			= bars.Instrument.MasterInstrument.Round2TickSize(newHigh);
							anchorPrice		= newHigh;
							trend			= Trend.Up;
							UpdateBar(bars, o, newHigh, l, newHigh, barTime, volumeCount, isRealtime);
						}
						else
							if (bars.Instrument.MasterInstrument.Compare(anchorPrice - boxSize, bars.LastPrice) >= 0)
							{
								double newLow	= anchorPrice - boxSize;
								while (bars.Instrument.MasterInstrument.Compare(newLow - boxSize, bars.LastPrice) >= 0) newLow -= boxSize;
								newLow			= bars.Instrument.MasterInstrument.Round2TickSize(newLow);
								anchorPrice		= newLow;
								trend			= Trend.Down;
								UpdateBar(bars, o, h, newLow, newLow, barTime, volumeCount, isRealtime);
							}
							else
								UpdateBar(bars, anchorPrice, anchorPrice, anchorPrice, anchorPrice, barTime, volumeCount, isRealtime);
						break;
				}
			}
			else
			{
				switch (trend)
				{
					case Trend.Up:
						bool updatedUp = false;
						if (bars.Instrument.MasterInstrument.Compare(tmpHigh, anchorPrice + boxSize) >= 0)
						{
							double newHigh	= anchorPrice;
							while (bars.Instrument.MasterInstrument.Compare(tmpHigh, newHigh + boxSize) >= 0) newHigh += boxSize;
							newHigh			= bars.Instrument.MasterInstrument.Round2TickSize(newHigh);
							updatedUp		= true;
							anchorPrice		= newHigh;
							long vol		= bars.Instrument.MasterInstrument.Compare(anchorPrice - reversalSize, tmpLow) >= 0 ? 0 : volumeCount;
							DateTime tt		= bars.Instrument.MasterInstrument.Compare(anchorPrice - reversalSize, tmpLow) >= 0 ? tTime : barTime;
							UpdateBar(bars, o, newHigh, l, newHigh, tt, vol, isRealtime);
						}
						if (bars.Instrument.MasterInstrument.Compare(anchorPrice - reversalSize, tmpLow) >= 0)
						{
							double newHigh	= anchorPrice - boxSize;
							double newLow	= anchorPrice - reversalSize;
							while (bars.Instrument.MasterInstrument.Compare(newLow - boxSize, tmpLow) >= 0) newLow -= boxSize;
							newHigh			= bars.Instrument.MasterInstrument.Round2TickSize(newHigh);
							newLow			= bars.Instrument.MasterInstrument.Round2TickSize(newLow);
							updatedUp		= true;
							anchorPrice		= newLow;
							trend			= Trend.Down;
							AddBar(bars, newHigh, newHigh, newLow, newLow, barTime, volumeCount, isRealtime);
						}
						if (!updatedUp)
						{
							UpdateBar(bars, o, h, l, c, barTime, volumeCount, isRealtime);
							anchorPrice = h;
						}
						break;
					case Trend.Down:
						bool updatedDn = false;
						if (bars.Instrument.MasterInstrument.Compare(tmpLow, anchorPrice - boxSize) <= 0)
						{
							double newLow	= anchorPrice;
							while (bars.Instrument.MasterInstrument.Compare(newLow - boxSize, tmpLow) >= 0) newLow -= boxSize;
							newLow			= bars.Instrument.MasterInstrument.Round2TickSize(newLow);
							updatedDn		= true;
							anchorPrice		= newLow;
							long vol		= bars.Instrument.MasterInstrument.Compare(tmpHigh, anchorPrice + reversalSize) >= 0 ? 0 : volumeCount;
							DateTime tt		= bars.Instrument.MasterInstrument.Compare(anchorPrice - reversalSize, tmpLow) >= 0 ? tTime : barTime;
							UpdateBar(bars, o, h, newLow, newLow, tt, vol, isRealtime);
						}
						if (bars.Instrument.MasterInstrument.Compare(tmpHigh, anchorPrice + reversalSize) >= 0)
						{
							double newLow	= anchorPrice + boxSize;
							double newHigh	= anchorPrice + reversalSize;
							while (bars.Instrument.MasterInstrument.Compare(tmpHigh, newHigh + boxSize) >= 0) newHigh += boxSize;
							newHigh			= bars.Instrument.MasterInstrument.Round2TickSize(newHigh);
							newLow			= bars.Instrument.MasterInstrument.Round2TickSize(newLow);
							updatedDn		= true;
							anchorPrice		= newHigh;
							trend			= Trend.Up;
							AddBar(bars, newLow, newHigh, newLow, newHigh, barTime, volumeCount, isRealtime);
						}
						if (!updatedDn)
						{
							UpdateBar(bars, o, h, l, c, barTime, volumeCount, isRealtime);
							anchorPrice = l;
						}
						break;
					default:
						if (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, anchorPrice + boxSize) >= 0)
						{
							double newHigh	= anchorPrice + boxSize;
							while (bars.Instrument.MasterInstrument.Compare(bars.LastPrice, newHigh + boxSize) >= 0) newHigh += boxSize;
							newHigh			= bars.Instrument.MasterInstrument.Round2TickSize(newHigh);
							anchorPrice		= newHigh;
							trend			= Trend.Up;
							UpdateBar(bars, o, newHigh, l, newHigh, barTime, volumeCount, isRealtime);
						}
						else
							if (bars.Instrument.MasterInstrument.Compare(anchorPrice - boxSize, bars.LastPrice) >= 0)
							{
								double newLow	= anchorPrice - boxSize;
								while (bars.Instrument.MasterInstrument.Compare(newLow - boxSize, bars.LastPrice) >= 0) newLow -= boxSize;
								newLow			= bars.Instrument.MasterInstrument.Round2TickSize(newLow);
								anchorPrice		= newLow;
								trend			= Trend.Down;
								UpdateBar(bars, o, h, newLow, newLow, barTime, volumeCount, isRealtime);
							}
							else
								UpdateBar(bars, anchorPrice, anchorPrice, anchorPrice, anchorPrice, barTime, volumeCount, isRealtime);
						break;
				}
			}
		}
Exemplo n.º 51
0
 public static void Reset()
 {
     GestureTracker.counter = 0;
     GestureTracker.trend = Trend.Neutral;
 }
Exemplo n.º 52
0
 public void AddTrend(Trend newTrend, string decodedName, string username)
 {
     var theTrendReport = GetTrendReportByName(decodedName, username);
     theTrendReport.Trends.Add(newTrend);
     _context.Trends.Add(newTrend);
 }
Exemplo n.º 53
0
		/// <summary>
		/// </summary>
		/// <param name="bars"></param>
		/// <param name="open"></param>
		/// <param name="high"></param>
		/// <param name="low"></param>
		/// <param name="close"></param>
		/// <param name="time"></param>
		/// <param name="volume"></param>
		/// <param name="isRealtime"></param>
		public override void Add(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime)
		{
			#region Building Bars from Base Period
			if (bars.Count != tmpCount) // reset cache when bars are trimmed
				if (bars.Count == 0)
				{
					tmpTime			= Cbi.Globals.MinDate;
					tmpVolume		= 0;
					tmpDayCount		= 0;
					tmpTickCount	= 0;
				}
				else
				{
					tmpTime			= bars.GetTime(bars.Count - 1);
					tmpVolume		= bars.GetVolume(bars.Count - 1);
					tmpTickCount	= bars.TickCount;
					tmpDayCount		= bars.DayCount;
					bars.LastPrice	= bars.GetClose(bars.Count - 1);
					anchorPrice		= bars.LastPrice;
				}

			switch (bars.Period.BasePeriodType)
			{
				case PeriodType.Day:
					tmpTime = time.Date; // will be modified for realtime only
					if (isRealtime && time >= cacheSessionEnd /* on realtime include60 is always false */)
					{
						bars.Session.GetSessionDate(time, false, out tmpTime, out cacheSessionEnd);
						if (tmpTime < time.Date) tmpTime = time.Date; // make sure timestamps are ascending
					}

					if (prevTime != tmpTime) tmpDayCount++;

					if (tmpDayCount < bars.Period.BasePeriodValue
						|| (!isRealtime && bars.Count > 0 && tmpTime == bars.TimeLastBar.Date)
						|| (isRealtime && bars.Count > 0 && tmpTime <= bars.TimeLastBar.Date))
						endOfBar = false;
					else
					{
						prevTime = tmpTime;
						endOfBar = true;
					}

					break;

				case PeriodType.Minute:

					if (tmpTime == Cbi.Globals.MinDate)
						prevTime = tmpTime = TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime);

					if (!isRealtime && time <= tmpTime || isRealtime && time < tmpTime)
						endOfBar = false;
					else
					{
						prevTime	= tmpTime;
						tmpTime		= TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime);
						endOfBar	= true;
					}
					break;

				case PeriodType.Volume:
					if (tmpTime == Cbi.Globals.MinDate)
					{
						tmpVolume	= volume;
						endOfBar	= tmpVolume >= bars.Period.BasePeriodValue;
						prevTime	= tmpTime = time;
						if (endOfBar) tmpVolume = 0;
						break;
					}

					tmpVolume	+= volume;
					endOfBar	= tmpVolume >= bars.Period.BasePeriodValue;
					if (endOfBar)
					{
						prevTime	= tmpTime;
						tmpVolume	= 0;
					}
                    tmpTime = time;
                    break;

                case PeriodType.Tick:
                    if (tmpTime == Cbi.Globals.MinDate || bars.Period.BasePeriodValue == 1)
                    {
                        prevTime        = tmpTime == Cbi.Globals.MinDate ? time : tmpTime;
                        tmpTime         = time;
                        tmpTickCount    = bars.Period.BasePeriodValue == 1 ? 0 : 1;
                        endOfBar        = bars.Period.BasePeriodValue == 1;
                        break;
                    }

                    if (tmpTickCount < bars.Period.BasePeriodValue)
                    {
                        tmpTime         = time;
                        endOfBar        = false;
                        tmpTickCount++;
                    }
                    else
                    {
                        prevTime        = tmpTime;
                        tmpTime         = time;
                        endOfBar        = true;
                        tmpTickCount    = 1;
                    }
                    break;

                case PeriodType.Month:
					if (tmpTime == Cbi.Globals.MinDate)
						prevTime = tmpTime = TimeToBarTimeMonth(time, bars.Period.BasePeriodValue);

					if (time.Month <= tmpTime.Month && time.Year == tmpTime.Year || time.Year < tmpTime.Year)
						endOfBar = false;
					else
					{
						prevTime	= tmpTime;
						endOfBar	= true;
						tmpTime		= TimeToBarTimeMonth(time, bars.Period.BasePeriodValue);
					}
					break;

				case PeriodType.Second:
					if (tmpTime == Cbi.Globals.MinDate)
					{
						prevTime = tmpTime = TimeToBarTimeSecond(bars, time,
																	new DateTime(	bars.Session.NextBeginTime.Year,
																					bars.Session.NextBeginTime.Month,
																					bars.Session.NextBeginTime.Day,
																					bars.Session.NextBeginTime.Hour,
																					bars.Session.NextBeginTime.Minute, 0),
																	bars.Period.BasePeriodValue);
					}
					if ((bars.Period.Value > 1 && time < tmpTime) || (bars.Period.Value == 1 && time <= tmpTime))
						endOfBar	= false;
					else
					{
						prevTime	= tmpTime;
						tmpTime		= TimeToBarTimeSecond(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue);
						endOfBar	= true;
					}
					break;

				case PeriodType.Week:
					if (tmpTime == Cbi.Globals.MinDate)
						prevTime = tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue);
					if (time.Date <= tmpTime.Date)
						endOfBar = false;
					else
					{
						prevTime	= tmpTime;
						endOfBar	= true;
						tmpTime		= TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue);
					}
					break;

				case PeriodType.Year:
					if (tmpTime == Cbi.Globals.MinDate)
						prevTime = tmpTime = TimeToBarTimeYear(time, bars.Period.Value);
					if (time.Year <= tmpTime.Year)
						endOfBar = false;
					else
					{
						prevTime	= tmpTime;
						endOfBar	= true;
						tmpTime		= TimeToBarTimeYear(time, bars.Period.Value);
					}
					break;
			}
			#endregion
			#region Kagi Logic

			reversalPoint = bars.Period.ReversalType == ReversalType.Tick ? bars.Period.Value * bars.Instrument.MasterInstrument.TickSize : bars.Period.Value * 0.01 * anchorPrice;

			if (bars.Count == 0 || (IsIntraday && ((bars.Period.BasePeriodType != PeriodType.Second && bars.IsNewSession(time, isRealtime))
									|| (bars.Period.BasePeriodType == PeriodType.Second && bars.IsNewSession(tmpTime, isRealtime)))))
			{
				if (bars.Count > 0)
				{
					double		lastOpen		= bars.GetOpen(bars.Count - 1);
					double		lastHigh		= bars.GetHigh(bars.Count - 1);
					double		lastLow			= bars.GetLow(bars.Count - 1);
					double		lastClose		= bars.GetClose(bars.Count - 1);

					if (bars.Count == tmpCount)
						CalculateKagiBar(bars, lastOpen, lastHigh, lastLow, lastClose, prevTime, volume, isRealtime);
				}

				AddBar(bars, close, close, close, close, tmpTime, volume, isRealtime);
				anchorPrice		= close;
				trend			= Trend.Undetermined;
				prevTime		= tmpTime;
				volumeCount		= 0;
				bars.LastPrice	= close;
				tmpCount		= bars.Count;
				return;
			}

			Bar		bar		= (Bar)bars.Get(bars.Count - 1);
			double	c		= bar.Close;
			double	o		= bar.Open;
			double	h		= bar.High;
			double	l		= bar.Low;

			if (endOfBar)
				CalculateKagiBar(bars, o, h, l, c, prevTime, volume, isRealtime);
			else
				volumeCount += volume;

			bars.LastPrice	= close;
			tmpCount		= bars.Count;

			#endregion
		}
Exemplo n.º 54
0
        /// <summary>
        /// Принять тренд входного канала от SCADA-Сервера
        /// </summary>
        public bool ReceiveTrend(string tableName, DateTime date, Trend trend)
        {
            Monitor.Enter(tcpLock);
            bool result = false;
            errMsg = "";

            try
            {
                try
                {
                    if (RestoreConnection())
                    {
                        WriteAction(string.Format(Localization.UseRussian ? 
                            "Приём тренда входного канала {0} от SCADA-Сервера. Файл: {1}" : 
                            "Receive input channel {0} trend from SCADA-Server. File: {1}", 
                            trend.CnlNum, tableName), Log.ActTypes.Action);

                        commState = CommStates.WaitResponse;
                        tcpClient.ReceiveTimeout = commSettings.ServerTimeout;

                        byte tableType;        // тип таблицы: текущая, часовая или минутная
                        byte year, month, day; // дата запрашиваемых данных

                        if (tableName == "current.dat")
                        {
                            tableType = (byte)0x01;
                            year = month = day = 0;
                        }
                        else
                        {
                            tableType = tableName.Length > 0 && tableName[0] == 'h' ? (byte)0x02 : (byte)0x03;
                            year = (byte)(date.Year % 100);
                            month = (byte)date.Month;
                            day = (byte)date.Day;
                        }

                        // отправка запроса тренда входного канала
                        byte[] buf = new byte[13];
                        buf[0] = 0x0D;
                        buf[1] = 0x00;
                        buf[2] = 0x0D;
                        buf[3] = tableType;
                        buf[4] = year;
                        buf[5] = month;
                        buf[6] = day;
                        buf[7] = 0x01;
                        buf[8] = 0x00;
                        byte[] bytes = BitConverter.GetBytes(trend.CnlNum);
                        Array.Copy(bytes, 0, buf, 9, 4);
                        netStream.Write(buf, 0, 13);

                        // приём данных тренда входного канала
                        buf = new byte[7];
                        int bytesRead = netStream.Read(buf, 0, 7);
                        int pointCnt = 0;

                        if (bytesRead == 7)
                        {
                            pointCnt = buf[5] + buf[6] * 256;

                            if (pointCnt > 0)
                            {
                                Array.Resize<byte>(ref buf, 7 + pointCnt * 18);
                                bytesRead += ReadNetStream(buf, 7, buf.Length - 7);
                            }
                        }

                        // заполение тренда входного канала из полученных данных
                        if (bytesRead == buf.Length && buf[4] == 0x0D)
                        {
                            for (int i = 0; i < pointCnt; i++)
                            {
                                Trend.Point point;
                                int pos = i * 18 + 7;
                                point.DateTime = Arithmetic.DecodeDateTime(BitConverter.ToDouble(buf, pos));
                                point.Val = BitConverter.ToDouble(buf, pos + 8);
                                point.Stat = BitConverter.ToUInt16(buf, pos + 16);

                                trend.Points.Add(point);
                            }

                            trend.Sort();
                            result = true;
                            commState = CommStates.Authorized;
                        }
                        else
                        {
                            errMsg = Localization.UseRussian ? 
                                "Неверный формат ответа SCADA-Сервера на запрос тренда входного канала" :
                                "Incorrect SCADA-Server response to input channel trend request";
                            WriteAction(errMsg, Log.ActTypes.Error);
                            commState = CommStates.Error;
                        }
                    }
                }
                finally
                {
                    // очистка тренда, если не удалось получить новые данные
                    if (!result)
                    {
                        trend.Clear();
                        trend.TableName = tableName;
                    }
                }
            }
            catch (Exception ex)
            {
                errMsg = (Localization.UseRussian ? "Ошибка при приёме тренда входного канала от SCADA-Сервера: " :
                    "Error receiving input channel trend from SCADA-Server: ") + ex.Message;
                WriteAction(errMsg, Log.ActTypes.Exception);
                Disconnect();
            }
            finally
            {
                RestoreReceiveTimeout();
                Monitor.Exit(tcpLock);
            }

            return result;
        }
Exemplo n.º 55
0
		/// <summary>
		/// </summary>
		/// <param name="bars"></param>
		/// <param name="open"></param>
		/// <param name="high"></param>
		/// <param name="low"></param>
		/// <param name="close"></param>
		/// <param name="time"></param>
		/// <param name="volume"></param>
		/// <param name="isRealtime"></param>
		public override void Add(Bars bars, double open, double high, double low, double close, DateTime time, long volume, bool isRealtime)
		{
			#region Building Bars from Base Period

			if (bars.Count != tmpCount) // reset cache when bars are trimmed
				if (bars.Count == 0)
				{
					tmpTime			= Cbi.Globals.MinDate;
					tmpVolume		= 0;
					tmpDayCount		= 0;
					tmpTickCount	= 0;
				}
				else
				{
					tmpTime			= bars.GetTime(bars.Count - 1);
					tmpVolume		= bars.GetVolume(bars.Count - 1);
					tmpTickCount	= bars.TickCount;
					tmpDayCount		= bars.DayCount;
					bars.LastPrice	= anchorPrice = bars.GetClose(bars.Count - 1);
				}

			switch (bars.Period.BasePeriodType)
			{
				case PeriodType.Day:
					tmpTime = time.Date;
					if (isRealtime && time >= cacheSessionEnd)
					{
						tmpDayCount++;
						bars.Session.GetSessionDate(time, false, out tmpTime, out cacheSessionEnd);
						if (tmpTime < time.Date) tmpTime = time.Date; // make sure timestamps are ascending
					}

					if (!isRealtime && prevTimeD != tmpTime) tmpDayCount++;

					if ((!isRealtime && bars.Count > 0 && tmpTime == bars.TimeLastBar.Date)
						|| (isRealtime && bars.Count > 0 && tmpTime <= bars.TimeLastBar.Date)
						|| tmpDayCount < bars.Period.BasePeriodValue)
						endOfBar = false;
					else
					{
						prevTime	= prevTimeD == Cbi.Globals.MinDate ? tmpTime : prevTimeD;
						prevTimeD	= tmpTime;
						endOfBar	= true;
					}

					break;

				case PeriodType.Minute:

					if (tmpTime == Cbi.Globals.MinDate)
						prevTime = tmpTime = TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime);

					if (!isRealtime && time <= tmpTime || isRealtime && time < tmpTime)
						endOfBar	= false;
					else
					{
						prevTime	= tmpTime;
						tmpTime		= TimeToBarTimeMinute(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue, isRealtime);
						endOfBar	= true;
					}
					break;

				case PeriodType.Volume:
					if (tmpTime == Cbi.Globals.MinDate)
					{
						tmpVolume	= volume;
						endOfBar	= tmpVolume >= bars.Period.BasePeriodValue;
						prevTime	= tmpTime = time;
						if (endOfBar) 
							tmpVolume = 0;
						break;
					}

					tmpVolume += volume;
					endOfBar = tmpVolume >= bars.Period.BasePeriodValue;
					if (endOfBar)
					{
						prevTime = tmpTime;
						tmpVolume = 0;
						tmpTime = time;
					}
					break;

				case PeriodType.Month:
					if (tmpTime == Cbi.Globals.MinDate)
						prevTime	= tmpTime = TimeToBarTimeMonth(time, bars.Period.BasePeriodValue);

					if (time.Month <= tmpTime.Month && time.Year == tmpTime.Year || time.Year < tmpTime.Year)
						endOfBar	= false;
					else
					{
						prevTime	= tmpTime;
						endOfBar	= true;
						tmpTime		= TimeToBarTimeMonth(time, bars.Period.BasePeriodValue);
					}
					break;

				case PeriodType.Second:
					if (tmpTime == Cbi.Globals.MinDate)
					{
						prevTime = tmpTime = TimeToBarTimeSecond(bars, time,
																	new DateTime(bars.Session.NextBeginTime.Year,
																				bars.Session.NextBeginTime.Month,
																				bars.Session.NextBeginTime.Day,
																				bars.Session.NextBeginTime.Hour,
																				bars.Session.NextBeginTime.Minute, 0),
																	bars.Period.BasePeriodValue);
					}
					if (time <= tmpTime)
						endOfBar	= false;
					else
					{
						prevTime	= tmpTime;
						tmpTime		= TimeToBarTimeSecond(bars, time, bars.Session.NextBeginTime, bars.Period.BasePeriodValue);
						endOfBar	= true;
					}
					break;

				case PeriodType.Tick:
					if (tmpTime == Cbi.Globals.MinDate || bars.Period.BasePeriodValue == 1)
					{
						prevTime		= tmpTime = time;
						tmpTickCount	= bars.Period.BasePeriodValue == 1 ? 0 : 1;
						endOfBar		= bars.Period.BasePeriodValue == 1;
						break;
					}

					if (tmpTickCount < bars.Period.BasePeriodValue)
					{
						tmpTime			= time;
						endOfBar		= false;
						tmpTickCount++;
					}
					else
					{
						prevTime		= tmpTime;
						tmpTime			= time;
						endOfBar		= true;
						tmpTickCount	= 1;
					}
					break;

				case PeriodType.Week:
					if (tmpTime == Cbi.Globals.MinDate)
						prevTime = tmpTime = TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue);
					if (time.Date <= tmpTime.Date)
						endOfBar	= false;
					else
					{
						prevTime	= tmpTime;
						endOfBar	= true;
						tmpTime		= TimeToBarTimeWeek(time.Date, tmpTime.Date, bars.Period.BasePeriodValue);
					}
					break;

				case PeriodType.Year:
					if (tmpTime == Cbi.Globals.MinDate)
						prevTime = tmpTime = TimeToBarTimeYear(time, bars.Period.Value);
					if (time.Year <= tmpTime.Year)
						endOfBar	= false;
					else
					{
						prevTime	= tmpTime;
						endOfBar	= true;
						tmpTime		= TimeToBarTimeYear(time, bars.Period.Value);
					}
					break;
				default:
					break;
			}
			#endregion
			#region P&F logic
			double tickSize		= bars.Instrument.MasterInstrument.TickSize;
			boxSize				= Math.Floor(10000000.0 * bars.Period.Value * tickSize) / 10000000.0;
			reversalSize		= bars.Period.Value2 * boxSize;

			if (bars.Count == 0 || (IsIntraday && bars.IsNewSession(time, isRealtime)))
			{
				if (bars.Count > 0)
				{
					double		lastOpen	= bars.GetOpen(bars.Count - 1);
					double		lastHigh	= bars.GetHigh(bars.Count - 1);
					double		lastLow		= bars.GetLow(bars.Count - 1);
					double		lastClose	= bars.GetClose(bars.Count - 1);
					DateTime	lastTime	= bars.GetTime(bars.Count - 1);
					bars.LastPrice			= anchorPrice = lastClose;

					if (bars.Count == tmpCount)
						CalculatePfBar(bars, lastOpen, lastHigh, lastLow, lastClose, prevTime, lastTime, isRealtime);
				}

				AddBar(bars, close, close, close, close, tmpTime, volume, isRealtime);
				anchorPrice		= close;
				trend			= Trend.Undetermined;
				prevTime		= tmpTime;
				volumeCount		= 0;
				bars.LastPrice	= close;
				tmpCount		= bars.Count;
				tmpHigh			= high;
				tmpLow			= low;
				return;
			}

			Bar			bar		= (Bar)bars.Get(bars.Count - 1);
			double		c		= bar.Close;
			double		o		= bar.Open;
			double		h		= bar.High;
			double		l		= bar.Low;
			DateTime	t		= bar.Time;

			if (endOfBar)
			{
				CalculatePfBar(bars, o, h, l, c, prevTime, t, isRealtime);
				volumeCount		= volume;
				tmpHigh			= high;
				tmpLow			= low;
			}
			else
			{
				tmpHigh			= (high > tmpHigh ? high : tmpHigh);
				tmpLow			= (low < tmpLow ? low : tmpLow);
				volumeCount		+= volume;
			}

			bars.LastPrice		= close;
			tmpCount			= bars.Count;

			#endregion
		}