Exemplo n.º 1
0
        private async Task SaveCandle(BinanceStreamKline kline, NatsClient natsClient)
        {
            if (kline.Final)
            {
                Candle candle = kline.ToCandle();
                long?  id     = await _candlesProcessor.Create(candle);

                _logger.LogTrace($"Saved candle from {Exchange.Description} - {candle.Symbol}");

                await natsClient.PubAsJsonAsync(_settings.Value.CandlesQueueName, new Notification <Candle>() { Code = ActionCode.CREATED.Code, Payload = candle });
            }
        }
        public async Task StopLoss(Trade trade, PairConfig config)
        {
            await WithConnection(async (connection, transaction) =>
            {
                IExchangeCode exchangeCode = ExchangeCode.Create(trade.ExchangeCode);

                IEnumerable <Deal> deals = await _dealManager.GetOpenDeals(trade.ExchangeCode, trade.Symbol, connection, transaction);
                foreach (Deal deal in deals)
                {
                    deal.Orders = await _orderManager.GetOrdersByDealId(deal.Id, connection, transaction) as List <Order>;
                    if (deal.StopLoss.HasValue && trade.Price < deal.StopLoss.Value)
                    {
                        foreach (Order dealOrder in deal.Orders)
                        {
                            if (dealOrder.OrderStatusCode == OrderStatusCode.PENDING.Code || dealOrder.OrderStatusCode == OrderStatusCode.EXPIRED.Code || dealOrder.OrderStatusCode == OrderStatusCode.HOLD.Code)
                            {
                                await _orderManager.Delete(dealOrder.Id, connection, transaction);
                            }
                            else if (dealOrder.OrderStatusCode == OrderStatusCode.LISTED.Code)
                            {
                                dealOrder.OrderStatusCode = OrderStatusCode.CANCELED.Code;
                                dealOrder.Updated         = DateTime.UtcNow;
                                dealOrder.UpdateRequired  = true;

                                await _orderManager.Update(dealOrder, connection, transaction);

                                NatsClient client = _connector.Client;
                                await client.PubAsJsonAsync(_settings.Value.OrdersQueueName, new Notification <Order>()
                                {
                                    Code = ActionCode.UPDATED.Code, Payload = dealOrder
                                });
                            }
                        }

                        Order order            = new Order();
                        order.ExchangeCode     = trade.ExchangeCode;
                        order.Symbol           = trade.Symbol;
                        order.TradingModeCode  = TradingModeCode.AUTO;
                        order.FillPoliticsCode = FillPoliticsCode.GTC;
                        order.OrderStatusCode  = OrderStatusCode.PENDING;
                        order.DealId           = deal.Id;
                        order.OrderTypeCode    = OrderTypeCode.MKT;
                        order.OrderSideCode    = OrderSideCode.SELL;
                        order.Amount           = deal.Amount;

                        order.Id = await _orderManager.Create(order, connection, transaction);
                    }
                }

                return(Task.CompletedTask);
            });
        }
Exemplo n.º 3
0
        protected override async Task DoWork(PairConfig pair, CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    using (BinanceSocketClient client = new BinanceSocketClient())
                    {
                        ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString);
                        using (NatsClient natsClient = new NatsClient(cnInfo))
                        {
                            if (!natsClient.IsConnected)
                            {
                                natsClient.Connect();
                            }

                            CallResult <UpdateSubscription> successKline = null;
                            successKline = client.SubscribeToTradeUpdates(pair.Symbol, async(data) =>
                            {
                                Trade trade = data.ToEntity();

                                if (!_settings.Value.DisadleDealsSaving)
                                {
                                    long id = await _tradesProcessor.Create(trade);
                                }

                                await natsClient.PubAsJsonAsync(_settings.Value.TradesQueueName, new Notification <Trade>()
                                {
                                    Code = ActionCode.CREATED.Code, Payload = trade
                                });
                            });

                            successKline.Data.ConnectionLost     += () => { _logger.LogError($"Connection to {Exchange} is lost"); };
                            successKline.Data.ConnectionRestored += (data) => { _logger.LogError($"Connection to {Exchange} is Restored"); };

                            while (!stoppingToken.IsCancellationRequested)
                            {
                            }

                            natsClient.Disconnect();
                            await client.Unsubscribe(successKline.Data);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"{Exchange.Description} Trades service failed with message {ex.Message}", ex);
                }
            }
        }
        public async Task Should_be_able_to_publish_and_consume_JSON_payloads_asynchronously()
        {
            var orgItem = EncodingTestItem.Create();
            EncodingTestItem decodedItem = null;

            await _client.SubAsync("ClientProtobufEncodingTests", stream => stream.Subscribe(msg =>
            {
                decodedItem = msg.FromJson <EncodingTestItem>();
                ReleaseOne();
            }));

            await _client.PubAsJsonAsync("ClientProtobufEncodingTests", orgItem);

            WaitOne();

            orgItem.Should().BeEquivalentTo(decodedItem);
        }
        public async Task Should_be_able_to_publish_and_consume_JSON_payloads_asynchronously()
        {
            var subject = Context.GenerateSubject();
            var orgItem = EncodingTestItem.Create();
            EncodingTestItem decodedItem = null;

            _sync   = Sync.MaxOne();
            _client = await Context.ConnectClientAsync();

            await _client.SubAsync(subject, stream => stream.Subscribe(msg =>
            {
                decodedItem = msg.FromJson <EncodingTestItem>();
                _sync.Release();
            }));

            await _client.PubAsJsonAsync(subject, orgItem);

            _sync.WaitForAll();

            orgItem.Should().BeEquivalentTo(decodedItem);
        }
Exemplo n.º 6
0
        public async Task <IActionResult> CreateOrder(OrderModel model)
        {
            if (ModelState.IsValid)
            {
                Deal deal = await _dealProcessor.CreateForOrder(model.ToOrder());

                try
                {
                    NatsClient client = _connector.Client;
                    await client.PubAsJsonAsync(_settings.Value.OrdersQueueName, new Notification <Deal>() { Code = ActionCode.CREATED.Code, Payload = deal });
                }
                catch (Exception ex)
                {
                    _logger.LogError("Can't send Nata notification", ex);
                }

                return(RedirectToAction("CreateOrder"));
            }

            return(View(model));
        }
        public static async Task RunAsync(ConnectionInfo cnInfo)
        {
            using (var client = new NatsClient("Publisher", cnInfo))
            {
                client.Connect();

                while (true)
                {
                    Console.WriteLine("Say what? (blank=quit)");
                    var message = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(message))
                    {
                        break;
                    }

                    await client.PubAsJsonAsync("demo.greeting", new Greeting
                    {
                        Message = message,
                        SentBy  = Environment.UserName
                    });
                }
            }
        }
        protected override async Task DoWork(PairConfig config, CancellationToken stoppingToken)
        {
            ExchangeConfig exchangeConfig = await _exchangeConfigProcessor.GetExchangeConfig(Exchange.Code);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    string listenKey = String.Empty;
                    using (BinanceClient client = new BinanceClient())
                    {
                        listenKey = client.StartUserStream().Data;
                    }

                    using (BinanceSocketClient socketClient = new BinanceSocketClient())
                    {
                        ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString);
                        using (NatsClient natsClient = new NatsClient(cnInfo))
                        {
                            if (!natsClient.IsConnected)
                            {
                                natsClient.Connect();
                            }

                            CallResult <UpdateSubscription> successAccount = socketClient.SubscribeToUserDataUpdates(listenKey,
                                                                                                                     accountData =>
                            {
                            },
                                                                                                                     async orderData =>
                            {
                                Order order = orderData.ToOrder();
                                Deal deal   = await _dealProcessor.UpdateForOrder(order, config);

                                await natsClient.PubAsJsonAsync(_settings.Value.OrdersQueueName, new Notification <Deal>()
                                {
                                    Code = ActionCode.UPDATED.Code, Payload = deal
                                });
                            },
                                                                                                                     ocoOrderData =>
                            {
                            },
                                                                                                                     async balancesData =>
                            {
                                IEnumerable <Balance> balances = balancesData.Select(x => x.ToBalance());
                                foreach (Balance balance in balances)
                                {
                                    await _balanceProcessor.UpdateOrCreate(balance);
                                }
                            },
                                                                                                                     onAccountBalanceUpdate =>
                            {
                            });

                            while (!stoppingToken.IsCancellationRequested)
                            {
                            }

                            natsClient.Disconnect();
                            await socketClient.UnsubscribeAll();
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
        }