Example #1
0
        public OrderResponse OrderLimit(string paramOrd, string publicKey, string secretKey)
        {
            string correctParam = paramOrd.Replace("_", "");

            var    privateApi = new SecretKeyRequiredRequester();
            string response   = string.Empty;

            Regex  my_reg     = new Regex(@"\D");
            string serverTime = string.Empty;

            try
            {
                serverTime = my_reg.Replace(ServiceRequests.ServerTime(), "");
            }
            catch (Exception ex)
            {
                // TODO: loging
            }

            string url_order     = "https://api.binance.com/api/v3/order?" + correctParam + "&type=LIMIT&recvWindow=5000&timeInForce=GTC&timestamp=" + serverTime;
            string api_parametrs = correctParam + "&type=LIMIT&recvWindow=5000&timeInForce=GTC&timestamp=" + serverTime;

            try
            {
                response = privateApi.GetWebRequest(url_order, api_parametrs, publicKey, secretKey, "POST");
            }
            catch (Exception ex)
            {
                // TODO: ВЫВЕСТИ НА МОРДУ
            }

            return(JConverter.JsonConver <OrderResponse>(response));
        }
        private void GetHistoryCandle()
        {
            try
            {
                var klineString = kline.GetHistory();
                var klines      = JConverter.JsonConver <List <object[]> >(klineString);

                foreach (var k in klines)
                {
                    var ohlcPoint = new OhlcPoint()
                    {
                        Open  = Convert.ToDouble(k[1], new CultureInfo("en-US")),
                        High  = Convert.ToDouble(k[2], new CultureInfo("en-US")),
                        Low   = Convert.ToDouble(k[3], new CultureInfo("en-US")),
                        Close = Convert.ToDouble(k[4], new CultureInfo("en-US"))
                    };
                    OhclValues.Add(ohlcPoint);
                    LabelsX.Add(Convert.ToInt64(k[0]).UnixToDateTime().ToString(formatX));
                }
            }
            catch (Exception ex)
            {
                // запись логов в БД
            }
        }
Example #3
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);
            }
        }
Example #4
0
        private void GetHistoryCandle()
        {
            try
            {
                candles.Clear();
                kline = new Kline(SelectedPair, SelectedInterval);
                var klineString = kline.GetHistory();
                var klines      = JConverter.JsonConver <List <object[]> >(klineString);

                foreach (var k in klines)
                {
                    var ohlcPoint = new Charts.Models.Candle(
                        Convert.ToInt64(k[0], new CultureInfo("en-US")),
                        Convert.ToDouble(k[2], new CultureInfo("en-US")),
                        Convert.ToDouble(k[3], new CultureInfo("en-US")),
                        Convert.ToDouble(k[1], new CultureInfo("en-US")),
                        Convert.ToDouble(k[4], new CultureInfo("en-US")));
                    candles.Add(ohlcPoint);
                }
            }
            catch (Exception ex)
            {
                // запись логов в БД
            }
        }
Example #5
0
        public async Task <int> Rquest1()
        {
            try
            {
                HttpWebRequest reqGET = (HttpWebRequest)WebRequest.Create(@"https://api.binance.com/api/v3/historicalTrades?symbol=BTCUSDT&fromId=1&limit=10");
                reqGET.Accept      = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                reqGET.UserAgent   = "Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0";
                reqGET.ContentType = "application/x-www-form-urlencoded";
                reqGET.Headers.Add("X-MBX-APIKEY", "33SB2WjAtgVzFjcSGLE4fuvxzBQD8sz475bmC29UI8WCwtOVmdKwzqu78zVD6pqx");


                HttpWebResponse response = (HttpWebResponse)await reqGET.GetResponseAsync();

                var status = (int)response.StatusCode;
                countRequest++;
                Console.Clear();
                Console.WriteLine($"{status} count: {countRequest}");

                WebHeaderCollection headers = response.Headers;
                for (int i = 0; i < headers.Count; i++)
                {
                    //Console.WriteLine("{0}: {1}", headers.GetKey(i), headers[i]);
                }


                Stream       stream = response.GetResponseStream();
                StreamReader sr     = new StreamReader(stream);
                string       s      = sr.ReadToEnd();
                var          trades = JConverter.JsonConver <List <StockExchenge.MarketTradesHistory.Trade> >(s);
                //Console.WriteLine(s);


                return(status);
            }
            catch (WebException ex)
            {
                var resp = (HttpWebResponse)ex.Response;
                if (resp != null)
                {
                    var status = (int)resp.StatusCode;
                    Console.WriteLine(status);
                    return(status);
                }
                else
                {
                    Console.WriteLine(ex.Message);
                    return(-1);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(-2);
                return(-2);
            }
        }
Example #6
0
        //public List<Trade> RequestedTrades(string publicKey, string secretKey, TradeConfiguration configuration)
        //{
        //    var trades = TradesRequest(publicKey, secretKey, $"{configuration.MainCoin}{configuration.AltCoin}");
        //    if (trades != null)
        //    {
        //        foreach (var trade in trades)
        //        {
        //            tradeRepository.Create(new DataBaseWork.Models.Trade()
        //            {
        //                FK_PublicKey = publicKey,
        //                Symbol = trade.symbol,
        //                TradeID = trade.id,
        //                OrderID = trade.orderId,
        //                OrderListID = trade.orderListId,
        //                Price = trade.price,
        //                Qty = trade.qty,
        //                QuoteQty = trade.quoteQty,
        //                Commission = trade.commission,
        //                CommissionAsset = trade.commissionAsset,
        //                Time = trade.time,
        //                IsBuyer = trade.isBuyer,
        //                IsMaker = trade.isMaker,
        //                IsBestMatch = trade.isBestMatch
        //            });
        //        }
        //    }
        //    return trades;
        //}

        private List <Trade> TradesRequest(string key, string secret, string pair, long fromId)
        {
            logService.Write("***********TradesRequest START***********", true);
            logService.Write($"\tTradesRequest Public key: {key}");
            logService.Write($"\tTradesRequest pair: {pair}");
            List <Trade> result     = null;
            var          privateApi = new SecretKeyRequiredRequester();
            var          my_reg     = new Regex(@"\D");
            var          serverTime = "";
            var          response   = "";

            try
            {
                serverTime = my_reg.Replace(ServiceRequests.ServerTime(), "");
                logService.Write($"\tTradesRequest get serverTime successful: {serverTime}");
            }
            catch (Exception ex)
            {
                logService.Write($"\tAccount get serverTime error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}");
            }
            try
            {
                var request = CreatRequest(pair, serverTime, out string requestParams, fromId);
                response = privateApi.GetWebRequest(request, requestParams, key, secret, "GET");
                logService.Write($"\tTradesRequest {Resources.DOMAIN_V3}myTrades... successful: response = {response}");
            }
            catch (Exception ex)
            {
                logService.Write($"\tTradesRequest {Resources.DOMAIN_V3}myTrades... error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}");
            }

            try
            {
                result = JConverter.JsonConver <List <Trade> >(response);
                logService.Write($"\tTradesRequest JConverter successful.");
            }
            catch (Exception ex)
            {
                logService.Write($"\tTradesRequest JConverter error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}");
            }

            if (result != null)
            {
                var tradeForRemove = result.FirstOrDefault(x => x.id == fromId);
                if (tradeForRemove != null)
                {
                    result.Remove(tradeForRemove);
                }
            }
            logService.Write("***********TradesRequest END***********", true);
            return(result);
        }
Example #7
0
 public LastPriceResponse GetInfo(string pair)
 {
     try
     {
         var response = publicRequester.RequestPublicApi($"https://api.binance.com/api/v3/ticker/price?symbol={pair}");
         return(JConverter.JsonConver <LastPriceResponse>(response));
     }
     catch (Exception ex)
     {
         // TODO: Сохранеие логово
     }
     return(null);
 }
        private void Kline_MessageEvent(object sender, KlineEventArgs e)
        {
            try
            {
                Candle candle    = JConverter.JsonConver <Candle>(e.Message);
                var    ohlcPoint = new OhlcPoint()
                {
                    Open  = candle.k.o,
                    High  = candle.k.h,
                    Low   = candle.k.l,
                    Close = candle.k.c
                };

                var firstCandle = OhclValues.FirstOrDefault();
                if (isClose)
                {
                    OhclValues.Add(ohlcPoint);
                    OhclValues.Remove(firstCandle);
                    LabelsX.Add(candle.k.t.UnixToDateTime().ToString(formatX));
                    isClose = false;
                }
                else
                {
                    if (OhclValues.Count > 0)
                    {
                        var lastOhlc = OhclValues.Last();
                        lastOhlc.Open  = ohlcPoint.Open;
                        lastOhlc.High  = ohlcPoint.High;
                        lastOhlc.Low   = ohlcPoint.Low;
                        lastOhlc.Close = ohlcPoint.Close;
                    }
                    else
                    {
                        OhclValues.Add(ohlcPoint);
                        LabelsX.Add(candle.k.t.UnixToDateTime().ToString(formatX));
                    }
                }

                if (candle.k.x) // проверка должна быть после добавления, иначе добавим закрытую свечу
                {
                    isClose = true;
                }
            }
            catch (Exception ex)
            {
                //TODO: запись логов в БД
            }
            //CreateChartValuesLines();
        }
        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);
            }
        }
Example #10
0
        private void GetLastPrice(string data)
        {
            var aggTrade  = JConverter.JsonConver <AggTrade>(data);
            var lastPrice = PrimitiveConverter.ToDouble(aggTrade.p);

            if (!previosPrices.ContainsKey(aggTrade.s))
            {
                previosPrices.Add(aggTrade.s, lastPrice);
                OnLastPriceEvent(aggTrade.s, lastPrice);
            }
            else
            {
                var previosPrice = previosPrices[aggTrade.s];
                if (lastPrice != previosPrice)
                {
                    previosPrices[aggTrade.s] = lastPrice;
                    OnLastPriceEvent(aggTrade.s, lastPrice);
                }
            }
        }
Example #11
0
        private Account Account(string key, string secret)
        {
            logService.Write("***********Account START***********", true);
            logService.Write($"\tPublic key: {key}");
            Account result = null;
            SecretKeyRequiredRequester privateApi = new SecretKeyRequiredRequester();
            string response   = string.Empty;
            Regex  my_reg     = new Regex(@"\D");
            string serverTime = string.Empty;

            try
            {
                serverTime = my_reg.Replace(ServiceRequests.ServerTime(), "");
                logService.Write($"\tAccount get serverTime successful: {serverTime}");
            }
            catch (Exception ex)
            {
                logService.Write($"\tAccount get serverTime error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}");
            }
            try
            {
                response = privateApi.GetWebRequest($"{Resources.DOMAIN_V3}account?recvWindow=5000&timestamp=" + serverTime, "recvWindow=5000&timestamp=" + serverTime, key, secret, "GET");
                logService.Write($"\tAccount {Resources.DOMAIN_V3}account... successful: response = {response.Substring(0, 500)}");
            }
            catch (Exception ex)
            {
                logService.Write($"\tAccount {Resources.DOMAIN_V3}account... error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}");
            }

            try
            {
                result = JConverter.JsonConver <Account>(response);
                logService.Write($"\tAccount JConverter successful.");
            }
            catch (Exception ex)
            {
                logService.Write($"\tAccount JConverter error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}");
            }
            logService.Write("***********Account END***********", true);
            return(result);
        }
Example #12
0
        private void UpdateBalance(string data)
        {
            var balance = JConverter.JsonConver <BalanceInfo>(data);

            if (balance != null)
            {
                if (balance.B != null)
                {
                    foreach (var b in balance.B)
                    {
                        if (b.f != 0 || b.l != 0)
                        {
                            repositories.BalanceRepository.Update(new DataBaseWork.Models.Balance()
                            {
                                FK_PublicKey = key.PublicKey,
                                Asset        = b.a,
                                Free         = b.f,
                                Locked       = b.l
                            });
                        }
                    }
                }
            }
        }
Example #13
0
        /// <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;
            }));
        }