Exemple #1
0
        //------------------ helper methods -------------------
        private static long GetTimeTrade(string url, out int id)
        {
            Thread.Sleep(100);
            var requester = new PublicKeyRequiredRequester();
            var response  = requester.Request(url, Resources.PUBLIC_KEY);

            using (Stream stream = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                string       s  = sr.ReadToEnd();

                List <StockExchenge.MarketTradesHistory.Trade> trades = null;
                try
                {
                    trades = JConverter.JsonConver <List <StockExchenge.MarketTradesHistory.Trade> >(s);
                }
                catch (Exception)
                {
                    Console.WriteLine($"Response: {s}");
                }

                if (trades?.Count > 0)
                {
                    var tradeFirst = trades.First();
                    id = tradeFirst.ID;
                    return(tradeFirst.Time);
                }
                else
                {
                    Console.WriteLine($"NOT FOUND");
                }
                id = 0;
                return(0);
            }
        }
        public void GetDateTrade()
        {
            var requester     = new PublicKeyRequiredRequester();
            var fromIdStart   = 0L;
            var isFoundtrades = true;

            while (isFoundtrades)
            {
                var response = requester.Request(GetUrl(PAIR, fromIdStart), Resources.PUBLIC_KEY);
                using (Stream stream = response.GetResponseStream())
                {
                    StreamReader sr = new StreamReader(stream);
                    string       s  = sr.ReadToEnd();

                    List <StockExchenge.MarketTradesHistory.Trade> trades = null;
                    try
                    {
                        trades = JConverter.JsonConver <List <StockExchenge.MarketTradesHistory.Trade> >(s);
                    }
                    catch (Exception)
                    {
                        Console.WriteLine($"Response: {s}");
                        break;
                    }

                    if (trades?.Count > 0)
                    {
                        var tradeFirst = trades.First();
                        var tradesLast = trades.Last();

                        Console.WriteLine($"STSRT TIME {tradeFirst.ID}: {tradeFirst.Time.UnixToDateTime()}");
                        Console.WriteLine($"FINISH TIME {tradesLast.ID}: {tradesLast.Time.UnixToDateTime()}");
                    }
                    else
                    {
                        Console.WriteLine($"NOT FOUND");
                        isFoundtrades = false;
                    }
                }
                fromIdStart += LIMIT;
                Thread.Sleep(1000);
            }
        }
        /// <summary>
        /// Скачиваем все последователно
        /// </summary>
        /// <returns></returns>
        private async Task <int> LoadAll()
        {
            return(await Task.Run(() =>
            {
                OnLoadStateEvent("TradesHistory: START");
                var url = GetUrl();
                var requester = new PublicKeyRequiredRequester();

                IsActiveLoad = true;
                var countRequest = 0;
                while (IsActiveLoad)
                {
                    countRequest++;
                    try
                    {
                        var response = requester.Request(GetUrl(), Resources.PUBLIC_KEY);
                        using (Stream stream = response.GetResponseStream())
                        {
                            StreamReader sr = new StreamReader(stream);
                            string s = sr.ReadToEnd();

                            var trades = JConverter.JsonConver <List <StockExchenge.MarketTradesHistory.Trade> >(s);
                            var tradesDB = new List <DataBaseWork.Models.TradeHistory>();

                            foreach (var trade in trades)
                            {
                                if (dateEndUnix.HasValue && trade.Time > dateEndUnix.Value)
                                {
                                    IsActiveLoad = false;
                                    OnLoadStateEvent($"TradesHistory загрузка завершена: время последней загруженной сделки = {trade.Time.UnixToDateTime()}");
                                    break;
                                }
                                tradesDB.Add(new DataBaseWork.Models.TradeHistory()
                                {
                                    TradeId = trade.ID,
                                    Pair = pair,
                                    Price = trade.Price,
                                    Qty = trade.Qty,
                                    Time = trade.Time,
                                    QuoteQty = trade.QuoteQty,
                                    IsBestMatch = trade.IsBestMatch,
                                    IsBuyerMaker = trade.IsBuyerMaker
                                });
                            }
                            tradeHistoryBuffer.AddRange(tradesDB);
                            fromId += trades.Count();                             // альтернатива: max Id или last Id

                            var statusCode = (int)response.StatusCode;
                            if (statusCode == 418 || statusCode == 429)
                            {
                                var secondSleep = 0;
                                var headers = response.Headers;
                                for (int i = 0; i < headers.Count; i++)
                                {
                                    if (headers.GetKey(i).ToLower() == "retry-after")
                                    {
                                        int.TryParse(headers[i], out secondSleep);
                                        OnLoadStateEvent($"TradesHistory retry-after header: secondSleep = {secondSleep}");
                                    }
                                }
                                if (secondSleep == 0)
                                {
                                    secondSleep = 60;
                                }
                                Thread.Sleep(secondSleep * 1000);
                                OnLoadStateEvent($"Status Code: {statusCode}; secondSleep = {secondSleep * 1000}");
                            }
                            else if (statusCode == 200)
                            {
                                if (trades.Count == 0)
                                {
                                    OnLoadStateEvent($"TradesHistory statusCode: {statusCode}. trades.Count == 0");
                                    break;
                                }
                                if (countRequest % 100 == 0)
                                {
                                    OnLoadStateEvent($"TradesHistory time load: {trades.Last().Time.UnixToDateTime()}");
                                }
                            }
                            else
                            {
                                OnLoadStateEvent($"TradesHistory: STOP (statusCode: {statusCode})");
                                return -1;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // запись лога в БД
                        OnLoadStateEvent($"TradesHistory error: возможно указана неверная пара.");
                        return -1;
                    }
                }
                tradeHistoryBuffer.Save();
                OnLoadStateEvent("TradesHistory: STOP");
                return 1;
            }));
        }