Exemple #1
0
        private Dictionary <IBarrierValue, Decimal> GetBarrierDistances(
            StudyValue StudyValue,
            int BarNumber,
            bool IsTrendTypeTest,
            TrendType TrendType,
            bool IsBoundaryTest,
            CongestionBoundary CongestionBoundary)
        {
            Dictionary <IBarrierValue, Decimal> distances = new Dictionary <IBarrierValue, Decimal>();

            foreach (IBarrierValue barrier in this.GetBarriers())
            {
                if ((!IsTrendTypeTest) || ((barrier is ITrendLine) && ((barrier as ITrendLine).TrendType == TrendType)))
                {
                    if ((!IsBoundaryTest) || (CongestionBoundary == barrier.CongestedBoundary))
                    {
                        // TODO: should not have to check this, but some double zero lines are coming through twice
                        if (!distances.ContainsKey(barrier))
                        {
                            distances.Add(barrier, barrier.GetValueAt(BarNumber) - StudyValue.Value);
                        }
                    }
                }
            }

            return(distances);
        }
Exemple #2
0
        private void ProcessSlow()
        {
            Log("SLOW, bar " + CurrentBar);
            ParabolicSAR p = ParabolicSAR(BarsArray[2], Acceleration, AccelerationMax, AccelerationStep);

            currTrendSLow = p[0] > Closes[2][0] ? TrendType.UP : TrendType.DOWN;
        }
        public static bool accordTrend(List <StockKLineBaidu> arr, TrendType trend)
        {
            bool ret = false;

            switch (trend)
            {
            case TrendType.TT_Down:
                ret = accordDownTrend(arr);
                break;

            case TrendType.TT_NotUp:
                ret = accordNotUpTrend(arr);
                break;

            case TrendType.TT_Sideway:
                ret = accordSideway(arr);
                break;

            case TrendType.TT_NotDown:
                ret = accordNotDownTrend(arr);
                break;

            case TrendType.TT_Up:
                ret = accordUpTrend(arr);
                break;

            default:
                break;
            }

            return(ret);
        }
Exemple #4
0
        private void ProcessFast()
        {
            Log("bar " + CurrentBar);
            ParabolicSAR p = ParabolicSAR(BarsArray[3], Acceleration, AccelerationMax, AccelerationStep);

            currTrendFast = p[0] > Closes[3][0] ? TrendType.UP : TrendType.DOWN;
        }
        private decimal GenerateLast()
        {
            if (_trendCount == 0 || _lastPrice < _minPriceLimit)
            {
                _trendCount = _random.Next(3, 13);
                if (_lastPrice > _maxPriceLimit)
                {
                    _trend = TrendType.Down;
                }
                else if (_lastPrice < _minPriceLimit)
                {
                    _trend = TrendType.Up;
                }
                else
                {
                    _trend = _trend == TrendType.Down ? TrendType.Up : TrendType.Down;
                }
            }

            var multiplier = _trend == TrendType.Down ? -1 : 1;

            _lastPrice += multiplier * RandomValue(_priceOffset);
            _trendCount--;
            return(_lastPrice);
        }
Exemple #6
0
        private void ProcessDaily()
        {
            Log("DAILY, bar " + CurrentBar);
            ParabolicSAR p = ParabolicSAR(BarsArray[1], Acceleration, AccelerationMax, AccelerationStep);

            currTrendDaily = p[0] > Closes[1][0] ? TrendType.UP : TrendType.DOWN;
        }
Exemple #7
0
 public Trend[] GetInRange(int[] itemids, long from, long to, TrendType trendType = TrendType.Float)
 {
     var response = _provider.Get(new Get
     {
         itemids = itemids,
         time_from = from,
         time_till = to,
         history = trendType
     });
     return response;
 }
Exemple #8
0
        public PsnChannelMock(IPsnMeter owner, TrendType type, DateTime startTime, GeneratedDataType dataType)
        {
            _startTime    = startTime;
            _dataType     = dataType;
            Type          = type;
            OwnerPsnMeter = owner;

            IsEnabled = true;
            Trend     = new List <IDataPoint>();

            UnicId = Guid.NewGuid();
        }
        public static void DefineChartTrendType(this Measure m, TrendType trendtype, Color c)
        {
            var ch2 = m.Grid as OlapChart;

            if (ch2 != null)
            {
                ch2.chartDefinitions.TrendTypes.Remove(m);

                var tw = new TrendWrapper(c, trendtype);
                ch2.chartDefinitions.TrendTypes.Add(m, tw);
            }
        }
Exemple #10
0
        private TrendType GetTypeOfReport(GroupCollection groups)
        {
            TrendType ret = TrendType.None;

            for (int i = 1; i < NumberOfGroups; i++)
            {
                if (groups[i].Success)
                {
                    ret = regexTypes[i];
                    break;
                }
            }
            return(ret);
        }
Exemple #11
0
        private static TrendType UpdateTrend(TrendType currentTrend, decimal sma50, decimal sma200)
        {
            var newTrend = TrendType.Unknown;

            if ((currentTrend == TrendType.Unknown || currentTrend == TrendType.Down) && sma50 > sma200)
            {
                newTrend = TrendType.Up;
            }
            else if ((_trend == TrendType.Unknown || _trend == TrendType.Up) && sma50 < sma200)
            {
                newTrend = TrendType.Down;
            }
            // else
            //   _trend = TrendType.Unknown;
            return(newTrend);
        }
        public decimal GetLastValue(CurrencyPair currency, out TrendType trend)
        {
            decimal newPrice = this.inMemoryStorage[currency].Last().Value;

            bool tryGetValue = this.lastPricePerCurrency.TryGetValue(currency, out decimal value);

            trend = tryGetValue ? newPrice > this.lastPricePerCurrency[currency] ? TrendType.Up : TrendType.Down : TrendType.Up;

            this.lastPricePerCurrency.AddOrUpdate(currency, newPrice,
                                                  (key, existingVal) =>
            {
                existingVal = newPrice;
                return(existingVal);
            });

            return(newPrice);
        }
Exemple #13
0
        /// <summary>
        /// Get signal for the bar
        /// </summary>
        /// <returns></returns>
        protected SignalType GetSignal(int bar)
        {
            SignalType result = SignalType.None;
            //double price = Close[bar];
            double    price     = smaPrice[bar];
            TrendType trendType = GetTrendType(bar);

            // Move last maximum, minimum
            if (price < lastMin)
            {
                lastMin    = price;
                lastMinBar = bar;
            }
            if (price > lastMax)
            {
                lastMax    = price;
                lastMaxBar = bar;
            }

            // Buy if go up more then deltaUp
            if (price - lastMin >= deltaUp.Value &&
                trendType == TrendType.Bear &&
                (!IsLastPositionActive ||
                 (IsLastPositionActive &&
                  LastActivePosition.PositionType != PositionType.Long)))
            {
                result = SignalType.Buy;
                AnnotateBar("Min", lastMinBar, true, Color.DarkRed);
                AnnotateBar("Buy", bar, true, Color.DarkBlue);
                lastMax = lastMin = price;
            }
            // Sell if go down more then deltaDown
            else if (lastMax - price >= deltaDown.Value &&
                     trendType == TrendType.Bull &&
                     (!IsLastPositionActive ||
                      (IsLastPositionActive &&
                       LastActivePosition.PositionType != PositionType.Short)))
            {
                result = SignalType.Sell;
                AnnotateBar("Max", lastMaxBar, true, Color.DarkBlue);
                AnnotateBar("Sell", bar, true, Color.DarkRed);
                lastMax = lastMin = price;
            }

            return(result);
        }
Exemple #14
0
        public virtual List <IBarrierValue> GetClosestBarrierBelow(
            StudyValue StudyValue,
            int BarNumber,
            bool IsTrendTypeTest,
            TrendType TrendType,
            bool IsBoundaryTest,
            CongestionBoundary CongestionBoundary)
        {
            List <IBarrierValue> barriers = new List <IBarrierValue>();

            foreach (IBarrierValue barrier in
                     GetBarrierDistances(StudyValue, BarNumber, IsTrendTypeTest, TrendType, IsBoundaryTest, CongestionBoundary).Where(t => t.Value < 0.0M).OrderBy(t => t.Value).Reverse().Select(t => t.Key))
            {
                barriers.Add(barrier);
            }

            return(barriers);
        }
Exemple #15
0
        /// <summary>
        /// Get trend type for the bar
        /// </summary>
        /// <param name="bar"></param>
        /// <returns></returns>
        protected TrendType GetTrendType(int bar)
        {
            TrendType result = TrendType.Unknown;

            if (bar == 0)
            {
                result = TrendType.Unknown;
            }
            else if (smaTrend[bar - 1] < smaTrend[bar])
            {
                result = TrendType.Bull;
            }
            else if (smaTrend[bar - 1] > smaTrend[bar])
            {
                result = TrendType.Bear;
            }
            return(result);
        }
Exemple #16
0
        public Trend[] GetInRange(DateTime from, DateTime to, TrendType trendType = TrendType.Float)
        {
            if (from == null || to == null)
                throw new ArgumentNullException();

            if (from.Kind != DateTimeKind.Utc)
                from = from.ToUniversalTime();

            if (to.Kind != DateTimeKind.Utc)
                to = to.ToUniversalTime();

            var response = _provider.Get(new Get
                {
                    time_from = from.ToUnixTime(),
                    time_till = to.ToUnixTime(),
                    history = trendType
                });
            return response;
        }
Exemple #17
0
        public RpdChannel(IRpdMeter owner, int number, string name, bool isEnabled, bool isService, TrendType type)
        {
            InitWorker();
            OwnerMeter   = owner;
            Name         = name;
            Number       = number;
            IsEnabled    = isEnabled;
            IsService    = isService;
            CurrentValue = null;
            Type         = type;
            //-----------------------------
            Trend         = new List <IDataPoint>();
            IsTrendExists = false;
            IsTrendLoaded = false;

            DumpCondition = new RpdChannellDumpCondition();
            //this.Start = new DateTime();
            //this.Start = new DateTime();
        }
Exemple #18
0
        public List <IBarrierValue> GetClosestBarrierBelow(
            StudyValue StudyValue,
            int BarNumber,
            bool IsTrendTypeTest,
            TrendType TrendType,
            bool IsBoundaryTest,
            CongestionBoundary CongestionBoundary,
            int MinimumTests)
        {
            List <IBarrierValue> barriers = new List <IBarrierValue>();

            foreach (IBarrierValue barrier in base.GetClosestBarrierBelow(StudyValue, BarNumber, IsTrendTypeTest, TrendType, IsBoundaryTest, CongestionBoundary))
            {
                if ((barrier as IAggregateLine).NumTests >= MinimumTests)
                {
                    barriers.Add(barrier);
                }
            }

            return(barriers);
        }
Exemple #19
0
 public TrendLine(
     int BarNumberIdentified,
     Decimal Intercept,
     Decimal Gradient,
     TrendType TrendType,
     TrendOrientation Orientation,
     int NumTests,
     decimal AbsoluteGradientThreshold,
     decimal AbsoluteFlatThreshold,
     decimal FailureDistanceMultiple)
 {
     this.BarNumberIdentified       = BarNumberIdentified;
     this.Intercept                 = Intercept;
     this.Gradient                  = Gradient;
     this.TrendType                 = TrendType;
     this.Orientation               = Orientation;
     this.NumTests                  = NumTests;
     this.AbsoluteGradientThreshold = AbsoluteGradientThreshold;
     this.AbsoluteFlatThreshold     = AbsoluteFlatThreshold;
     this.FailureDistanceMultiple   = FailureDistanceMultiple;
 }
Exemple #20
0
        private static ActionSignalType GetActionSignal(TrendType trend)
        {
            // if currently holding a position do nothing
            if (_position != null)
            {
                return(ActionSignalType.DoNothing);
            }

            switch (trend)
            {
            case TrendType.Up:
                return(ActionSignalType.Buy);

            case TrendType.Down:
                return(ActionSignalType.Sell);

            case TrendType.Unknown:
            default:
                return(ActionSignalType.DoNothing);;
            }
        }
Exemple #21
0
        public static TrendType GetTrendType(string raw)
        {
            TrendType result = 0;//THINK add unspecified for 0?

            switch (raw)
            {
            case "NOSIG":
                result = TrendType.NOSIG;
                break;

            case "BECMG":
                result = TrendType.BECMG;
                break;

            case "GRADU":
                result = TrendType.GRADU;
                break;

            case "RAPID":
                result = TrendType.RAPID;
                break;

            case "TEMPO":
                result = TrendType.TEMPO;
                break;

            case "INTER":
                result = TrendType.INTER;
                break;

            case "TEND":
                result = TrendType.TEND;
                break;

                /*default:
                 *  result = TrendType.Unspecified;
                 *  break;*/
            }
            return(result);
        }
Exemple #22
0
        public PsnChannelSimple(Guid unicId, Guid configurationId, string channelName, TrendType chanleType, IPsnChannelTrendLoader trendLoader, IThreadNotifier uiNotifier, IWorker <Action> bworker, IPsnMeter ownerMeter)
        {
            _sync = new object();

            UnicId          = unicId;
            ConfigurationId = configurationId;
            Name            = channelName;
            Type            = chanleType;
            _trendLoader    = trendLoader;

            //_signalConfiguration = signalConfiguration;
            //_psnData = psnData;
            //_psnConfiguration = psnConfiguration;
            //_psnDataInformation = psnDataInformation;

            _uiNotifier   = uiNotifier;
            _bworker      = bworker;
            OwnerPsnMeter = ownerMeter;


            _points        = new List <IDataPoint>();
            _isTrendLoaded = false;
        }
Exemple #23
0
 public SignalMock(TrendType type)
 {
     Type = type;
 }
 private void ProcessFast()
 {
     Log("bar " + CurrentBar);
     ParabolicSAR p = ParabolicSAR(BarsArray[3], Acceleration, AccelerationMax, AccelerationStep);
     currTrendFast = p[0] > Closes[3][0] ? TrendType.UP : TrendType.DOWN;
 }
Exemple #25
0
        public async Task <CurrentDataResponse <TrendStatistics[]> > GetTrendAsync(Guid uuid, Gamemode gamemodes, DateTime start, DateTime end, TeamRole teamroles, TrendType trendType)
        {
            // ?gameMode=all,ranked,unranked,casual&startDate=20200718&endDate=20201115&teamRole=all,attacker,defender&trendType=weeks
            var queries = BuildQuery(gamemodes, start, end, null, teamroles, trendType);

            return(await GetData <CurrentDataResponse <TrendStatistics[]> >(Endpoints.R6SStats.Trend, uuid, queries).ConfigureAwait(false));
        }
 private void ProcessDaily()
 {
     Log("DAILY, bar " + CurrentBar);
     ParabolicSAR p = ParabolicSAR(BarsArray[1], Acceleration, AccelerationMax, AccelerationStep);
     currTrendDaily = p[0] > Closes[1][0] ? TrendType.UP : TrendType.DOWN;
 }
 private void ProcessSlow()
 {
     Log("SLOW, bar " + CurrentBar);
     ParabolicSAR p = ParabolicSAR(BarsArray[2], Acceleration, AccelerationMax, AccelerationStep);
     currTrendSLow = p[0] > Closes[2][0] ? TrendType.UP : TrendType.DOWN;
     
 }
Exemple #28
0
 public static void UpdateTrendStat(TrendType trendType)
 {
     DatabaseProvider.GetInstance().UpdateTrendStat(trendType);
 }
Exemple #29
0
 public Trend[] GetLastsForPeriod(TimeSpan span, int[] itemids = null, TrendType trendType = TrendType.Float)
 {
     return GetInRange(itemids, (DateTime.UtcNow - span), DateTime.UtcNow, trendType);
 }
        public bool berekenTrends(double minVoorwaarde, Entiteit entiteit, TrendType type, Voorwaarde voorwaarde)
        {
            initNonExistingRepo();
            DateTime vandaag  = DateTime.Today;
            DateTime gisteren = DateTime.Today.AddDays(-1);
            //DateTime vandaag = new DateTime(2018, 01, 14);
            //DateTime gisteren = new DateTime(2018, 01, 13);
            List <Post> AllePosts      = entiteit.Posts;
            List <Post> PostsGisteren  = AllePosts.Where(x => x.Date.Day == gisteren.Day).Where(x => x.Date.Month == gisteren.Month).Where(x => x.Date.Year == gisteren.Year).ToList();
            List <Post> PostsVandaag   = AllePosts.Where(x => x.Date.Day == vandaag.Day).Where(x => x.Date.Month == vandaag.Month).Where(x => x.Date.Year == vandaag.Year).ToList();
            int         AantalGisteren = PostsGisteren.Count;
            int         AantalVandaag  = PostsVandaag.Count;
            //We MOETEN entiteit even zelf ophalen zodat de context op de hoogte is van welke entiteit we gebruiken
            Entiteit e                = getAlleEntiteiten().Single(x => x.EntiteitId == entiteit.EntiteitId);
            Trend    newTrend         = new Trend();
            double   trendVerandering = 1.3;

            //controle of trend al bestaat, zoja moeten we de berekening niet maken
            foreach (var trend in e.Trends)
            {
                if (trend.Type == type)
                {
                    return(true);
                }
            }

            //PRESET voor berekening juist zetten
            switch (type)
            {
            case TrendType.STERKOPWAARTS:
                trendVerandering = 1.3;
                newTrend.Type    = TrendType.STERKOPWAARTS;
                break;

            case TrendType.MATIGOPWAARDS:
                trendVerandering = 1.1;
                newTrend.Type    = TrendType.MATIGOPWAARDS;
                break;

            case TrendType.MATIGDALEND:
                trendVerandering = 0.9;
                newTrend.Type    = TrendType.MATIGDALEND;
                break;

            case TrendType.STERKDALEND:
                trendVerandering = 0.7;
                newTrend.Type    = TrendType.STERKDALEND;
                break;
            }


            switch (voorwaarde)
            {
            case Voorwaarde.SENTIMENT:
                double sentimentGisteren = 0;
                double sentimentVandaag  = 0;

                foreach (var post in PostsGisteren)
                {
                    sentimentGisteren += (post.Sentiment.polariteit * post.Sentiment.subjectiviteit) / AantalGisteren;
                }

                foreach (var post in PostsVandaag)
                {
                    sentimentVandaag += (post.Sentiment.polariteit * post.Sentiment.subjectiviteit) / AantalVandaag;
                }
                double sentimentVerschil = 0;

                if (type == TrendType.STIJGEND)
                {
                    sentimentVerschil = sentimentVandaag - sentimentGisteren;
                    if (sentimentVerschil >= minVoorwaarde)
                    {
                        newTrend.Type       = TrendType.STIJGEND;
                        newTrend.Voorwaarde = Voorwaarde.SENTIMENT;
                        entiteit.Trends.Add(newTrend);
                        updateEntiteit(e);
                        return(true);
                    }
                }
                else if (type == TrendType.DALEND)
                {
                    sentimentVerschil   = sentimentGisteren - sentimentVandaag;
                    newTrend.Type       = TrendType.DALEND;
                    newTrend.Voorwaarde = Voorwaarde.SENTIMENT;
                    entiteit.Trends.Add(newTrend);
                    updateEntiteit(e);
                    return(true);
                }
                break;

            case Voorwaarde.AANTALVERMELDINGEN:
                newTrend.Voorwaarde = Voorwaarde.AANTALVERMELDINGEN;
                if (type == TrendType.DALEND)
                {
                    if ((AantalGisteren - AantalVandaag) >= minVoorwaarde)
                    {
                        return(true);
                    }
                }
                if (type == TrendType.STIJGEND)
                {
                    if ((AantalVandaag - AantalGisteren) >= minVoorwaarde)
                    {
                        return(true);
                    }
                }
                if (type == TrendType.STERKOPWAARTS)
                {
                    if ((AantalVandaag / AantalGisteren) >= trendVerandering)
                    {
                        if (entiteit.Trends == null)
                        {
                            entiteit.Trends = new List <Trend>();
                        }
                        entiteit.Trends.Add(newTrend);
                        updateEntiteit(e);
                        return(true);
                    }
                }
                if (type == TrendType.STERKDALEND)
                {
                    if ((AantalVandaag / AantalGisteren) <= trendVerandering)
                    {
                        if (entiteit.Trends == null)
                        {
                            entiteit.Trends = new List <Trend>();
                        }
                        entiteit.Trends.Add(newTrend);
                        updateEntiteit(e);
                        return(true);
                    }
                }
                break;


            case Voorwaarde.TRENDING:
                //de eventuele trend die aanwezig kan zijn juist zetten op de trend waarop we vergelijken
                newTrend.Voorwaarde = Voorwaarde.TRENDING;
                //if kijkt na of het aantal posts van gisteren tegenover vandaag met 50% is gestegen en er moet minstens een volume van 10 posts zijn
                if ((AantalVandaag / AantalGisteren) > 1.5 && AantalGisteren >= 10 && AantalVandaag >= 10)
                {
                    if (entiteit.Trends == null)
                    {
                        entiteit.Trends = new List <Trend>();
                    }
                    entiteit.Trends.Add(newTrend);
                    updateEntiteit(e);
                    return(true);
                }
                break;

            case Voorwaarde.KEYWORDS:
                break;

            default:
                break;
            }
            //als we hier komen is er geen trend aanwezig.
            return(false);
        }
Exemple #31
0
 public Trend[] GetInRange(int[] itemids, DateTime from, DateTime to, TrendType trendType = TrendType.Float)
 {
     if (from == null || to == null)
         throw new ArgumentNullException();
     return GetInRange(itemids, from.ToUnixTime(), to.ToUnixTime(), trendType);
 }
Exemple #32
0
        public static AdaptiveCard GetTopCharts(TopCharts chart, TrendType trend)
        {
            AdaptiveCard adaptiveCard = new AdaptiveCard();

            ContainerStylesConfig config = new ContainerStylesConfig();

            config.Default.ForegroundColors.Good = new FontColorConfig("#4caf50", "#8bc34a");

            AdaptiveHostConfig adaptiveHostConfig = new AdaptiveHostConfig();

            var top_charts = trend == TrendType.Gainer ? chart.Data.OrderByDescending(dt => dt.ChangePercent).Take(15) : chart.Data.OrderBy(dt => dt.ChangePercent).Take(15);

            var body = new List <AdaptiveElement>();

            var first_col_items = new List <AdaptiveElement>()
            {
                new AdaptiveTextBlock()
                {
                    Text   = "Company",
                    Weight = AdaptiveTextWeight.Bolder,
                    Wrap   = false
                }
            };

            foreach (var stock in top_charts)
            {
                first_col_items.Add(new AdaptiveTextBlock()
                {
                    Text   = stock.Name,
                    Weight = AdaptiveTextWeight.Lighter,
                    Wrap   = false
                });
            }
            ;

            var change_col_items = new List <AdaptiveElement>()
            {
                new AdaptiveTextBlock()
                {
                    Text   = "Change",
                    Weight = AdaptiveTextWeight.Bolder,
                    Wrap   = false
                }
            };


            foreach (var stock in top_charts)
            {
                var upOrDown = stock.Change < 0 ? "▼" : "▲";

                change_col_items.Add(new AdaptiveTextBlock()
                {
                    Text   = $"{upOrDown} {stock.ChangePercent.ToString()}",
                    Weight = AdaptiveTextWeight.Bolder,
                    Color  = stock.Change < 0 ? AdaptiveTextColor.Warning: AdaptiveTextColor.Accent,
                    Wrap   = false
                });
            }

            var second_col_items = new List <AdaptiveElement>()
            {
                new AdaptiveTextBlock()
                {
                    Text   = "CMP",
                    Weight = AdaptiveTextWeight.Bolder,
                    Wrap   = false
                }
            };

            foreach (var stock in top_charts)
            {
                second_col_items.Add(new AdaptiveTextBlock()
                {
                    Text   = stock.LastPrice.ToString(),
                    Weight = AdaptiveTextWeight.Lighter,
                    Wrap   = false
                });
            }

            var third_col_items = new List <AdaptiveElement>()
            {
                new AdaptiveTextBlock()
                {
                    Text   = "Day High",
                    Weight = AdaptiveTextWeight.Bolder,
                    Wrap   = false
                }
            };

            foreach (var stock in top_charts)
            {
                third_col_items.Add(new AdaptiveTextBlock()
                {
                    Text   = stock.High.ToString(),
                    Weight = AdaptiveTextWeight.Lighter,
                    Wrap   = false
                });
            }

            var fourth_col_items = new List <AdaptiveElement>()
            {
                new AdaptiveTextBlock()
                {
                    Text   = "Day Low",
                    Weight = AdaptiveTextWeight.Bolder,
                    Wrap   = false
                }
            };

            foreach (var stock in top_charts)
            {
                fourth_col_items.Add(new AdaptiveTextBlock()
                {
                    Text   = stock.Low.ToString(),
                    Weight = AdaptiveTextWeight.Lighter,
                    Wrap   = false
                });
            }

            body.Add(new AdaptiveContainer()
            {
                Items = new List <AdaptiveElement>()
                {
                    new AdaptiveTextBlock()
                    {
                        Text   = trend == TrendType.Gainer ? "Top Gainers" : "Top Losers",
                        Weight = AdaptiveTextWeight.Bolder,
                        Size   = AdaptiveTextSize.Medium
                    },
                    new AdaptiveColumnSet()
                    {
                        Columns = new List <AdaptiveColumn>()
                        {
                            new AdaptiveColumn()
                            {
                                Width = AdaptiveColumnWidth.Auto,
                                Items = first_col_items
                            },
                            new AdaptiveColumn()
                            {
                                Width = AdaptiveColumnWidth.Auto,
                                Items = change_col_items
                            },
                            new AdaptiveColumn()
                            {
                                Width = AdaptiveColumnWidth.Auto,
                                Items = second_col_items
                            },
                            new AdaptiveColumn()
                            {
                                Width = AdaptiveColumnWidth.Auto,
                                Items = third_col_items
                            },
                            new AdaptiveColumn()
                            {
                                Width = AdaptiveColumnWidth.Auto,
                                Items = fourth_col_items
                            },
                        }
                    }
                }
            });

            adaptiveCard.Body = body;

            return(adaptiveCard);
        }
Exemple #33
0
        static async Task Main(string[] args)
        {
            // TODO: while market open
            while (true)
            {
                // https://www.alphavantage.co/documentation/#latestprice
                var quoteUrl = $"https://www.alphavantage.co/query?function={_globalQuoteFuntionName}&symbol={_symbol}&apikey={_apiKey}";
                // https://www.alphavantage.co/documentation/#sma
                var sma50Url  = $"https://www.alphavantage.co/query?function={_smaFuntionName}&symbol={_symbol}&interval={_interval}&time_period={_timePeriod50.ToString()}&series_type={_seriesType}&apikey={_apiKey}";
                var sma200Url = $"https://www.alphavantage.co/query?function={_smaFuntionName}&symbol={_symbol}&interval={_interval}&time_period={_timePeriod200.ToString()}&series_type={_seriesType}&apikey={_apiKey}";

                // Moving Average
                // 1. Identify Trends (up, down)
                // if the price is > MA --> uptrend
                // if the price is < MA --> downtrend

                // 2. Confirm Reversals
                // if the price is = MA --> trend reversal

                // 3. Identify Support and Resistance Level
                // TODO

                // 4. BUY/SELL
                // if the price is > MA --> signal to BUY with stop loss below the MA
                // if the price is < MA --> signal to SELL with stop loss above the MA

                // TYPES
                // 1. SMA - Simple Moving Average
                // Summary: Equal weight to all periods - laggy price reaction
                // Good for: Mid- to Long-term trends
                // Calculation: Sum of closing price for given period (days) / period length (number of days)
                // Example: 10 closing prices for each day in 10 days (c1+c2+...c10)/10

                // 2. WMA - Weighted Moving Average
                // Summary: Responds faster to price action, more weight to recent periods, less weight to older periods, reflect a quicker shift in sentiment
                // Good for: Short-term trends
                // Calculation: TODO

                // 3. EMA - Exponential Moving Average
                // Summary: Responds faster to price action, more weight to recent periods, less weight to older periods, reflect a quicker shift in sentiment
                // Good for: Short-term trends
                // Calculation: TODO

                // MA Crossovers
                // Summary: Combination of MA's reflecting two different time periods (short-term with long-term) create opportunity to trade MA Crossovers - used to determine if the trend has changed direction
                // Example 1: When a shorter period MA crosses above a longer period MA - signal uptrend --> signal to buy (Bullish).
                // Example 2: When a shorter period MA crosses below a longer period MA - signal downtrend --> signal to sell (Bearish).

                Console.WriteLine(DateTime.UtcNow);
                Console.WriteLine("Symbol: " + _symbol);
                // Get current price
                string quoteResponseBody = await _client.GetStringAsync(quoteUrl);

                var quote = ParseResponse <Quote>(quoteResponseBody, "Global Quote");
                _currentPrice = decimal.Parse(quote.Price);
                Console.WriteLine("Price: " + _currentPrice.ToString());

                // Get current SMA50 & current SMA200
                _sma50 = await GetSma(sma50Url, _timePeriod50);

                _sma200 = await GetSma(sma200Url, _timePeriod200);

                // Trend
                _trend = UpdateTrend(_trend, _sma50, _sma200);
                Console.WriteLine("Trend: " + _trend.ToString());

                // Buy/Sell Signal
                var actionSignal = GetActionSignal(_trend);
                Console.WriteLine("Signal: " + actionSignal.ToString());

                // Buy/Sell
                switch (actionSignal)
                {
                case ActionSignalType.Buy:
                    Buy();
                    break;

                case ActionSignalType.Sell:
                    Sell();
                    break;

                case ActionSignalType.DoNothing:
                case ActionSignalType.Unknown:
                default:
                    break;
                }
                Console.WriteLine("***************************");
                Console.WriteLine("Position: " + string.Format("{0:C}", _position.Value));
                Console.WriteLine("Cash: " + string.Format("{0:C}", _account));
                Console.WriteLine("Total: " + string.Format("{0:C}", _position.Value + _account));
                Console.WriteLine("***************************");

                // Sleep for 5 min and repeat
                Thread.Sleep(60000);
            }
        }
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {

            // OnBarUpdate() will be called on incoming tick events on all Bars objects added to the strategy
            // We only want to process events on our primary Bars object (index = 0) which is set when adding
            // the strategy to a chart
            //if (BarsInProgress != 0)
            //    return;

            if (CurrentBars[0] <= BarsRequired || CurrentBars[1] <= BarsRequired) return;
            //if (CurrentBars[0] < 1) return;
            //if (CurrentBars[1] < 1) return;

       //    Print("BarsinProgress: " + BarsInProgress + ", CurrentBar: " + CurrentBar + ", Closes[0]: "+ Closes[0][0]);

        
            //sma2 = SMA(BarsArray[1], SMAPeriod2*24)[0];
            //PlotSMA2.Set(sma2);

            if (BarsInProgress == 1)
            {

                sma1 = SMA(Closes[1], SMAPeriod1 * 24)[0];
                
                double threshold = 0.000;
                //   double threshold = 0.000;

                if (PlotSMA1[0] + threshold < PlotSMA1[1])
                {
                    currentOverallTrend = TrendType.DOWN;
                }
                else if (PlotSMA1[0] > PlotSMA1[1] + threshold)
                {
                    currentOverallTrend = TrendType.UP;
                }
                else
                {
                    currentOverallTrend = TrendType.NEUTRAL;
                }
            }



            // Draws a dotted lime green arrow line
            //   DrawArrowLine("tag1", true, 10, Close[10] * 1.05, 0, Close[0] * 1.05, Color.LimeGreen, DashStyle.Solid, 3);

            // only draw on primary series
            if (BarsInProgress == 0)
            {

                PlotSMA1.Set(sma1);

                switch (currentOverallTrend)
                {
                    case TrendType.DOWN:
                        DrawArrowDown("arrdown" + CurrentBar, false, 1, High[1] * 1.0008, Color.Red);
                        //   BackColor = Color.Pink;
                        break;

                    case TrendType.UP:
                        DrawArrowUp("arrup" + CurrentBar,1, Low[1] * 0.9992, Color.Blue);
                        //     BackColor = Color.LightGreen;
                        break;

                    default:
                        DrawArrowLine("arrneu" + CurrentBar, 2, Close[0], 1, Close[0], Color.Yellow);
                        break;
                }
            }



            // only draw on last bar of the primary series
            if (BarsInProgress == 0 && Count - 2 == CurrentBar)
            {
                switch (currentOverallTrend)
                {
                    case TrendType.DOWN:
                        DrawTextFixed("texttrend", "Trend: DOWN", TextPosition.TopRight, Color.Red, fontTrend, Color.Blue, Color.Black, 100);
                        break;
                    case TrendType.UP:
                        DrawTextFixed("texttrend", "Trend: UP", TextPosition.TopRight, Color.Lime, fontTrend, Color.Blue, Color.Black, 100);
                        break;
                    default:
                        break;
                }
            }









        }
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            // OnBarUpdate() will be called on incoming tick events on all Bars objects added to the strategy
            // We only want to process events on our primary Bars object (index = 0) which is set when adding
            // the strategy to a chart
            //if (BarsInProgress != 0)
            //    return;

            if (CurrentBars[0] <= BarsRequired || CurrentBars[1] <= BarsRequired)
            {
                return;
            }
            //if (CurrentBars[0] < 1) return;
            //if (CurrentBars[1] < 1) return;

            //    Print("BarsinProgress: " + BarsInProgress + ", CurrentBar: " + CurrentBar + ", Closes[0]: "+ Closes[0][0]);


            //sma2 = SMA(BarsArray[1], SMAPeriod2*24)[0];
            //PlotSMA2.Set(sma2);

            if (BarsInProgress == 1)
            {
                sma1 = SMA(Closes[1], SMAPeriod1 * 24)[0];

                double threshold = 0.000;
                //   double threshold = 0.000;

                if (PlotSMA1[0] + threshold < PlotSMA1[1])
                {
                    currentOverallTrend = TrendType.DOWN;
                }
                else if (PlotSMA1[0] > PlotSMA1[1] + threshold)
                {
                    currentOverallTrend = TrendType.UP;
                }
                else
                {
                    currentOverallTrend = TrendType.NEUTRAL;
                }
            }



            // Draws a dotted lime green arrow line
            //   DrawArrowLine("tag1", true, 10, Close[10] * 1.05, 0, Close[0] * 1.05, Color.LimeGreen, DashStyle.Solid, 3);

            // only draw on primary series
            if (BarsInProgress == 0)
            {
                PlotSMA1.Set(sma1);

                switch (currentOverallTrend)
                {
                case TrendType.DOWN:
                    DrawArrowDown("arrdown" + CurrentBar, false, 1, High[1] * 1.0008, Color.Red);
                    //   BackColor = Color.Pink;
                    break;

                case TrendType.UP:
                    DrawArrowUp("arrup" + CurrentBar, 1, Low[1] * 0.9992, Color.Blue);
                    //     BackColor = Color.LightGreen;
                    break;

                default:
                    DrawArrowLine("arrneu" + CurrentBar, 2, Close[0], 1, Close[0], Color.Yellow);
                    break;
                }
            }



            // only draw on last bar of the primary series
            if (BarsInProgress == 0 && Count - 2 == CurrentBar)
            {
                switch (currentOverallTrend)
                {
                case TrendType.DOWN:
                    DrawTextFixed("texttrend", "Trend: DOWN", TextPosition.TopRight, Color.Red, fontTrend, Color.Blue, Color.Black, 100);
                    break;

                case TrendType.UP:
                    DrawTextFixed("texttrend", "Trend: UP", TextPosition.TopRight, Color.Lime, fontTrend, Color.Blue, Color.Black, 100);
                    break;

                default:
                    break;
                }
            }
        }
        public bool berekenTrends(int minVoorwaarde, Entiteit entiteit, TrendType type, Domain.Alert.Voorwaarde voorwaarde)
        {
            initNonExistingRepo();
            //DateTime vandaag = DateTime.Today;
            //DateTime gisteren = DateTime.Today.AddDays(-1);
            DateTime    vandaag        = new DateTime(2018, 01, 14);
            DateTime    gisteren       = new DateTime(2018, 01, 13);
            List <Post> AllePosts      = entiteit.Posts;
            List <Post> PostsGisteren  = AllePosts.Where(x => x.Date.Day == gisteren.Day).Where(x => x.Date.Month == gisteren.Month).Where(x => x.Date.Year == gisteren.Year).ToList();
            List <Post> PostsVandaag   = AllePosts.Where(x => x.Date.Day == vandaag.Day).Where(x => x.Date.Month == vandaag.Month).Where(x => x.Date.Year == vandaag.Year).ToList();
            int         AantalGisteren = PostsGisteren.Count;
            int         AantalVandaag  = PostsVandaag.Count;
            //We MOETEN entiteit even zelf ophalen zodat de context op de hoogte is van welke entiteit we gebruiken
            Entiteit p        = getAlleEntiteiten().Single(x => x.EntiteitId == entiteit.EntiteitId);
            Trend    newTrend = new Trend();

            double trendVerandering = 1.3;


            //controle of trend al bestaat, zoja moeten we de berekening niet maken
            foreach (var trend in p.Trends)
            {
                if (trend.Type == type)
                {
                    return(true);
                }
            }

            //PRESET voor berekening juist zetten
            switch (type)
            {
            case TrendType.STERKOPWAARDS:
                trendVerandering = 1.3;
                newTrend.Type    = TrendType.STERKOPWAARDS;
                break;

            case TrendType.MATIGOPWAARDS:
                trendVerandering = 1.1;
                newTrend.Type    = TrendType.MATIGOPWAARDS;
                break;

            case TrendType.MATIGDALEND:
                trendVerandering = 0.9;
                newTrend.Type    = TrendType.MATIGDALEND;
                break;

            case TrendType.STERKDALEND:
                trendVerandering = 0.7;
                newTrend.Type    = TrendType.STERKDALEND;
                break;
            }

            switch (voorwaarde)
            {
            case Voorwaarde.SENTIMENT:
                if (type == TrendType.STIJGEND)
                {
                    double sentimentGisteren = 0;
                    double sentimentVandaag  = 0;

                    foreach (var post in PostsGisteren)
                    {
                        sentimentGisteren += (post.sentiment.polariteit * post.sentiment.objectiviteit) / AantalGisteren;
                    }

                    foreach (var post in PostsVandaag)
                    {
                        sentimentVandaag += (post.sentiment.polariteit * post.sentiment.objectiviteit) / AantalVandaag;
                    }
                    double sentimentVerschil = sentimentVandaag - sentimentGisteren;
                    if (sentimentVerschil >= minVoorwaarde)
                    {
                        newTrend.Type = TrendType.STIJGEND;
                        entiteit.Trends.Add(newTrend);
                        UpdateEntiteit(entiteit);
                        return(true);
                    }
                }
                break;

            case Voorwaarde.AANTALVERMELDINGEN:
                if (type == TrendType.STIJGEND)
                {
                    if ((AantalVandaag - AantalGisteren) >= minVoorwaarde)
                    {
                        return(true);
                    }
                }
                if (type == TrendType.DALEND)
                {
                    if ((AantalGisteren - AantalVandaag) >= minVoorwaarde)
                    {
                        return(true);
                    }
                }
                if (type == TrendType.STERKOPWAARDS)
                {
                    if ((AantalVandaag / AantalGisteren) >= trendVerandering)
                    {
                        if (entiteit.Trends == null)
                        {
                            entiteit.Trends = new List <Trend>();
                        }
                        entiteit.Trends.Add(newTrend);
                        UpdateEntiteit(p);
                        return(true);
                    }
                }
                break;

            case Voorwaarde.KEYWORDS:
                break;

            default:
                break;
            }

            //ALS het een type stijging is, dit is een waarde die de user heeft opgegeven kijken we of deze stijging voldoet aan de voorwaarde.
            if (type == TrendType.STIJGEND)
            {
                if ((AantalVandaag - AantalGisteren) >= minVoorwaarde)
                {
                    return(true);
                }
            }
            //zelde als bij stijging maar hier kijken we of de daling voldoet.
            else if (type == TrendType.DALEND)
            {
                if ((AantalGisteren - AantalVandaag) >= minVoorwaarde)
                {
                    return(true);
                }
            }
            else
            {
                if ((AantalVandaag / AantalGisteren) >= trendVerandering)
                {
                    if (entiteit.Trends == null)
                    {
                        entiteit.Trends = new List <Trend>();
                    }
                    entiteit.Trends.Add(newTrend);
                    UpdateEntiteit(p);
                    return(true);
                }
            }
            //als we hier komen wil het zeggen dat er geen trend aanwezig is dus moet de alert niet getriggered worden.
            return(false);
        }
Exemple #37
0
 public static void UpdateTrendStat(TrendType trendType)
 {
     DatabaseProvider.GetInstance().UpdateTrendStat(trendType);
 }
Exemple #38
0
 public static void UpdateTrendStat(TrendType trendType)
 {
     Data.Users.UpdateTrendStat(trendType);
 }
Exemple #39
0
 //public DataTable GetUserInfoByEmail(string email)
 //{
 //    return DbHelper.ExecuteDataset(CommandType.StoredProcedure, string.Format("SELECT [username],[email] FROM [{0}users] WHERE [email]=@email", BaseConfigs.GetTablePrefix),DbHelper.MakeInParam("@email", (DbType)SqlDbType.NVarChar, 50, email)).Tables[0];
 //}
 /// <summary>
 /// ��̳ÿ����Ϣͳ��
 /// </summary>
 /// <param name="trendType">ͳ��������</param>
 public void UpdateTrendStat(TrendType trendType)
 {
     lock (stat)
     {
         stat[trendType]++;
         //�����ϴθ���ʱ��ʱ��������ٴθ���
         if (lastTrendUpdateTime.AddMinutes(5) <= DateTime.Now)
         {
             DbParameter[] parms = {
                              DbHelper.MakeInParam("@daytime",(DbType)SqlDbType.Int,4,DateTime.Now.ToString("yyyyMMdd")),
                              DbHelper.MakeInParam("@login",(DbType)SqlDbType.Int,4, stat[TrendType.Login]),
                              DbHelper.MakeInParam("@register",(DbType)SqlDbType.Int,4, stat[TrendType.Register]),
                              DbHelper.MakeInParam("@topic",(DbType)SqlDbType.Int,4, stat[TrendType.Topic]),
                              DbHelper.MakeInParam("@post",(DbType)SqlDbType.Int,4, stat[TrendType.Post]),
                              DbHelper.MakeInParam("@poll",(DbType)SqlDbType.Int,4, stat[TrendType.Poll]),
                              DbHelper.MakeInParam("@bonus",(DbType)SqlDbType.Int,4, stat[TrendType.Bonus]),
                              DbHelper.MakeInParam("@debate",(DbType)SqlDbType.Int,4, stat[TrendType.Debate])
                           };
             DbHelper.ExecuteNonQuery(CommandType.StoredProcedure, string.Format("{0}updatettrendstat", BaseConfigs.GetTablePrefix), parms);
             Initial();
             //����ǰʱ������Ϊ������ʱ��
             lastTrendUpdateTime = DateTime.Now;
         }
     }
 }
        public static int getInflectionPoint(List <StockKLineBaidu> arr, int startIndex, TrendType trend, bool reversed = false)
        {
            int    index   = -1;
            int    i       = 0;
            double diff    = m_inflectionLimit;
            double subDiff = m_inflectionLimit;

            if (!reversed)
            {
                index = arr.Count;
                for (i = startIndex; i < arr.Count - 1; i++)
                {
                    double curVal     = getCenterPrice(arr[i]);
                    double nextVal    = getCenterPrice(arr[i + 1]);
                    double curSubVal  = getMA5Value(arr[i]);
                    double nextSubVal = getMA5Value(arr[i + 1]);

                    double val    = (nextVal - curVal) / curVal;
                    double subVal = (nextSubVal - curSubVal) / curSubVal;
                    if (trend == TrendType.TT_Up)
                    {
                        if (val < diff && subVal < subDiff)
                        {
                            index = i + 1;
                            break;
                        }
                    }
                    else if (trend == TrendType.TT_Down)
                    {
                        if (val > -diff && subVal < -subDiff)
                        {
                            index = i + 1;
                            break;
                        }
                    }
                }
            }
            else
            {
                index = 0;
                for (i = startIndex; i > 0; i--)
                {
                    double curVal     = getCenterPrice(arr[i]);
                    double prevVal    = getCenterPrice(arr[i - 1]);
                    double curSubVal  = getMA5Value(arr[i]);
                    double prevSubVal = getMA5Value(arr[i - 1]);

                    double val    = (curVal - prevVal) / prevVal;
                    double subVal = (curSubVal - prevSubVal) / prevSubVal;
                    if (trend == TrendType.TT_Up)
                    {
                        if (val < diff && subVal < subDiff)
                        {
                            index = i - 1;
                            break;
                        }
                    }
                    else if (trend == TrendType.TT_Down)
                    {
                        if (val > -diff && subVal < -subDiff)
                        {
                            index = i - 1;
                            break;
                        }
                    }
                }
            }

            return(index);
        }
Exemple #41
0
 public static void UpdateTrendStat(TrendType trendType)
 {
     Data.Users.UpdateTrendStat(trendType);
 }
Exemple #42
0
        //public DataTable GetUserInfoByEmail(string email)
        //{
        //    return DbHelper.ExecuteDataset(CommandType.StoredProcedure, string.Format("SELECT [username],[email] FROM [{0}users] WHERE [email]=@email", BaseConfigs.GetTablePrefix),DbHelper.MakeInParam("@email", (DbType)NpgsqlDbType.Varchar, 50, email)).Tables[0];
        //}

        /// <summary>
        /// 论坛每日信息统计
        /// </summary>
        /// <param name="trendType">统计项名称</param>
        public void UpdateTrendStat(TrendType trendType)
        {
            lock (stat)
            {
                stat[trendType]++;
                //当距上次更新时间时差五分钟再次更新
                if (lastTrendUpdateTime.AddMinutes(5) <= DateTime.Now)
                {
                    DbParameter[] parms = { 
                                     DbHelper.MakeInParam("@daytime",(DbType)NpgsqlDbType.Integer,4,DateTime.Now.ToString("yyyyMMdd")),
                                     DbHelper.MakeInParam("@login",(DbType)NpgsqlDbType.Integer,4, stat[TrendType.Login]),
                                     DbHelper.MakeInParam("@register",(DbType)NpgsqlDbType.Integer,4, stat[TrendType.Register]),
                                     DbHelper.MakeInParam("@topic",(DbType)NpgsqlDbType.Integer,4, stat[TrendType.Topic]),
                                     DbHelper.MakeInParam("@post",(DbType)NpgsqlDbType.Integer,4, stat[TrendType.Post]),
                                     DbHelper.MakeInParam("@poll",(DbType)NpgsqlDbType.Integer,4, stat[TrendType.Poll]),
                                     DbHelper.MakeInParam("@bonus",(DbType)NpgsqlDbType.Integer,4, stat[TrendType.Bonus]),
                                     DbHelper.MakeInParam("@debate",(DbType)NpgsqlDbType.Integer,4, stat[TrendType.Debate])
                                  };
                    string sql = @"SELECT  [daytime]
                        FROM    [dnt_trendstat]
                        WHERE   [daytime] = @daytime";
                    var a = DbHelper.ExecuteScalar(CommandType.Text, sql, parms);
                    if (a == null)
                    {
                        string sql2 = @"  INSERT  INTO [dnt_trendstat]
                    ( [daytime] ,
                      [login] ,
                      [register] ,
                      [topic] ,
                      [post]
                    )
            VALUES  ( @daytime ,
                      0 ,
                      0 ,
                      0 ,
                      0
                    )	;	
		
        UPDATE  [dnt_trendstat]
        SET     [login] = [login] + @login ,
                [register] = [register] + @register ,
                [topic] = [topic] + @topic ,
                [post] = [post] + @post ,
                [poll] = [poll] + @poll ,
                [bonus] = [bonus] + @bonus ,
                [debate] = [debate] + @debate
        WHERE   [daytime] = @daytime";
                        DbHelper.ExecuteNonQuery(CommandType.Text, sql2, parms);

                    }
                    else
                    {
                        string sql2 = @"   	
		
        UPDATE  [dnt_trendstat]
        SET     [login] = [login] + @login ,
                [register] = [register] + @register ,
                [topic] = [topic] + @topic ,
                [post] = [post] + @post ,
                [poll] = [poll] + @poll ,
                [bonus] = [bonus] + @bonus ,
                [debate] = [debate] + @debate
        WHERE   [daytime] = @daytime";
                        DbHelper.ExecuteNonQuery(CommandType.Text, sql2, parms);

                    }


                    Initial();
                    //将当前时间设置为最后更新时间
                    lastTrendUpdateTime = DateTime.Now;
                }
            }
        }