示例#1
0
文件: Signal.cs 项目: AlienJust/RPD
        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;
        }
        /// <summary>
        /// Adds a message duration to the consumer stats
        /// </summary>
        /// <param name="messageProducerId"></param>
        /// <param name="duration"></param>
        public static void Add(Guid messageProducerId, TimeSpan duration)
        {
            if (!_producers.ContainsKey(messageProducerId))
            {
                _producers[messageProducerId] = new Trend(messageProducerId);
            }

            _totals.Add(duration);
            _producers[messageProducerId].Add(duration);
        }
示例#3
0
        protected override decimal ComputeNextValue(IndicatorDataPoint input)
        {
            Price.Add(input);

            if (Price.Samples > 2)
            {
                // From Ehlers page 16 equation 2.9
                var it = (a - ((a / 2) * (a / 2))) * Price[0].Value + ((a * a) / 2) * Price[1].Value
                         - (a - (3 * (a * a) / 4)) * Price[2].Value + 2 * (1 - a) * Trend[0].Value
                         - ((1 - a) * (1 - a)) * Trend[1].Value;
                Trend.Add(new IndicatorDataPoint(input.Time, it));
            }
            else
            {
                Trend.Add(new IndicatorDataPoint(input.Time, Price[0].Value));
            }

            return(Trend[0].Value);
        }
示例#4
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var trend =
                await Cache.GetRecordAsync <Dictionary <int, List <Trend> > >(RedisKeyM)
                ?? new Dictionary <int, List <Trend> >();

            Logger.LogInformation("Loaded {0} existing Trend rows.", trend.Count);
            var forecast =
                await Cache.GetCompressedRecordAsync <List <Data> >(RedisKeyF)
                ?? new List <Data>();

            Logger.LogInformation("Loaded {0} existing Forecast rows.", forecast.Count);
            string endpointM = $"http://api.openweathermap.org/data/2.5/group?id={string.Join(',', keys)}&units=metric&appid={Config["OpenWeatherApiKey"]}";

            while (!stoppingToken.IsCancellationRequested)
            {
                var waitMins = (85 - DateTime.Now.Minute) % 60;
                Logger.LogInformation("{0}, waiting until {1}, {2} minutes...", DateTimeOffset.Now, DateTime.Now.AddMinutes(waitMins), waitMins);
                await Task.Delay((int)TimeSpan.FromMinutes(waitMins).TotalMilliseconds, stoppingToken);

                try
                {
                    using (var http = new HttpClient())
                    {
                        var responseM = await http.GetAsync(endpointM);

                        var temp = JsonSerializer.Deserialize <Response>(
                            await responseM.Content.ReadAsStringAsync(), JsonOptions);
                        foreach (var m in temp.list)
                        {
                            if (trend.TryGetValue(m.id, out var t))
                            {
                                var last = t[t.Count - 1];
                                if (!last.TimeStamp.Equals(m.dt))
                                {
                                    t.Add(Trend.Add(t[t.Count - 1], m));
                                }
                                if (t.Count > 48)
                                {
                                    t.RemoveAt(0);
                                }
                            }
                            else
                            {
                                trend.Add(m.id, new List <Trend>(new Trend[] { Trend.Add(null, m) }));
                            }
                            forecast.Add(new Data(DataType.actual, m.id, m.dt, 0, m.main, m.wind, m.clouds));
                            if (m.dt.Hour % 3 == 0)
                            {
                                string endpointF = $"http://api.openweathermap.org/data/2.5/forecast?id={m.id}&units=metric&appid={Config["OpenWeatherApiKey"]}";
                                var    responseF = await http.GetAsync(endpointF);

                                var fc = JsonSerializer.Deserialize <Response>(await responseF.Content.ReadAsStringAsync(), JsonOptions);
                                forecast.AddRange(fc.list.Select(f => new Data(DataType.forecast, fc.city.id, f.dt, (int)(f.dt - m.dt).TotalMinutes, f.main, f.wind, f.clouds)));
                            }
                        }
                        forecast.RemoveAll(f => f.dt.CompareTo(DateTime.Now.AddDays(-4)) < 0);
                        await Cache.SetRecordAsync(RedisKeyM, trend);

                        await Cache.SetCompressedRecordAsync(RedisKeyF, forecast);

                        Logger.LogInformation("Saved {0} Trend Rows and {1} Forecast Rows.", trend.Count, forecast.Count);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                await Task.Delay((int)TimeSpan.FromMinutes(2).TotalMilliseconds, stoppingToken);
            }
        }
示例#5
0
        static void Main(string[] args)
        {
            var apiKey     = ConfigurationManager.AppSettings["ApiKey"];
            var apiSecret  = ConfigurationManager.AppSettings["SecretKey"];
            var passPhrase = ConfigurationManager.AppSettings["PassPhrase"];

            var trendSize     = int.Parse(ConfigurationManager.AppSettings["TrendItemCount"]);
            var windowSize    = int.Parse(ConfigurationManager.AppSettings["TrendWindow"]);
            var pauseInterval = int.Parse(ConfigurationManager.AppSettings["PauseInterval"]);

            var playerQuota = decimal.Parse(ConfigurationManager.AppSettings["PlayerQuota"]);
            var perBidValue = decimal.Parse(ConfigurationManager.AppSettings["PerBidValue"]);

            Authenticator auth = new Authenticator(apiKey, apiSecret, passPhrase);

            GDAXClient.GDAXClient client = new GDAXClient.GDAXClient(auth, false);
            //var result = client.OrdersService.PlaceLimitOrderAsync(OrderSide.Buy, ProductType.LtcUsd, 0.5M, 20).Result;


            var player = new Player(client, playerQuota, perBidValue);
            var trend  = new Trend(trendSize, windowSize);
            var view   = new ConsoleView(player, trend);

            while (true)
            {
                try
                {
                    var trades        = client.ProductsService.GetProductTradesAsync(player.ProductType).Result.ToList();
                    var currentTicker = client.ProductsService.GetProductTickerAsync(player.ProductType).Result;

                    var buyTrades  = trades.FindAll(t => t.Side == "buy");
                    var sellTrades = trades.FindAll(t => t.Side == "sell");

                    var tradeMedian = GetMedian(trades);
                    var buyMedian   = GetMedian(buyTrades);
                    var sellMedian  = GetMedian(sellTrades);
                    var buyVolume   = buyTrades.Sum(t => t.Size);
                    var sellVolume  = sellTrades.Sum(t => t.Size);

                    var trade = new Trade()
                    {
                        DateTime    = currentTicker.Time,
                        Price       = Decimal.Round(currentTicker.Price, 2),
                        BidPrice    = Decimal.Round(currentTicker.Bid, 2),
                        AskPrice    = Decimal.Round(currentTicker.Ask, 2),
                        TradeMedian = Decimal.Round(tradeMedian, 2),
                        BuyMedian   = Decimal.Round(buyMedian, 2),
                        BuyVolume   = Decimal.Round(buyVolume, 2),
                        SellMedian  = Decimal.Round(sellMedian, 2),
                        SellVolume  = Decimal.Round(sellVolume, 2)
                    };
                    trend.Add(trade);
                    view.Show();
                    //Console.WriteLine($"Time: {trade.DateTime}, Price: {trade.Price}, Bid: {trade.BidPrice}, Ask: {trade.AskPrice}, TradeM: {trade.TradeMedian}, BuyM: {trade.BuyMedian}, SellM: {trade.SellMedian}, BV: {trade.BuyVolume}, SV: {trade.SellVolume}, MedianScore: {trade.MedianScore}");

                    player.Play(trend, trade);
                }
                catch (Exception ex)
                {
                    view.ShowError(ex);
                    Helper.WriteError(ex);
                }
                Thread.Sleep(pauseInterval);
            }
        }