Esempio n. 1
0
        private void UpdateOrder(OrderReply order)
        {
            Stock stock = GetStock(order.Venue, order.Symbol);

            Dictionary <int, OrderReply> stockOrders;

            if (!Orders.TryGetValue(stock, out stockOrders))
            {
                stockOrders = new Dictionary <int, OrderReply>
                {
                    { order.OrderId, order }
                };
                // Add a orderbook for that stock
                Orders.Add(stock, stockOrders);
            }
            else
            {
                OrderReply existingOrder;
                if (!stockOrders.TryGetValue(order.OrderId, out existingOrder))
                {
                    // Add the order if the orderId doesn't exist for that stock
                    Orders[stock].Add(order.OrderId, order);
                }
                else
                {
                    if (existingOrder.Timestamp < order.Timestamp)
                    {
                        // Update order if the reply is newer than current
                        Orders[stock][order.OrderId] = order;
                    }
                }
            }
        }
Esempio n. 2
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation($"Checking orders at {DateTimeOffset.Now}");
                try
                {
                    Channel channel = new Channel("localhost:50051", ChannelCredentials.Insecure);
                    OrdersManager.OrdersManagerClient client = new OrdersManager.OrdersManagerClient(channel);

                    OrderRequest request = new OrderRequest();
                    OrderReply   result  = await client.GetNewOrderAsync(request);

                    if (result.OrderId != 0)
                    {
                        _databaseService.UpdateOrder(result.OrderId);
                        _logger.LogInformation($"Order with id {result.OrderId} has been processed");
                    }
                    else
                    {
                        _logger.LogInformation($"No pending orders at {DateTimeOffset.Now}");
                    }

                    await channel.ShutdownAsync();
                }
                catch (Exception exc)
                {
                    _logger.LogError(exc.Message + exc.StackTrace);
                }

                await Task.Delay(3000, stoppingToken);
            }
        }
Esempio n. 3
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation($"Checking orders at {DateTimeOffset.Now}");
                try
                {
                    //var httpClient = new HttpClient();
                    // The port number(5001) must match the port of the gRPC server.
                    //httpClient.BaseAddress = new Uri("https://localhost:5001");
                    var          channel = GrpcChannel.ForAddress("https://localhost:5001");
                    var          client  = new OrdersHandler.OrdersManager.OrdersManagerClient(channel);
                    OrderRequest request = new OrderRequest();
                    OrderReply   result  = await client.GetNewOrderAsync(request);

                    if (result.OrderId != 0)
                    {
                        _databaseService.UpdateOrder(result.OrderId);
                        _logger.LogInformation($"Order with id {result.OrderId} has been processed");
                    }
                    else
                    {
                        _logger.LogInformation($"No pending orders at {DateTimeOffset.Now}");
                    }
                }
                catch (Exception exc)
                {
                    _logger.LogError(exc.Message + exc.StackTrace);
                }

                await Task.Delay(3000, stoppingToken);
            }
        }
Esempio n. 4
0
        private void UpdateMonitoringParameters(OrderReply order)
        {
            Stock     stock     = _venue.GetStock(order.Symbol);
            Direction direction = Utils.GetDirection(order.Direction);

            MonitoringParameter parameter;
            Dictionary <Direction, MonitoringParameter> parameterSides;

            if (!_monitoringParameters.TryGetValue(stock, out parameterSides))
            {
                parameter = new MonitoringParameter();
                parameter.Update(order);
                parameterSides = new Dictionary <Direction, MonitoringParameter>
                {
                    { direction, parameter }
                };
                _monitoringParameters.Add(stock, parameterSides);
            }
            else
            {
                if (!parameterSides.TryGetValue(direction, out parameter))
                {
                    parameter = new MonitoringParameter();
                    parameter.Update(order);
                    parameterSides.Add(direction, parameter);
                }
                else
                {
                    parameter.Update(order);
                    _monitoringParameters[stock][direction] = parameter;
                }
            }
        }
Esempio n. 5
0
 private void UpdateOrder(OrderReply reply)
 {
     //EventHandler<OrderReply> handler = OrderUpdated;
     //if (handler != null)
     //{
     //    handler(null, reply);
     //}
     _dataAccess.UpdateOrder(reply);
 }
Esempio n. 6
0
        public void CheckOrder(Order order, Department department)
        {
            string orderType;

            if (order is BroadCastOrder broadcastORder)
            {
                Console.WriteLine("Broadcast order recieved at department " +
                                  department.Id);
                orderType = nameof(BroadCastOrder);
            }
            else
            {
                Console.WriteLine("Order placed at department" + department.Id);
                orderType = nameof(Order);
            }
            var product = department.Products.FirstOrDefault(x => x.Id == order.Product.Id);

            if (product != null)
            {
                //Product found, determaining if full delivery is possible.
                var          amount = product.Amount;
                DeliveryEnum type;
                if (amount > order.Product.Amount)
                {
                    type = DeliveryEnum.Full;
                }
                else if (amount > 0)
                {
                    type = DeliveryEnum.Partial;
                }
                else
                {
                    type = DeliveryEnum.None;
                }

                var reply = new OrderReply(department.Id, order.Id, product, type, orderType);
                if (type != DeliveryEnum.None)
                {
                    bool isInternal = department.Country.Equals(order.Customer.Country, StringComparison.InvariantCultureIgnoreCase);
                    reply.DeliveryTime = isInternal ? InternalShippingDays : ExternalShippingDays;
                    reply.ShippingFee  = isInternal ? InternalShippingCharge : ExternalShippingCharge;
                }
                _bus.Send(order.ReplyTo, reply);
                Console.WriteLine("Order processed with deliverytype" +
                                  type +
                                  " at department" + department.Id);
            }
            else
            {
                //No products of that Id
                _bus.Send(order.ReplyTo, new OrderReply(department.Id, order.Id, null, DeliveryEnum.None, orderType));

                Console.WriteLine("No products found at department" + department.Id);
            }
        }
Esempio n. 7
0
        public OrderReply CancelOrder(Stock stock, int id)
        {
            CancelOrder request = new CancelOrder(Name, stock, id);
            bool        success = request.Execute();
            OrderReply  reply   = (request.Reply as OrderReply) ?? new OrderReply(false);

            if (success)
            {
                UpdateOrder(reply);
            }
            return(reply);
        }
Esempio n. 8
0
        public OrderReply PostOrder(string account, Stock stock, Fill order, OrderType orderType)
        {
            PostOrder  request = new PostOrder(account, Name, stock, order, orderType);
            bool       success = request.Execute();
            OrderReply reply   = (request.Reply as OrderReply) ?? new OrderReply(false);

            if (success)
            {
                UpdateOrder(reply);
            }
            return(reply);
        }
Esempio n. 9
0
        public override Task <OrderReply> GetNewOrder(OrderRequest request, ServerCallContext context)
        {
            DatabaseService service = new DatabaseService();
            var             order   = service.GetPendingOrder();
            int             orderId = order == null ? 0 : order.OrderId;
            OrderReply      reply   = new OrderReply
            {
                OrderId = orderId
            };

            return(Task.FromResult(reply));
        }
Esempio n. 10
0
        public void PostOrderTest_Immediate()
        {
            Stock     stock   = new Stock("", Utils.TestStock);
            Fill      order   = new Fill(0, 100, Direction.Buy);
            PostOrder request = new PostOrder(Utils.TestAccount, Utils.TestVenue, stock, order, OrderType.ImmediateOrCancell);
            bool      actual  = request.Execute();

            Assert.IsTrue(actual);
            OrderReply reply = request.Reply as OrderReply;

            Assert.IsNotNull(reply);
            Assert.AreEqual(Utils.TestVenue, reply.Venue);
            Assert.AreEqual(Utils.TestStock, reply.Symbol);
        }
Esempio n. 11
0
        public void PostOrderTest_StockDoesNotExist()
        {
            Stock     stock   = new Stock("", "FALSEEX");
            Fill      order   = new Fill(0, 100, Direction.Buy);
            PostOrder request = new PostOrder(Utils.TestAccount, Utils.TestVenue, stock, order, OrderType.Market);
            bool      actual  = request.Execute();

            Assert.IsFalse(actual);
            OrderReply reply = request.Reply as OrderReply;

            Assert.IsNotNull(reply);
            Assert.IsNull(reply.Venue);
            Assert.IsNull(reply.Symbol);
            Assert.IsNull(reply.Fills);
        }
 public override Task <OrderReply> IsSameOrder(OrderRequest request, ServerCallContext context)
 {
     #region 业务逻辑
     //创建时间转换
     DateTime CreationTime = request.CreationTime.ToDateTime();
     var      packageList  = request.PackageList.ToList();
     foreach (var packageRequest in packageList)
     {
         var weight = packageRequest.Weight;
     }
     #endregion
     var reply = new OrderReply();
     reply.IsSame  = false;
     reply.Message = "不是同一订单";
     return(Task.FromResult(reply));
 }
Esempio n. 13
0
        public void PostOrderTest_NoAccount()
        {
            Stock     stock   = new Stock("", Utils.TestStock);
            Fill      order   = new Fill(0, 0, Direction.Buy);
            PostOrder request = new PostOrder("", Utils.TestStock, stock, order, OrderType.Market);
            bool      actual  = request.Execute();

            Assert.IsFalse(actual);
            OrderReply reply = request.Reply as OrderReply;

            Assert.IsNull(reply);
            BaseReply baseReply = request.Reply as BaseReply;

            Assert.IsNotNull(baseReply);
            StringAssert.Contains("The remote server returned an error: (404) Not Found.", baseReply.Error);
        }
Esempio n. 14
0
        private void ProcessReply(OrderReply message)
        {
            Console.WriteLine("Proccesing reply");
            var order = _outstandingOrders.FirstOrDefault(x => x.Id == message.OrderId);

            if (order == null)
            {
                return;
            }
            if (message.DeliveryType == DeliveryEnum.Full)
            {
                _bus.Publish(message, order.Customer.Id);
                Console.WriteLine("Sent reply");
                _outstandingOrders.Remove(order);
            }
            else
            {
                _bus.Publish(new BroadCastOrder(order.Id, order.Product, order.Customer)
                {
                    ReplyTo = nameof(BroadCastOrder)
                });
                Console.WriteLine("Broadcasted request");
            }
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation($"Checking orders at {DateTimeOffset.Now}");
                try
                {
                    AppContext.SetSwitch(
                        "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport",
                        true);
                    HttpClient httpClient = new HttpClient();
                    httpClient.BaseAddress = new Uri("http://127.0.0.1:8194");

                    var grpcClient = GrpcClient.Create <OrdersManager.OrdersManagerClient>(httpClient);

                    OrderRequest request = new OrderRequest();
                    OrderReply   result  = await grpcClient.GetNewOrderAsync(request);

                    if (result.OrderId != 0)
                    {
                        _databaseService.UpdateOrder(result.OrderId);
                        _logger.LogInformation($"Order with id {result.OrderId} has been processed");
                    }
                    else
                    {
                        _logger.LogInformation($"No pending orders at {DateTimeOffset.Now}");
                    }
                }
                catch (Exception exc)
                {
                    _logger.LogError(exc.Message + exc.StackTrace);
                }

                await Task.Delay(3000, stoppingToken);
            }
        }
Esempio n. 16
0
 public void Update(OrderReply args)
 {
 }
Esempio n. 17
0
        private void ProcessBroadCastReply(OrderReply message)
        {
            Console.WriteLine("Proccesing Broadcast reply");
            if (_broadcastOrders.All(x => x.Key != message.OrderId))
            {
                _broadcastOrders.Add(message.OrderId, new List <OrderReply> {
                    message
                });
            }
            var dictItem = _broadcastOrders[message.OrderId];

            if (dictItem == null)
            {
                return;
            }

            if (!dictItem.Contains(message))
            {
                dictItem.Add(message);
            }

            var order = _outstandingOrders.FirstOrDefault(x => x.Id == message.OrderId);

            if (order != null)
            {
                if (dictItem.Any(x => x.DeliveryType == DeliveryEnum.Full))
                {
                    Console.WriteLine("Full order delivery possible");
                    _bus.Publish(dictItem.FirstOrDefault(x => x.DeliveryType == DeliveryEnum.Full), order.Customer.Id);
                    _outstandingOrders.Remove(order);
                    return;
                }
                if (dictItem.Where(x => x.Product != null).Sum(x => x.Product.Amount) > order.Product.Amount)
                {
                    Console.WriteLine("Multiple partial delivery possible");

                    var currentOrders = new List <OrderReply>();
                    while (currentOrders.Sum(x => x.Product.Amount) < order.Product.Amount)
                    {
                        int maxStock = dictItem.Max(x => x.Product.Amount);
                        IEnumerable <OrderReply> items = dictItem.Where(x => x.Product.Amount == maxStock).ToArray();
                        currentOrders.AddRange(items);
                        foreach (OrderReply item in items)
                        {
                            dictItem.Remove(item);
                        }
                    }
                    var replyMessage = new OrderReply(-2, order.Id, order.Product, DeliveryEnum.Full, null)
                    {
                        DeliveryTime = currentOrders.Max(x => x.DeliveryTime),
                        ShippingFee  = currentOrders.Sum(x => x.ShippingFee)
                    };
                    _bus.Publish(replyMessage, order.Customer.Id);
                    _outstandingOrders.Remove(order);
                    return;
                }
                if (dictItem.Count == 3)
                {
                    Console.WriteLine("No delivery possible");
                    _bus.Publish(new OrderReply(-1, message.OrderId, order.Product, DeliveryEnum.None, null), order.Customer.Id);
                    _outstandingOrders.Remove(order);
                }
            }
        }
 private void ProcessOrder(OrderReply message)
 {
     _reply = message;
     Console.WriteLine("Proccesed order" + _reply.OrderId + " Delivery type: " + message.DeliveryType + " Shippingfee: " + message.ShippingFee + " Delivery time" + message.DeliveryTime);
 }
Esempio n. 19
0
 public void UpdateOrder(OrderReply order)
 {
 }
Esempio n. 20
0
 private void OnStartOrders(int mode, uint transId, double orderNum, string classCode, string secCode, double price, int balance, double volume, int direction, int status, int orderDescriptor)
 {
     OrderReply.SafeInvoke((Modes)mode, transId, (long)orderNum, classCode, secCode, price, balance, (int)volume, (Sides)direction, (OrderStates)status);
 }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation($"Checking orders at {DateTimeOffset.Now}");
                try
                {
                    AppContext.SetSwitch(
                        "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport",
                        true);

                    var httpClient = new HttpClient();
                    httpClient.BaseAddress = new Uri("http://127.0.0.1:8194");

                    var grpcClient = GrpcClient.Create <OrdersManager.OrdersManagerClient>(httpClient);

                    OrderRequest request = new OrderRequest();
                    OrderReply   result  = await grpcClient.GetNewOrderAsync(request);

                    if (result.OrderId != 0)
                    {
                        var updateRequest = new UpdateOrderRequest()
                        {
                            OrderID = result.OrderId
                        };

                        try
                        {
                            UpdateOrderResponse updateResponse =
                                await grpcClient.UpdateOrderAsync(updateRequest);

                            if (updateResponse.Success)
                            {
                                _logger.LogInformation($"Order with id {result.OrderId} has been processed");
                            }
                            else
                            {
                                _logger.LogInformation($"Order with id {result.OrderId} was not updated and returned error {updateResponse.ErrorMessage}");
                            }
                        }
                        catch (Exception ex)
                        {
                            var msg = (ex.InnerException != null)
                                ? $"{ex.Message} {ex.InnerException.Message} {ex.StackTrace}"
                                : $"{ex.Message} {ex.StackTrace}";
                            _logger.LogInformation($"Order with id {result.OrderId} was not updated and returned error {msg}");
                        }
                    }
                    else
                    {
                        _logger.LogInformation($"No pending orders at {DateTimeOffset.Now}");
                    }
                }
                catch (Exception exc)
                {
                    _logger.LogError(exc.Message + exc.StackTrace);
                }

                await Task.Delay(3000, stoppingToken);
            }
        }