示例#1
0
        public void QueryOrder_Should_RespondWithQueriedOrder()
        {
            // arrange
            var order = new BinanceOrder()
            {
                ClientOrderId    = "order2",
                ExecutedQuantity = 0.6m,
                IcebergQuantity  = 0.7m,
                OrderId          = 200000000000,
                OriginalQuantity = 0.8m,
                Price            = 0.9m,
                Side             = OrderSide.Sell,
                Status           = OrderStatus.PartiallyFilled,
                StopPrice        = 1.0m,
                Symbol           = "ETHBTC",
                Time             = new DateTime(2017, 1, 10),
                TimeInForce      = TimeInForce.ImmediateOrCancel,
                Type             = OrderType.Market
            };

            var objects = TestHelpers.PrepareClient(() => Construct(new BinanceClientOptions()
            {
                ApiCredentials = new ApiCredentials("Test", "Test")
            }), JsonConvert.SerializeObject(order));

            // act
            var result = objects.Client.QueryOrder("BNBBTC", orderId: 1);

            // assert
            Assert.IsTrue(result.Success);
            Assert.IsTrue(TestHelpers.PublicInstancePropertiesEqual(order, result.Data));
        }
示例#2
0
        public void QueryOrder_Should_RespondWithQueriedOrder()
        {
            // arrange
            var order = new BinanceOrder()
            {
                ClientOrderId    = "order2",
                ExecutedQuantity = 0.6m,
                IcebergQuantity  = 0.7m,
                OrderId          = 200000000000,
                OriginalQuantity = 0.8m,
                Price            = 0.9m,
                Side             = OrderSide.Sell,
                Status           = OrderStatus.PartiallyFilled,
                StopPrice        = 1.0m,
                Symbol           = "ETHBTC",
                Time             = new DateTime(2017, 1, 10),
                TimeInForce      = TimeInForce.ImmediateOrCancel,
                Type             = OrderType.Market
            };

            var client = TestHelpers.CreateResponseClient(order, new BinanceClientOptions()
            {
                ApiCredentials = new ApiCredentials("Test", "Test"),
                AutoTimestamp  = false
            });

            // act
            var result = client.GetOrder("BNBBTC", orderId: 1);

            // assert
            Assert.IsTrue(result.Success);
            Assert.IsTrue(TestHelpers.AreEqual(order, result.Data));
        }
示例#3
0
        private Trade CreateTradeFromOrder(BinanceOrder o)
        {
            var trade = new Trade
            {
                Broker         = Name,
                Market         = o.Symbol,
                TradeDirection = o.Side == OrderSide.Buy ? TradeDirection.Long : TradeDirection.Short,
                Id             = o.OrderId.ToString()
            };

            trade.SetOrder(
                o.CreateTime,
                o.Price,
                o.Symbol,
                o.Side == OrderSide.Buy ? TradeDirection.Long : TradeDirection.Short,
                o.Quantity,
                null);

            trade.EntryQuantity = o.QuantityFilled;
            trade.EntryPrice    = o.AverageFillPrice;

            if (trade.EntryQuantity == trade.OrderAmount)
            {
                trade.CloseDateTime = o.UpdateTime;
            }

            return(trade);
        }
        public async Task <BinanceOrder> BinanceCancelOrdersAsync(BinanceOrder binanceOrder)
        {
            try
            {
                ProcessLogBroadcast?.Invoke(MessageType.General, $"Cancelling order.");
                ServerTime serverTime = await UpdateTimeServerAsync();

                Request request = new Request(_connectionAdapter.Authentication.EndpointUrl,
                                              "DELETE",
                                              $"/api/v3/order?")
                {
                    RequestQuery =
                        $"symbol={binanceOrder.Symbol}&orderId={binanceOrder.ID}&timestamp={serverTime.ServerTimeLong}"
                };
                string json = await _connectionAdapter.RequestAsync(request);

                if (!string.IsNullOrEmpty(json))
                {
                    binanceOrder = JsonSerializer.Deserialize <BinanceOrder>(json);
                }
                ProcessLogBroadcast?.Invoke(MessageType.JsonOutput, $"BinanceCancelOrdersAsync JSON:\r\n{json}");
            }
            catch (Exception e)
            {
                ProcessLogBroadcast?.Invoke(MessageType.Error,
                                            $"Method: BinanceCancelOrdersAsync\r\nException Stack Trace: {e.StackTrace}");
            }
            return(binanceOrder);
        }
        public void QueryOrder_Should_RespondWithQueriedOrder()
        {
            // arrange
            var order = new BinanceOrder()
            {
                ClientOrderId    = "order2",
                ExecutedQuantity = 0.6,
                IcebergQuantity  = 0.7,
                OrderId          = 200000000000,
                OriginalQuantity = 0.8,
                Price            = 0.9,
                Side             = OrderSide.Sell,
                Status           = OrderStatus.PartiallyFilled,
                StopPrice        = 1.0,
                Symbol           = "ETHBTC",
                Time             = new DateTime(2017, 1, 10),
                TimeInForce      = TimeInForce.ImmediateOrCancel,
                Type             = OrderType.Market
            };

            var client = PrepareClient(JsonConvert.SerializeObject(order));

            // act
            var result = client.QueryOrder("BNBBTC", orderId: 1);

            // assert
            Assert.IsTrue(result.Success);
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(order, result.Data));
        }
        public async Task <BinanceOrder> BinancePostOrdersAsync(BinanceOrder order)
        {
            BinanceOrder binanceOrder = null;

            try
            {
                ProcessLogBroadcast?.Invoke(MessageType.General, $"[Binance] Post Order Information.");
                ServerTime serverTime = await UpdateTimeServerAsync();

                Request request = new Request(_connectionAdapter.Authentication.EndpointUrl, "POST",
                                              $"/api/v3/order?");
                if (order.OrderType == OrderType.Market)
                {
                    request.RequestQuery = $"timestamp={serverTime.ServerTimeLong}&symbol={order.Symbol.ToUpper()}" +
                                           $"&side={order.OrderSide.ToString().ToUpper()}" +
                                           $"&type={order.OrderType.ToString().ToUpper()}&quantity={order.OrderSize}";
                }
                else
                {
                    request.RequestQuery = $"timestamp={serverTime.ServerTimeLong}&symbol={order.Symbol.ToUpper()}" +
                                           $"&side={order.OrderSide.ToString().ToUpper()}&type={order.OrderType.ToString().ToUpper()}" +
                                           $"&quantity={order.OrderSize}&price={ order.LimitPrice}&timeInForce=GTC";
                }
                string json = await _connectionAdapter.RequestAsync(request);

                binanceOrder = JsonSerializer.Deserialize <BinanceOrder>(json);
                ProcessLogBroadcast?.Invoke(MessageType.JsonOutput, $"UpdateAccountsAsync JSON:\r\n{json}");
            }
            catch (Exception e)
            {
                ProcessLogBroadcast?.Invoke(MessageType.Error,
                                            $"Method: BinancePostOrdersAsync\r\nException Stack Trace: {e.StackTrace}");
            }
            return(binanceOrder);
        }
示例#7
0
        public static List <Fill> ToOrderFills(this BinanceOrder binanceOrder)
        {
            List <Fill> fills          = new List <Fill>();
            DateTime    start          = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            Order       convertedOrder = new Order
            {
                Size      = binanceOrder.OrigQty.ToString(CultureInfo.InvariantCulture),
                Side      = binanceOrder.OrderSide.ToString(),
                Type      = binanceOrder.OrderType.ToString(),
                Price     = binanceOrder.Price,
                ProductID = binanceOrder.Symbol,
                CreatedAt = start.AddMilliseconds(binanceOrder.TransactTime).ToLocalTime()
                            .ToString(CultureInfo.InvariantCulture),
                ExecutedValue = binanceOrder.ExecutedQty,
                ID            = binanceOrder.ID.ToString(),
                TimeInForce   = binanceOrder.TimeInForce,
                Status        = binanceOrder.Status
            };

            if (binanceOrder.Fills == null || !binanceOrder.Fills.Any())
            {
                return(fills);
            }
            foreach (Fill binanceOrderFill in binanceOrder.Fills)
            {
                binanceOrderFill.Size      = binanceOrder.OrigQty.ToString(CultureInfo.InvariantCulture);
                binanceOrderFill.Side      = binanceOrder.OrderSide.ToString();
                binanceOrderFill.ProductID = binanceOrder.Symbol;
                binanceOrderFill.Time      = start.AddMilliseconds(binanceOrder.TransactTime).ToLocalTime();
                fills.Add(binanceOrderFill);
            }
            return(fills);
        }
示例#8
0
文件: Program.cs 项目: RASK18/Bitbot
        // Ej: BTC-EUR
        // Buy:  EUR -> BTC
        // Sell: BTC -> EUR
        private static void MakeMoney()
        {
            BinancePlacedOrder buyPlaced = Client.Spot.Order
                                           .PlaceOrder(_session.Pair, OrderSide.Buy, OrderType.Market, null, _session.EurAvailable)
                                           .GetResult();

            decimal      buyFee = GetFee(buyPlaced);
            BinanceOrder buy    = WaitOrder(buyPlaced);

            _session.WantedPrice = buy.QuoteQuantity + buy.QuoteQuantity * _session.Profit / 100;
            string logBuy = $" Comprado: {buy.QuoteQuantity.Round()} - {buyFee.Round()} = {buy.QuoteQuantityFilled.Round()} Eur";

            _session.Logs.Add(logBuy);
            _session.UpdateAvailable();
            UiController.PrintSession(_session);

            int  count = 1;
            bool exit  = false;

            while (!exit)
            {
                Sleep(_session.IntervalMin * 6); // 10 veces

                decimal price       = Client.Spot.Market.GetPrice(_session.Pair).GetResult().Price;
                decimal actualPrice = buy.QuantityFilled * price; // Antes o despues de impuestos?
                decimal actualFees  = actualPrice * _session.TakerFee;
                decimal wouldGet    = actualPrice - actualFees;

                Console.WriteLine($" {count}/10 - Obtendría: {actualPrice.Round()} - {actualFees.Round()} = {wouldGet.Round()} Eur");

                if (wouldGet >= _session.WantedPrice)
                {
                    exit = true;
                }

                if (count >= 10)
                {
                    break;
                }

                count++;
            }

            BinancePlacedOrder sellPlaced = Client.Spot.Order
                                            .PlaceOrder(_session.Pair, OrderSide.Sell, OrderType.Market, buy.QuantityFilled)
                                            .GetResult();

            decimal      sellFee = GetFee(buyPlaced);
            BinanceOrder sell    = WaitOrder(sellPlaced);

            decimal finalSell = sell.QuoteQuantityFilled - sellFee;
            string  logSell   = $" Vendido: {sell.QuoteQuantityFilled.Round()} - {sellFee.Round()} = {finalSell.Round()} Eur";

            _session.Logs.Add(logSell);

            decimal balance = finalSell - buy.QuoteQuantity;

            _session.UpdateBalance(balance);
        }
        private void MonitorarVenda(EntMoeda objMoeda, EntCarteira objCarteira)
        {
            try
            {
                if (StringUtils.ToBoolean(ConfigurationManager.AppSettings["teste"]))
                {
                    Aviso(objMoeda.Codigo, "BITCOINER - ORDEM DE VENDA CONCLUIDA", "Concluida ordem de venda em " + DateUtils.ToStringCompleto(DateTime.Now) + "\n" + objMoeda.Codigo + "\nValor: US$ " + DecimalUtils.ToString_8(objMoeda.OperacaoVendaAberta.ValorBitcoin) + " | Quantidade: " + DecimalUtils.ToString_8(objMoeda.OperacaoVendaAberta.ValorReais));

                    objMoeda.OperacaoVendaAberta.DataFimExecucao = DateTime.Now;
                    new BllOperacao().Alterar(objMoeda.OperacaoVendaAberta, EntUsuario.USUARIO_PADRAO);

                    objCarteira.SaldoBitcoin = objCarteira.SaldoBitcoin - objMoeda.OperacaoCompraAberta.ValorReais;
                    objCarteira.SaldoDolar   = objCarteira.SaldoDolar + objMoeda.OperacaoCompraAberta.ValorReais * objMoeda.OperacaoVendaAberta.ValorBitcoin;
                    new BllCarteira().Alterar(objCarteira, EntUsuario.USUARIO_PADRAO);

                    objMoeda.OperacaoCompraAberta = new EntOperacao();
                    objMoeda.OperacaoVendaAberta  = new EntOperacao();
                    new BllMoeda().Alterar(objMoeda, EntUsuario.USUARIO_PADRAO);
                }
                else
                {
                    WebCallResult <BinanceOrder> ordemTemp = client.Spot.Order.GetOrder(objMoeda.Codigo + EntMoeda.USDT, StringUtils.ToInt64(objMoeda.OperacaoVendaAberta.Operacao));
                    if (ordemTemp != null && ordemTemp.Data != null)
                    {
                        BinanceOrder ordem = ordemTemp.Data;
                        if (ordem.Status == OrderStatus.Filled)
                        {
                            Aviso(objMoeda.Codigo, "BITCOINER - ORDEM DE VENDA CONCLUIDA", "Concluida ordem de venda em " + DateUtils.ToStringCompleto(DateTime.Now) + "\n" + objMoeda.Codigo + "\nValor: US$ " + DecimalUtils.ToString_8(ordem.Price) + " | Quantidade: " + DecimalUtils.ToString_8(ordem.QuantityFilled));

                            if (ordem.UpdateTime != null)
                            {
                                objMoeda.OperacaoVendaAberta.DataFimExecucao = ordem.UpdateTime.Value;
                            }
                            else
                            {
                                objMoeda.OperacaoVendaAberta.DataFimExecucao = DateTime.Now;
                            }
                            objMoeda.OperacaoVendaAberta.ValorBitcoin = ordem.Price;
                            new BllOperacao().Alterar(objMoeda.OperacaoVendaAberta, EntUsuario.USUARIO_PADRAO);

                            objMoeda.OperacaoCompraAberta = new EntOperacao();
                            objMoeda.OperacaoVendaAberta  = new EntOperacao();
                            new BllMoeda().Alterar(objMoeda, EntUsuario.USUARIO_PADRAO);

                            objCarteira.SaldoBitcoin = objCarteira.SaldoBitcoin - ordem.QuantityFilled;
                            objCarteira.SaldoDolar   = objCarteira.SaldoDolar + ordem.QuoteQuantityFilled;
                            new BllCarteira().Alterar(objCarteira, EntUsuario.USUARIO_PADRAO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Aviso(objMoeda.Codigo, "BITCOINER - ERRO MONITORAMENTO VENDA", "Houve um erro no monitoramento de venda " + objMoeda.Codigo + " em " + DateUtils.ToStringCompleto(DateTime.Now) + "\n\n" + ex.Message + "\n\n" + ex.StackTrace);
            }
        }
示例#10
0
文件: Program.cs 项目: RASK18/Bitbot
        private static BinanceOrder WaitOrder(BinancePlacedOrder placedOrder)
        {
            BinanceOrder order = Client.Spot.Order.GetOrder(_session.Pair, placedOrder.OrderId, placedOrder.ClientOrderId).GetResult();

            while (order.Status != OrderStatus.Filled)
            {
                Thread.Sleep(1000);
                order = Client.Spot.Order.GetOrder(_session.Pair, placedOrder.OrderId, placedOrder.ClientOrderId).GetResult();
            }

            return(order);
        }
示例#11
0
 public static Order ConvertOrder(BinanceOrder order)
 {
     return new Order(
                order.Symbol,
                ExchangeName.Binance,
                ConvertOrderDirection(order.Side),
                order.OriginalQuantity,
                order.Price,
                ConvertOrderType(order.Type),
                ConvertTimeInForce(order.TimeInForce),
                order.StopPrice,
                order.OrderId.ToString());
 }
示例#12
0
        public void BinancePostOrders_ShouldReturnBinanceOrder()
        {
            //Arrange
            _httpMessageHandlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync",
                                                 ItExpr.Is <HttpRequestMessage>(x => x.RequestUri.AbsoluteUri.Contains("/api/v1/time")),
                                                 ItExpr.IsAny <CancellationToken>())
            .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(
                    @"{""serverTime"":1592395836992}")
            }))
            .Verifiable();
            _httpMessageHandlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync",
                                                 ItExpr.Is <HttpRequestMessage>(x => x.RequestUri.AbsoluteUri.Contains("/api/v3/order")),
                                                 ItExpr.IsAny <CancellationToken>())
            .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(
                    @"{""symbol"":""BNBBTC"",""orderId"":156,
                            ""orderListId"":-1,""clientOrderId"":""Ovu4oRzIuBmzR7YKnZjQDg"",
                            ""transactTime"":1594418218604,""price"":""0.00000000"",""origQty"":""0.10000000"",
                            ""executedQty"":""0.10000000"",""cummulativeQuoteQty"":""0.00016933"",
                            ""status"":""FILLED"",""timeInForce"":""GTC"",""type"":""MARKET"",
                            ""side"":""BUY"",""fills"":[{""price"":""0.00169330"",""qty"":""0.10000000"",
                            ""commission"":""0.00000000"",""commissionAsset"":""BNB"",""tradeId"":72}]}")
            }))
            .Verifiable();
            HttpClient httpClient = new HttpClient(_httpMessageHandlerMock.Object);

            _connectionAdapter.HttpClient = httpClient;
            Binance subjectUnderTest = new Binance();

            subjectUnderTest.ConnectionAdapter = _connectionAdapter;
            BinanceOrder binanceOrder = new BinanceOrder();

            binanceOrder.OrderType = OrderType.Market;
            binanceOrder.OrderSide = OrderSide.Buy;
            binanceOrder.OrderSize = (decimal)0.1;
            binanceOrder.Symbol    = "BNBBTC";
            //Act
            BinanceOrder binanceOrderResult = subjectUnderTest.PostOrdersAsync(binanceOrder).Result;

            //Assert
            Assert.IsNotNull(binanceOrderResult);
        }
示例#13
0
        public void CancelOrder_ShouldReturnBinanceOrder()
        {
            //Arrange
            _httpMessageHandlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync",
                                                 ItExpr.Is <HttpRequestMessage>(x => x.RequestUri.AbsoluteUri.Contains("/api/v1/time")),
                                                 ItExpr.IsAny <CancellationToken>())
            .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(
                    @"{""serverTime"":1592395836992}")
            }))
            .Verifiable();
            _httpMessageHandlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync",
                                                 ItExpr.Is <HttpRequestMessage>(x => x.RequestUri.AbsoluteUri.Contains("/api/v3/order")),
                                                 ItExpr.IsAny <CancellationToken>())
            .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(
                    @"{""symbol"":""BNBBTC"",""origClientOrderId"":""IplSV4jLgOQVYO6o9UCeAv"",
                            ""orderId"":171,""orderListId"":-1,""clientOrderId"":""qpYlufBkQXlPI3bgSzHZE3"",
                            ""price"":""0.00100000"",""origQty"":""0.10000000"",""executedQty"":""0.00000000"",
                            ""cummulativeQuoteQty"":""0.00000000"",""status"":""CANCELED"",""timeInForce"":""GTC"",
                            ""type"":""LIMIT"",""side"":""BUY""}")
            }))
            .Verifiable();
            HttpClient httpClient = new HttpClient(_httpMessageHandlerMock.Object);

            _connectionAdapter.HttpClient = httpClient;
            Binance subjectUnderTest = new Binance();

            subjectUnderTest.ConnectionAdapter = _connectionAdapter;
            BinanceOrder binanceOrder = new BinanceOrder();

            binanceOrder.OrderType = OrderType.Market;
            binanceOrder.OrderSide = OrderSide.Buy;
            binanceOrder.OrderSize = (decimal)0.1;
            binanceOrder.Symbol    = "BNBBTC";
            //Act
            BinanceOrder binanceOrderResult = subjectUnderTest.CancelOrderAsync(binanceOrder).Result;

            //Assert
            Assert.IsNotNull(binanceOrderResult);
        }
示例#14
0
文件: Trade.cs 项目: vanBassum/Coins
 public Trade(BinanceOrder binanceOrder, BinanceSymbol binanceSymbol)
 {
     Timestamp   = binanceOrder.UpdateTime;
     ReferenceID = binanceOrder.OrderId.ToString();
     if (binanceOrder.Side == Binance.Net.Enums.OrderSide.Buy)
     {
         BoughtAsset    = binanceSymbol.BaseAsset;
         BoughtQuantity = binanceOrder.QuantityFilled;
         SoldAsset      = binanceSymbol.QuoteAsset;
         SoldQuantity   = binanceOrder.QuoteQuantityFilled;
     }
     else
     {
         SoldAsset      = binanceSymbol.BaseAsset;
         SoldQuantity   = binanceOrder.QuantityFilled;
         BoughtAsset    = binanceSymbol.QuoteAsset;
         BoughtQuantity = binanceOrder.QuoteQuantityFilled;
     }
 }
        private BinanceStreamOrderUpdate OrderToOrderUpdate(BinanceOrder o)
        {
            var oup = new BinanceStreamOrderUpdate();

            oup.ClientOrderId   = o.ClientOrderId;
            oup.IcebergQuantity = o.IcebergQuantity;
            oup.IsWorking       = o.IsWorking;
            oup.OrderId         = o.OrderId;
            oup.Price           = o.Price;
            oup.Quantity        = o.Quantity;   //o.OriginalQuantity
            oup.Side            = o.Side;
            oup.Status          = o.Status;
            oup.StopPrice       = o.StopPrice;
            oup.Symbol          = o.Symbol;
            oup.CreateTime      = o.CreateTime;
            oup.TimeInForce     = o.TimeInForce;
            oup.Type            = o.Type;
            return(oup);
        }
示例#16
0
        public static Order ToOrder(this BinanceOrder binanceOrder)
        {
            DateTime start          = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            Order    convertedOrder = new Order
            {
                Size      = binanceOrder.OrigQty.ToString(CultureInfo.InvariantCulture),
                Side      = binanceOrder.OrderSide.ToString(),
                Type      = binanceOrder.OrderType.ToString(),
                Price     = binanceOrder.Price,
                ProductID = binanceOrder.Symbol,
                CreatedAt = start.AddMilliseconds(binanceOrder.TransactTime).ToLocalTime()
                            .ToString(CultureInfo.InvariantCulture),
                ExecutedValue = binanceOrder.ExecutedQty,
                ID            = binanceOrder.ID.ToString(),
                TimeInForce   = binanceOrder.TimeInForce,
                Status        = binanceOrder.Status
            };

            return(convertedOrder);
        }
示例#17
0
        public XOrder CreateXOrder(BinanceOrder bo, string strategyId = "")
        {
            var xo = new XOrder("BINANCE", strategyId);

            //xo.API = api;
            xo.Amount       = bo.Quantity;          //.OriginalQuantity;
            xo.AmountFilled = bo.QuantityFilled;    //.ExecutedQuantity;
            xo.AveragePrice = bo.Price;
            xo.Fees         = 0;
            xo.FeesCurrency = "";
            xo.IsBuy        = bo.Side == Binance.Net.Enums.OrderSide.Buy;
            xo.Message      = "";
            xo.OrderDate    = bo.CreateTime;        //.Time;
            xo.OrderId      = bo.OrderId.ToString();
            xo.Price        = bo.Price;
            xo.Result       = MapToResult(bo.Status);
            xo.Symbol       = bo.Symbol;

            return(xo);
        }
示例#18
0
 private static bool OrderCancelled(BinanceOrder order) => order.Status == OrderStatus.Canceled;
示例#19
0
 private static bool OrderWorked(BinanceOrder order) => order.Status == OrderStatus.Filled;
示例#20
0
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation($"Worker started at: {DateTime.Now}");
            _exchangeService.FeedBroadcast       += FeedBroadCast;
            _exchangeService.ProcessLogBroadcast += ProcessLogBroadcast;
            //await _exchangeService.UpdateAccountsAsync();
            await _exchangeService.UpdateBinanceAccountAsync();

            await _exchangeService.UpdateExchangeInfoAsync();

            await _exchangeService.UpdateProductOrderBookAsync(new Product { ID = "BTCEUR" }, 20);

            await _exchangeService.UpdateProductHistoricCandlesAsync(new Product { ID = "BTCEUR" },
                                                                     DateTime.Now.AddHours(-2).ToUniversalTime(),
                                                                     DateTime.Now.ToUniversalTime(), 900);//15 minutes unused TODO

            await _exchangeService.UpdateTickersAsync(new List <Product> {
                new Product {
                    ID = "BTCEUR"
                }, new Product {
                    ID = "ETHBTC"
                }
            });

            //await _exchangeService.UpdateFillsAsync(new Product { ID = "BTCEUR" });
            BinanceOrder binanceOrder = new BinanceOrder();

            binanceOrder.OrderType = OrderType.Market;
            binanceOrder.OrderSide = OrderSide.Buy;
            binanceOrder.OrderSize = (decimal)0.1;
            binanceOrder.Symbol    = "BNBBTC";
            BinanceOrder r = await _exchangeService.BinancePostOrdersAsync(binanceOrder);

            BinanceOrder binanceOrder2 = new BinanceOrder();

            binanceOrder2.OrderType  = OrderType.Limit;
            binanceOrder2.OrderSide  = OrderSide.Buy;
            binanceOrder2.OrderSize  = (decimal)0.1;
            binanceOrder2.LimitPrice = (decimal)0.0010000;
            binanceOrder2.Symbol     = "BNBBTC";
            BinanceOrder r2 = await _exchangeService.BinancePostOrdersAsync(binanceOrder2);

            await _exchangeService.BinanceCancelOrdersAsync(r2);

            if (_exchangeService.Accounts != null && _exchangeService.Accounts.Any())
            {
                //await _exchangeService.UpdateAccountHistoryAsync(_exchangeService.Accounts[0].ID);
                //await _exchangeService.UpdateAccountHoldsAsync(_exchangeService.Accounts[0].ID);
                //_exchangeService.UpdateProductsAsync().Wait(cancellationToken);
                List <Product> products = new List <Product>
                {
                    _exchangeService.Products.FirstOrDefault(x => x.BaseCurrency == "BTC" && x.QuoteCurrency == "EUR"),
                    _exchangeService.Products.FirstOrDefault(x => x.BaseCurrency == "BTC" && x.QuoteCurrency == "USD"),
                    _exchangeService.Products.FirstOrDefault(x => x.BaseCurrency == "ETH" && x.QuoteCurrency == "EUR")
                };
                products.RemoveAll(x => x == null);
                if (products.Any())
                {
                    //_exchangeService.UpdateProductOrderBookAsync(products[0]).Wait(cancellationToken);
                    //_exchangeService.UpdateOrdersAsync().Wait(cancellationToken);
                    //_exchangeService.UpdateFillsAsync(products[0]).Wait(cancellationToken);
                    //_exchangeService.UpdateTickersAsync(products).Wait(cancellationToken);
                    //_exchangeService.ChangeFeed(products.ToSubscribeString());

                    //_exchangeService.StartProcessingFeed();

                    //string indicatorDatabaseDirectory = AppDomain.CurrentDomain.BaseDirectory + "indicator_database";
                    //if (!Directory.Exists(indicatorDatabaseDirectory))
                    //    Directory.CreateDirectory(indicatorDatabaseDirectory);
                    //string databaseFile = indicatorDatabaseDirectory + "\\indicator.database.json";
                    //if (!File.Exists(databaseFile))
                    //    File.Create(databaseFile).Close();
                    //_relativeStrengthIndexIndicator = RelativeStrengthIndex.Load(databaseFile, _exchangeService);
                    //_relativeStrengthIndexIndicator.DatabaseFile = databaseFile;
                    //_relativeStrengthIndexIndicator.DatabaseDirectory = indicatorDatabaseDirectory;
                    //_relativeStrengthIndexIndicator.Product = products[0];
                    //_relativeStrengthIndexIndicator.EnableRelativeStrengthIndexUpdater();
                    //market order
                    //buy
                    Order marketOrderBuy = new Order {
                        Size = "0.1", Side = OrderSide.Buy.GetStringValue(), Type = OrderType.Market.GetStringValue(), ProductID = "BTCEUR"
                    };
                    Order marketBuyOrderResponse = await _exchangeService.PostOrdersAsync(marketOrderBuy);

                    ////sell
                    //Order marketOrderSell = new Order { Size = "0.1", Side = OrderSide.Sell, Type = OrderType.Market, ProductID = "BTC-EUR" };
                    //Order marketSellOrderResponse = await _exchangeService.PostOrdersAsync(marketOrderSell);
                    ////limit order
                    //Order limitOrder = new Order { Size = "0.1", Side = OrderSide.Buy.GetStringValue(), Type = OrderType.Limit.GetStringValue(), ProductID = "BTC-EUR", Price = "1000" };
                    //Order limitOrderResponse = await _exchangeService.PostOrdersAsync(limitOrder);
                    //////cancel order
                    ////await _exchangeService.CancelOrdersAsync(new Product{ID="BTC-EUR"});
                    //await _exchangeService.CancelOrderAsync(limitOrderResponse);
                    //List<HistoricRate> historicRates = await _exchangeService.UpdateProductHistoricCandlesAsync(products[0],
                    //    DateTime.Now.AddHours(-2).ToUniversalTime(),
                    //    DateTime.Now.ToUniversalTime(), 900);//15 minutes
                }
                _logger.LogInformation($"Account Count: {_exchangeService.Accounts.Count}");
            }

            await base.StartAsync(cancellationToken);
        }
示例#21
0
        private Task Process(Order order)
        {
            return(Task.Run(async() =>
            {
                try
                {
                    order.Processing = true;
                    var orderBookRequest = (await binanceClient.GetOrderBookAsync(order.Pair, 50));
                    if (!orderBookRequest.Success)
                    {
                        order.Status = Status.Error;
                        order.ErrorMessage = orderBookRequest.Error.Message;
                        return;
                    }

                    BinanceOrderBook orderbook = orderBookRequest.Data;

                    order.Bid = orderbook.Bids.First().Price;
                    order.Ask = orderbook.Asks.First().Price;

                    if (order.Status == Status.WaitBuy)
                    {
                        var priceToPlace = GetPriceToPlace(order.Pair,
                                                           OrderSide.Buy,
                                                           orderbook,
                                                           order.BAlfa,
                                                           order.TickUp);

                        var checkBetaTick = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.BBeta,
                                                          OrderSide.Buy);

                        if (checkBetaTick)
                        {
                            order.BuyOrder = await PlaceOrder(order.Pair, order.Amount, OrderSide.Buy, priceToPlace);
                            order.Status = Status.Buy;
                            order.BuyPrice = priceToPlace;
                        }
                    }
                    else if (order.Status == Status.WaitSell)
                    {
                        var priceToPlace = GetPriceToPlace(order.Pair,
                                                           OrderSide.Sell,
                                                           orderbook,
                                                           order.SAlfa,
                                                           order.TickUp);

                        var checkBetaTick = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.SBeta,
                                                          OrderSide.Sell);

                        if (checkBetaTick)
                        {
                            order.SellOrder = await PlaceOrder(order.Pair, order.Amount, OrderSide.Sell, priceToPlace);
                            order.Status = Status.Sell;
                            order.SellPrice = priceToPlace;
                        }
                    }
                    else if (order.Status == Status.Buy)
                    {
                        var statusOrderRequest = await binanceClient.GetOrderAsync(order.Pair, order.BuyOrder.OrderId);

                        if (!statusOrderRequest.Success)
                        {
                            if (statusOrderRequest.Error.Code == -2013)
                            {
                                return;
                            }
                            order.Status = Status.Error;
                            order.ErrorMessage = statusOrderRequest.Error.Message;
                        }

                        var statusOrder = statusOrderRequest.Data;

                        if (statusOrder.Status == OrderStatus.Filled)
                        {
                            order.BuyOrderCompletedDatetime = DateTime.Now;
                            var priceToPlace = GetPriceToPlace(order.Pair, OrderSide.Sell, orderbook, order.SAlfa,
                                                               order.TickUp);

                            var checkBeta = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.SBeta,
                                                          OrderSide.Sell);

                            if (checkBeta)
                            {
                                order.SellOrder = await PlaceOrder(order.Pair, order.BuyOrder.OriginalQuantity,
                                                                   OrderSide.Sell, priceToPlace);
                                order.Status = Status.Sell;
                                order.SellPrice = priceToPlace;
                            }
                            else
                            {
                                order.Status = Status.WaitSell;
                            }
                        }
                        else if (statusOrder.Status == OrderStatus.New)
                        {
                            var orderBookClear = RemoveMyOrderFromOrderbook(order.BuyOrder.Price,
                                                                            order.BuyOrder.OriginalQuantity, OrderSide.Buy, orderbook);

                            var priceToPlace = GetPriceToPlace(order.Pair, OrderSide.Buy, orderBookClear, order.BAlfa,
                                                               order.TickUp);
                            var checkBeta = CheckBetaTick(order.Pair, orderBookClear, priceToPlace, order.BBeta,
                                                          OrderSide.Buy);

                            if (checkBeta)
                            {
                                if (priceToPlace != order.BuyOrder.Price)
                                {
                                    BinanceCanceledOrder orderCancelled;
                                    try
                                    {
                                        orderCancelled = await CancelBinanceOrder(order.Pair, order.BuyOrder.OrderId);
                                    }
                                    catch (UnknowOrderException)
                                    {
                                        return;
                                    }
                                    if (orderCancelled.ExecutedQuantity > 0)
                                    {
                                        ManagePartiallyFilledBuy(order, orderCancelled);
                                    }
                                    // Controllare
                                    order.BuyOrder = await PlaceOrder(order.Pair, order.BuyOrder.OriginalQuantity,
                                                                      OrderSide.Buy, priceToPlace);
                                    order.BuyPrice = priceToPlace;
                                }
                            }
                            else
                            {
                                BinanceCanceledOrder orderCancelled;
                                try
                                {
                                    orderCancelled = await CancelBinanceOrder(order.Pair, order.BuyOrder.OrderId);
                                }
                                catch (UnknowOrderException)
                                {
                                    return;
                                }
                                if (orderCancelled.ExecutedQuantity > 0)
                                {
                                    ManagePartiallyFilledBuy(order, orderCancelled);
                                }

                                order.Status = Status.WaitBuy;
                            }
                        }
                        else if (statusOrder.Status == OrderStatus.Canceled)
                        {
                            var priceToPlace = GetPriceToPlace(order.Pair, OrderSide.Buy, orderbook, order.BAlfa,
                                                               order.TickUp);
                            var checkBeta = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.BBeta,
                                                          OrderSide.Buy);

                            if (checkBeta)
                            {
                                // Controllare
                                order.BuyOrder = await PlaceOrder(order.Pair, order.BuyOrder.OriginalQuantity,
                                                                  OrderSide.Buy, priceToPlace);
                                order.BuyPrice = priceToPlace;
                            }
                            else
                            {
                                order.Status = Status.WaitBuy;
                            }
                        }
                        else if (statusOrder.Status == OrderStatus.PartiallyFilled)
                        {
                            BinanceCanceledOrder orderCancelled;
                            try
                            {
                                orderCancelled = await CancelBinanceOrder(order.Pair, order.BuyOrder.OrderId);
                            }
                            catch (UnknowOrderException)
                            {
                                return;
                            }
                            ManagePartiallyFilledBuy(order, orderCancelled);
                            context.Send(x => Orders.Remove(order), null);
                        }
                    }
                    else if (order.Status == Status.Sell)
                    {
                        var orderStatusRequest = await binanceClient.GetOrderAsync(order.Pair, order.SellOrder.OrderId);

                        if (!orderStatusRequest.Success)
                        {
                            order.Status = Status.Error;
                            order.ErrorMessage = orderStatusRequest.Error.Message;
                            return;
                        }

                        BinanceOrder statusOrder = orderStatusRequest.Data;

                        if (statusOrder.Status == OrderStatus.Filled)
                        {
                            order.SellOrderCompletedDatetime = DateTime.Now;
                            CompleteOrder(order);
                        }
                        else if (statusOrder.Status == OrderStatus.New)
                        {
                            var orderBookClear = RemoveMyOrderFromOrderbook(order.SellOrder.Price,
                                                                            order.BuyOrder.OriginalQuantity, OrderSide.Sell, orderbook);

                            var priceToPlace = GetPriceToPlace(order.Pair,
                                                               OrderSide.Sell,
                                                               orderBookClear,
                                                               order.SAlfa,
                                                               order.TickUp);

                            var checkBetaTick = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.SBeta,
                                                              OrderSide.Sell);
                            if (checkBetaTick)
                            {
                                if (priceToPlace != order.SellOrder.Price)
                                {
                                    BinanceCanceledOrder orderCancelled;
                                    try
                                    {
                                        orderCancelled = await CancelBinanceOrder(order.Pair, order.SellOrder.OrderId);
                                    }
                                    catch (UnknowOrderException)
                                    {
                                        return;
                                    }

                                    if (orderCancelled.ExecutedQuantity > 0)
                                    {
                                        ManagePartiallyFilledSell(order, orderCancelled);
                                        return;
                                    }

                                    order.SellOrder = await PlaceOrder(order.Pair, order.SellOrder.OriginalQuantity,
                                                                       OrderSide.Sell, priceToPlace);
                                    order.SellPrice = priceToPlace;
                                }
                            }
                            else
                            {
                                BinanceCanceledOrder orderCancelled;
                                try
                                {
                                    orderCancelled = await CancelBinanceOrder(order.Pair, order.SellOrder.OrderId);
                                }
                                catch (UnknowOrderException)
                                {
                                    return;
                                }
                                if (orderCancelled.ExecutedQuantity > 0)
                                {
                                    ManagePartiallyFilledSell(order, orderCancelled);
                                    return;
                                }

                                order.Status = Status.WaitSell;
                            }
                        }
                        else if (statusOrder.Status == OrderStatus.Canceled)
                        {
                            var orderBookClear = RemoveMyOrderFromOrderbook(order.SellOrder.Price,
                                                                            order.BuyOrder.OriginalQuantity, OrderSide.Sell, orderbook);

                            var priceToPlace = GetPriceToPlace(order.Pair,
                                                               OrderSide.Sell,
                                                               orderBookClear,
                                                               order.SAlfa,
                                                               order.TickUp);

                            var checkBetaTick = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.SBeta,
                                                              OrderSide.Sell);
                            if (checkBetaTick)
                            {
                                order.SellOrder = await PlaceOrder(order.Pair, order.SellOrder.OriginalQuantity,
                                                                   OrderSide.Sell, priceToPlace);
                                order.SellPrice = priceToPlace;
                            }
                            else
                            {
                                order.Status = Status.WaitSell;
                            }
                        }

                        else if (statusOrder.Status == OrderStatus.PartiallyFilled)
                        {
                            BinanceCanceledOrder orderCancelled;
                            try
                            {
                                orderCancelled = await CancelBinanceOrder(order.Pair, order.SellOrder.OrderId);
                            }
                            catch (UnknowOrderException)
                            {
                                return;
                            }
                            ManagePartiallyFilledSell(order, orderCancelled);
                        }
                    }
                }
                catch (Exception ex)
                {
                    order.Status = Status.Error;
                    order.ErrorMessage = ex.Message;
                }
                finally
                {
                    order.Processing = false;
                }
            }));
        }