Exemple #1
0
        public async Task <bool> Delete(HistoricalPrice contract)
        {
            var entity = ContractToEntity(contract);
            var result = await _hpRepo.Delete(entity);

            return(result);
        }
Exemple #2
0
 /*****************************************************************************
 *  FUNCTION:  CalculatePctChange
 *  Description:
 *  Parameters:
 *****************************************************************************/
 private void CalculatePctChange()
 {
     if (hist_price.Count() > 0)
     {
         pctChange = Math.Round(((HistoricalPrice.Last() - HistoricalPrice.First()) / HistoricalPrice.First()) * 100, 2);
     }
 }
Exemple #3
0
        public async Task <HistoricalPrice> Update(HistoricalPrice contract)
        {
            var entity = ContractToEntity(contract);

            entity = await _hpRepo.Update(entity);

            return(EntityToContract(entity));
        }
Exemple #4
0
 /*****************************************************************************
 *  FUNCTION:  CalculateAvgPrice
 *  Description:
 *  Parameters:
 *****************************************************************************/
 private void CalculateAvgPrice()
 {
     if (HistoricalPrice.Count() > 0)
     {
         avgPrice          = Math.Round(HistoricalPrice.Average(), 2);
         avgDailyPctChange = HistoricalPctChange.Average();
         avgDailyVolume    = (long)HistoricalVolumes.Average();
     }
 }
        public bool TryGetLastPrice(string ticker, Exchange?exchange, AssetClass assetType, out HistoricalPrice lastPrice, out string message)
        {
            //Last two months???
            //https://query1.finance.yahoo.com/v8/finance/chart/AAPL?region=US&lang=en-US&includePrePost=false&interval=2m&range=1d&corsDomain=finance.yahoo.com&.tsrc=finance

            //Daily, last day
            //https://query1.finance.yahoo.com/v8/finance/chart/AAPL?lang=en-US&includePrePost=false&interval=1d&range=1d

            //Daily, last 5 days
            //https://query1.finance.yahoo.com/v8/finance/chart/AAPL?lang=en-US&includePrePost=false&interval=1d&range=5d

            int days = 1;
            YahooChartInterval interval = YahooChartInterval.OneHour;
            bool ok = YahooApiCaller.GetDailyPrices(ticker, interval, days, out HttpStatusCode statusCode, out YahooChartResponse yahooResponse, out string jsonResponse, out message);

            if (ok && statusCode == HttpStatusCode.OK && yahooResponse != null && yahooResponse.Chart != null && yahooResponse.Chart.Result != null && yahooResponse.Chart.Result.Length > 0)
            {
                var     result = yahooResponse.Chart.Result.Last();
                int     length = result.TimeStampsAsLong.Length;
                decimal?close  = null;
                int     i      = length - 1;
                while (close == null && i > 0)
                {
                    if (result.Indicators.Quote[0].Close[i].HasValue)
                    {
                        close = result.Indicators.Quote[0].Close[i].Value;
                    }
                    else
                    {
                        i--;
                    }
                }
                int      index   = i;
                long     seconds = result.TimeStampsAsLong[index];
                DateTime dt      = DATE_1970.AddSeconds(seconds);
                decimal  price   = result.Indicators.Quote[0].Close[index].Value;
                ulong    volume  = result.Indicators.Quote[0].Volume[index].Value;
                lastPrice = new HistoricalPrice()
                {
                    Date   = dt,
                    Close  = price,
                    Volume = volume,
                };
                return(true);
            }
            else
            {
                lastPrice = null;
                return(false);
            }
        }
Exemple #6
0
        private Entities.Trade.HistoricalPrice ContractToEntity(HistoricalPrice contract)
        {
            var entity = new Entities.Trade.HistoricalPrice
            {
                Exchange = contract.Exchange,
                Pair     = contract.Pair,
                Price    = contract.Price,
                High     = contract.High,
                Low      = contract.Low,
                Snapshot = contract.Snapshot
            };

            return(entity);
        }
Exemple #7
0
        private HistoricalPrice TickerToHistoricalPrice(Ticker ticker, Exchange exchange)
        {
            var hp = new HistoricalPrice
            {
                Exchange = exchange,
                High     = ticker.High,
                Low      = ticker.Low,
                Pair     = ticker.Pair,
                Price    = ticker.LastPrice,
                Snapshot = DateTime.UtcNow
            };

            return(hp);
        }
Exemple #8
0
        private HistoricalPrice EntityToContract(Entities.Trade.HistoricalPrice entity)
        {
            var contract = new HistoricalPrice
            {
                Exchange = entity.Exchange,
                Pair     = entity.Pair,
                Price    = entity.Price,
                High     = entity.High,
                Low      = entity.Low,
                Snapshot = entity.Snapshot
            };

            return(contract);
        }
Exemple #9
0
        public bool TryGetFromCache(string ticker, Exchange?exchange, DateTime?from, DateTime?to, PriceInterval interval, out PriceList prices)
        {
            prices = new PriceList();
            try
            {
                string fileName = $"{ticker}";
                if (exchange.HasValue)
                {
                    fileName += $"_{exchange}";
                }

                if (from.HasValue)
                {
                    fileName += $"_{from}";
                }

                if (to.HasValue)
                {
                    fileName += $"_{to}";
                }

                fileName += $"_{interval.ToString()}.csv";

                string file = Path.Combine(FOLDER, fileName);

                if (File.Exists(file))
                {
                    string[] lines = File.ReadAllLines(file);
                    for (int i = 1; i < lines.Length; i++)
                    {
                        HistoricalPrice p = HistoricalPrice.From(lines[i]);
                        prices.Add(p);
                    }
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception)
            {
                return(false);
            }
#pragma warning restore CA1031 // Do not catch general exception types
        }
        //public async Task Load()
        //{
        //"MGLU3.SA"
        //var result = await Yahoo.GetHistoricalAsync("MGLU3.SA", new DateTime(2011, 05, 01), DateTime.Now, Period.Daily);

        //HistoricalPrice.AddRange(result.Where(a => a.Close != 0).ToList().ConvertAll(a => PBL_YahooFinance.BLL.Converter.ItemToFileHelperDto(a)));

        //var closePrice = result.Where(a => a.Close != 0).Select(a => a.Close).ToList();
        //var dateArray = result.Where(a => a.Close != 0).Select(a => a.DateTime.ToString("MM/dd/yyyy")).ToArray();

        //await LoadChart(closePrice, dateArray);

        //RaiseAllCanExecuteChanged();
        //}

        private async Task LoadHistoricalPrice()
        {
            StatusMessage = "Status: Loading...";
            var result = await Yahoo.GetHistoricalAsync(LoadAsset, StartDate, EndDate, Period.Daily);

            HistoricalPrice.Clear();
            HistoricalPrice.AddRange(result.Where(a => a.Close != 0)
                                     .OrderByDescending(a => a.DateTime)
                                     .ToList()
                                     .ConvertAll(a => PBL_YahooFinance.BLL.Converter.ItemToFileHelperDto(a)));

            var closePrice = result.Where(a => a.Close != 0).Select(a => a.Close).ToList();
            var dateArray  = result.Where(a => a.Close != 0).Select(a => a.DateTime.ToString("MM/dd/yyyy")).ToArray();

            await LoadChart(closePrice, dateArray);

            RaiseAllCanExecuteChanged();
            StatusMessage = "Status: Success.";
        }
        static void Main(string[] args)
        {
            MercuryContext mercury = new MercuryContext();

            //Product product = new Product()
            //{
            //    ProductName = "ETTAN",
            //    Price = 51.0m
            //};

            //mercury.Products.Add(product);
            //mercury.SaveChanges();


            var productToUpdate = mercury.Products
                                  .FirstOrDefault(o => o.ProductName.ToLower() == "ettan");

            //if(productToUpdate != null)
            //{
            //productToUpdate.Price *= 0.9m;
            //mercury.SaveChanges();
            //}

            bool done = false;

            while (!done)
            {
                HistoricalPrice hp = mercury
                                     .HistoricalPrices
                                     .FirstOrDefault(p => p.ProductsId == productToUpdate.Id);

                done = hp == null;

                if (!done)
                {
                    mercury.HistoricalPrices.Remove(hp);
                    mercury.SaveChanges();
                }
            }

            mercury.Products.Remove(productToUpdate);
            mercury.SaveChanges();
        }
Exemple #12
0
 public override async Task GetHistoricalPriceStreams(HistoricalPriceRequest request,
                                                      IServerStreamWriter <HistoricalPrice> responseStream, ServerCallContext context)
 {
     Logger.Here().Information("BGN");
     try {
         while (!context.CancellationToken.IsCancellationRequested)
         {
             String key = Constants.Redis.HISTORIC_PRICE + PriceType.TenSeconds +
                          "_" + request.Ticker;
             var secondPrice = redis.StringGet(key);
             if (secondPrice.HasValue)
             {
                 byte[]          bytes   = (RedisValue)secondPrice;
                 HistoricalPrice current = HistoricalPrice.Parser.ParseFrom(bytes);
                 await responseStream.WriteAsync(current);
             }
             //await Task.Delay(1 * 1000); // HACK: This should be an observable and not sleeping
         }
     } catch (Exception e) {
         Logger.Here().Warning(e.Message);
         throw new RpcException(new Status(StatusCode.Internal, e.Message));
     }
 }
        public bool TryGetHistoricalPrices(string ticker, Exchange?exchange, DateTime?from, DateTime?to, PriceInterval priceInterval, out PriceList prices, out string errorMessage)
        {
            double fromValue;

            if (from.HasValue)
            {
                fromValue = (from.Value - DATE_1970).TotalSeconds;
            }
            else
            {
                fromValue = (FIRST_DATE - DATE_1970).TotalSeconds;
            }

            double toValue;

            if (to.HasValue)
            {
                toValue = (to.Value - DATE_1970).TotalSeconds;
            }
            else
            {
                toValue = (DateTime.Now - DATE_1970).TotalSeconds;
            }


            string content = YahooApiCaller.GetHistoricalPrices(ticker, fromValue, toValue, priceInterval);

            string[] lines = content.Split('\n');
            prices = new PriceList();
            for (int i = 1; i < lines.Length; i++)
            {
                HistoricalPrice p = HistoricalPrice.From(lines[i]);
                prices.Add(p);
            }
            errorMessage = "ok";
            return(true);
        }
Exemple #14
0
        public bool TryGetLastPrice(string ticker, Exchange?exchange, AssetClass assetType, out HistoricalPrice lastPrice, out string message)
        {
            //https://api.nasdaq.com/api/quote/TQQQ/info?assetclass=etf
            //https://api.nasdaq.com/api/quote/AAPL/info?assetclass=stocks
            bool ok = NasdaqApiCaller.GetStockSummary(ticker, exchange, assetType, out HttpStatusCode statusCode, out NasdaqResponse nasdaqResponse, out string jsonResponse, out message);

            if (statusCode == HttpStatusCode.OK)
            {
                if (nasdaqResponse.Status.Code == 200)
                {
                    string temp = nasdaqResponse.Data.PrimaryData.LastSalePriceAsString;
                    lastPrice       = new HistoricalPrice();
                    lastPrice.Close = decimal.Parse(temp.Substring(1), ConvertionsExtensions.EnUs_CultureInfo);
                    temp            = nasdaqResponse.Data.PrimaryData.LastTradeTimestampAsString;
                    lastPrice.Date  = ParseDateTime(temp);

                    /*
                     * temp = rawdata.data.keyStats.Volume.value.ToString();
                     * lastPrice.Volume = int.Parse(temp, NumberStyles.Integer | NumberStyles.AllowThousands, enUsCultureInfo);
                     * temp = rawdata.data.keyStats.PreviousClose.value.ToString();
                     * lastPrice.PreviousClose = decimal.Parse(temp.Substring(1), enUsCultureInfo);
                     */

                    return(true);
                }
                else if (nasdaqResponse.Status.Code == 400 && nasdaqResponse.Status.CodeMessage.Count > 0)
                {
                    lastPrice = null;
                    var nasdaqMessage = nasdaqResponse.Status.CodeMessage[0];
                    message = $"{nasdaqMessage.ErrorMessage} (Code={nasdaqMessage.Code})";
                    return(false);
                }
            }
            lastPrice = null;
            return(false);
        }
Exemple #15
0
        public bool TryGetHistoricalPrices(string ticker, Exchange?exchange, DateTime?from, DateTime?to, PriceInterval interval, out PriceList prices, out string errorMessage)
        {
            //https://api.nasdaq.com/api/quote/AAPL/chart?assetclass=stocks&fromdate=2010-04-15&todate=2020-04-15
            if (from.HasValue == false)
            {
                from = DateTime.Now;
            }

            if (to.HasValue == false)
            {
                to = DateTime.Now;
            }

            bool ok = NasdaqApiCaller.GetPrices(ticker, exchange, from.Value, to.Value, interval, out HttpStatusCode statusCode, out NasdaqResponse nasdaqResponse, out string jsonResponse, out errorMessage);

            prices = new PriceList();
            foreach (var nasdaqPrice in nasdaqResponse.Data.Prices)
            {
                HistoricalPrice price = new HistoricalPrice();
                price.Close = nasdaqPrice.Price;
                prices.Add(price);
            }
            return(true);
        }
Exemple #16
0
        public async Task <bool> Get([FromQuery] string name,
                                     [FromQuery] int?price,
                                     [FromQuery] Rarity?rarity,
                                     [FromQuery] ItemCategory?category,
                                     [FromQuery(Name = "ext")] bool?extraordinary)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return(false);
            }
            if (price == null)
            {
                return(false);
            }
            if (rarity == null)
            {
                return(false);
            }
            if (category == null)
            {
                return(false);
            }
            if (extraordinary == null)
            {
                return(false);
            }

            var ipEntry = await _marketContext.IPs.SingleOrDefaultAsync(k => k.IP == HttpContext.Connection.RemoteIpAddress.ToString());

            if (ipEntry == null)
            {
                ipEntry = new IPEntry()
                {
                    IP = HttpContext.Connection.RemoteIpAddress.ToString()
                };
            }
            if (ipEntry.Blocked)
            {
                return(false);
            }

            var item = await _marketContext.Items.SingleOrDefaultAsync(i => i.Name == name && i.Rarity == rarity);

            if (item == null)
            {
                item = new Item()
                {
                    Name = name, Rarity = rarity, ItemCategory = category, IsExtraordinary = extraordinary
                };
            }
            else
            {
                var mostRecentPrice = await _marketContext.MostRecentPrices.SingleAsync(mrp => mrp.ItemID == item.ID);

                if (mostRecentPrice.Marks == price && mostRecentPrice.Time.AddHours(3) > DateTime.UtcNow)
                {
                    //Ignore duplicated prices if they happen over a small time window
                    return(false);
                }
            }

            var newPrice = new HistoricalPrice()
            {
                Item = item, Marks = price.Value, Time = DateTime.UtcNow, IP = ipEntry
            };

            _marketContext.Prices.Add(newPrice);

            await _marketContext.SaveChangesAsync();

            return(true);
        }
 /// <summary>
 /// It updates the market value if there is quantity.
 /// </summary>
 /// <param name="price"></param>
 public decimal?UpdateMarketValue(HistoricalPrice price, decimal?defaultValue)
 {
     return(UpdateMarketValue(price.Close, price.Date, defaultValue));
 }
Exemple #18
0
        public static Action <RedisChannel, RedisValue> TransactionProcessHandler(ILogger logger,
                                                                                  IDatabase redis)
        {
            return((channel, message) => {
                logger.Here().Information("BGN");
                byte[] bytes = message;
                TransactionProcessed transaction = TransactionProcessed.Parser.ParseFrom(bytes);
                RedisValue transactionId = redis.StringGet(transaction.TransactionId);
                if (transactionId.HasValue)
                {
                    return;
                }

                redis.StringSet(transaction.TransactionId, "1", TimeSpan.FromMinutes(EXPIRATION_MINUTES));
                logger.Here().Information("Updating Quote");
                CacheData data = Cache.Get(redis, transaction.Ticker);
                Quote quote = new Quote();
                bool isNewer = (data == null || transaction.CreatedTimestamp > data.Timestamp);
                quote.Bid = isNewer ? transaction.Level2.Bids[0].Price : data.Quote.Bid;
                quote.Ask = isNewer ? transaction.Level2.Asks[0].Price : data.Quote.Ask;
                quote.Last = isNewer ? transaction.Last : data.Quote.Last;
                quote.Volume = (data == null ? 0 : data.Quote.Volume) +
                               transaction.Volume;
                Cache.Set(redis, transaction.Ticker,
                          new CacheData(isNewer ? transaction.CreatedTimestamp : data.Timestamp,
                                        quote, isNewer ? transaction.Level2 : data.Level2));

                logger.Here().Information("Updating HistoricPrice 10 seconds");
                String key = Constants.Redis.HISTORIC_PRICE + PriceType.TenSeconds +
                             "_" + transaction.Ticker;
                RedisValue secondPrice = redis.StringGet(key);
                if (secondPrice.HasValue)
                {
                    byte[] secondPriceBytes = (RedisValue)secondPrice;
                    HistoricalPrice current = HistoricalPrice.Parser.ParseFrom(secondPriceBytes);
                    if ((current.Timestamp + (10 * TimeSpan.TicksPerSecond)) > transaction.CreatedTimestamp)
                    {
                        current.Close = transaction.Last;
                        if (transaction.Last > current.High)
                        {
                            current.High = transaction.Last;
                        }
                        if (transaction.Last < current.Low)
                        {
                            current.Low = transaction.Last;
                        }
                        current.Volume += transaction.Volume;
                        redis.StringSet(key, current.ToByteArray());
                    }
                    else
                    {
                        redis.StringSet(key, new HistoricalPrice()
                        {
                            Timestamp = ToTop10Second(transaction.CreatedTimestamp),
                            Open = transaction.Last,
                            Close = transaction.Last,
                            High = transaction.Last,
                            Low = transaction.Last,
                            Volume = transaction.Volume
                        }.ToByteArray());
                    }
                }
                else
                {
                    redis.StringSet(key, new HistoricalPrice()
                    {
                        Timestamp = ToTop10Second(transaction.CreatedTimestamp),
                        Open = transaction.Last,
                        Close = transaction.Last,
                        High = transaction.Last,
                        Low = transaction.Last,
                        Volume = transaction.Volume
                    }.ToByteArray());
                }

                logger.Here().Information("END");
            });
        }
 public bool TryGetLastPrice(string ticker, Exchange?exchange, AssetClass assetType, out HistoricalPrice lastPrice, out string message)
 {
     return(pricesDataSouce.TryGetLastPrice(ticker, exchange, assetType, out lastPrice, out message));
 }
Exemple #20
0
 public void Update(HistoricalPrice product)
 {
     throw new System.NotImplementedException();
 }
 public bool TryGetLastPrice(string ticker, Exchange?exchange, AssetClass assetType, out HistoricalPrice lastPrice, out string message)
 {
     throw new NotImplementedException();
 }