Beispiel #1
0
    public Task Handle(PlaceInvalidOrder placeOrder, IMessageHandlerContext context)
    {
        #region DelayedRetry

        var attempt = GetProcessingAttempt(context);

        if (attempt < 2)
        {
            log.Info($"Processing order {placeOrder.OrderId} failed. It will be retried using delayed retries.");
            //First attempt
            throw new Exception("Unexpected failure.");
        }

        #endregion

        log.Info($"Successfully processed order {placeOrder.OrderId}.");

        var placed = new PlaceOrderResponse
        {
            OrderId    = placeOrder.OrderId,
            WorkerName = Assembly.GetEntryAssembly().GetName().Name
        };

        return(context.Reply(placed));
    }
Beispiel #2
0
        public override async Task <PlaceOrderResponse> PlaceMarketOrder(MarketOrderRequest request, ServerCallContext context)
        {
            var token    = context.GetBearerToken();
            var response = await _walletApiV1Client.HotWalletPlaceMarketOrderAsync(
                new HotWalletOperation
            {
                AssetPair = request.AssetPairId,
                AssetId   = request.AssetId,
                Volume    = request.Volume
            },
                token,
                _walletApiConfig.Secret);

            var result = new PlaceOrderResponse();

            if (response.Result != null)
            {
                result.Body = _mapper.Map <OrderModel>(response.Result.Order);
            }

            if (response.Error != null)
            {
                result.Error = response.Error.ToApiError();
            }

            return(result);
        }
Beispiel #3
0
        public async Task <ActionResult <PlaceOrderResponse> > Place([FromBody] PlaceOrderRequest request)
        {
            _logger.LogInformation($"Place order service call for {request.OrderNumber}...");
            var response = new PlaceOrderResponse();

            try
            {
                await _orderProcessingService.PlaceOrderAsync(request.OrderNumber, request.UserId, request.OrderAmount, request.Gateway, request.Description, request.Callback);

                var order = await _orderProcessingService.GetOrderAsync(request.OrderNumber);

                response.Bills.AddRange(order.Bills.Select(x => (BillingInfoDTO)x).ToList());
            }
            catch (ValidationException ex)
            {
                _logger.LogWarning($"Validations failures: {ex.Message}");
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Exception occured while placing order: {ex.Message} {ex.StackTrace}");
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
            return(Ok(response));
        }
Beispiel #4
0
        public async Task <PlaceOrderResponse> PlaceOrder(PlaceOrderRequest request)
        {
            //Perform domain validation
            if (CanPlaceOrder(request))
            {
                var domainOrder = new Domain.Order()
                {
                    DatePlaced       = DateTime.Now,
                    CustomerId       = request.Order.CustomerId,
                    PromotionCode    = request.Order.PromotionCode,
                    BillingAddress   = request.Order.BillingAddress,
                    OrderLines       = request.Order.OrderLines,
                    ShippingAddress  = request.Order.ShippingAddress,
                    ShippingCost     = request.Order.ShippingCost,
                    TotalCost        = request.Order.TotalCost,
                    TransitLocations = request.Order.TransitLocations
                };
                //store the order in the repository
                await _unitOfWork.OrderRepos.AddAsync(domainOrder);

                _unitOfWork.Complete();
                var response = PlaceOrderResponse.Create(true, string.Empty, domainOrder.Id);
                //publish
                //_publisher.Publish(MapToContract(domainOrder, orderId));
                return(response);
            }
            else
            {
                var response = PlaceOrderResponse.Create(false, "Order validation failed", null);
                return(response);
            }
        }
Beispiel #5
0
        public async Task <PlaceOrderResponse> PlaceOrder(PlaceOrderRequest order)
        {
            string url         = $"/orders/create";
            var    requestBody = await Task.Run(() => JsonConvert.SerializeObject(order));

            using (HttpClient httpClient = new HttpClient())
            {
                PlaceOrderResponse data = new PlaceOrderResponse();
                try
                {
                    var authHeader = new AuthenticationHeaderValue("Bearer", await SecureStorage.GetAsync("auth_token"));
                    httpClient.DefaultRequestHeaders.Authorization = authHeader;
                    httpClient.BaseAddress = new Uri(Constants.BaseUrl);
                    StringContent       content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                    HttpResponseMessage result  = await httpClient.PostAsync(url, content);

                    string response = await result.Content.ReadAsStringAsync();

                    data = JsonConvert.DeserializeObject <PlaceOrderResponse>(response);

                    if (result.IsSuccessStatusCode && result.StatusCode == HttpStatusCode.OK)
                    {
                        return(data);
                    }

                    return(null);
                }
                catch (Exception exp)
                {
                    return(null);
                }
            }
        }
            internal override EntityRef Submit(OrderRequisition requisition, OrderEditorComponent component)
            {
                PlaceOrderResponse response = null;

                Platform.GetService <IOrderEntryService>(
                    service => response = service.PlaceOrder(new PlaceOrderRequest(requisition))
                    );

                return(response.Order.OrderRef);
            }
Beispiel #7
0
        //[AuthenticationValidationFilter(role: AuthRoles.Consumer)]
        public NegotiatedContentResult <PlaceOrderResponse> PostPlaceOrder([FromBody] PlaceOrderRequest request)
        {
            var properties = new Dictionary <string, string> {
                { "request", JsonConvert.SerializeObject(request) }
            };

            tm.TrackEvent(TelemetryEvents.PlaceOrder, properties);

            PlaceOrderResponse resp = _ordersServices.PlaceOrder(request);

            return(Content(HttpStatusCode.OK, resp));
        }
Beispiel #8
0
        public override void SendOrder(Order order)
        {
            _portfolioCurrent = order.PortfolioNumber;

            JsonObject jsonContent = new JsonObject();

            var accountData = order.PortfolioNumber.Split('_');

            var source = "spot-api";

            if (accountData[0] == "margin")
            {
                source = "margin-api";
            }
            else if (accountData[0] == "super-margin")
            {
                source = "super-margin-api";
            }

            jsonContent.Add("account-id", accountData[1]);
            jsonContent.Add("symbol", order.SecurityNameCode);
            jsonContent.Add("type", order.Side == Side.Buy ? "buy-limit" : "sell-limit");
            jsonContent.Add("amount", order.Volume);
            jsonContent.Add("price", order.Price);
            jsonContent.Add("source", source);
            jsonContent.Add("client-order-id", order.NumberUser);

            string url = _privateUriBuilder.Build("POST", "/v1/order/orders/place");

            StringContent httpContent = new StringContent(jsonContent.ToString(), Encoding.UTF8, "application/json");

            var httpClient = new HttpClient();

            var response = httpClient.PostAsync(url, httpContent).Result;

            string result = response.Content.ReadAsStringAsync().Result;

            PlaceOrderResponse orderResponse = JsonConvert.DeserializeObject <PlaceOrderResponse>(result);

            if (orderResponse.status == "ok")
            {
                SendLogMessage($"Order num {order.NumberUser} on exchange.", LogMessageType.Trade);
            }
            else
            {
                SendLogMessage($"Order exchange error num {order.NumberUser} : {orderResponse.errorMessage}", LogMessageType.Error);

                order.State = OrderStateType.Fail;

                OnOrderEvent(order);
            }
        }
Beispiel #9
0
    public async Task Handle(OrderValidated message, IMessageHandlerContext context)
    {
        log.Info($"Order {message.OrderId} validated. Sending notification to the customer.");

        await Task.Delay(1000).ConfigureAwait(false);

        var placed = new PlaceOrderResponse
        {
            OrderId    = message.OrderId,
            WorkerName = Assembly.GetEntryAssembly().GetName().Name
        };

        var options = new SendOptions();

        options.SetDestination(message.Sender);
        await context.Send(placed, options)
        .ConfigureAwait(false);
    }
 public List <PlaceOrderResponse> GetOrderPlace(int userId)
 {
     try
     {
         using (this.connection)
         {
             SqlCommand command = new SqlCommand("spGetPlaceOrder", this.connection);
             command.CommandType = CommandType.StoredProcedure;
             command.Parameters.AddWithValue("@UserId", userId);
             List <PlaceOrderResponse> placeorderRsponse = new List <PlaceOrderResponse>();
             PlaceOrderResponse        placeorder        = new PlaceOrderResponse();
             this.connection.Open();
             SqlDataReader dataReader = command.ExecuteReader();
             while (dataReader.Read())
             {
                 if (dataReader != null)
                 {
                     placeorder.OrderId        = (int)dataReader["OrderId"];
                     placeorder.BookId         = (int)dataReader["BookId"];
                     placeorder.BookName       = dataReader["BookName"].ToString();
                     placeorder.BookAutherName = dataReader["BookAutherName"].ToString();
                     placeorder.BookPrice      = (int)dataReader["BookPrice"];
                     placeorder.BookImage      = dataReader["BookImage"].ToString();
                     placeorder.CustomerId     = (int)dataReader["CustomerId"];
                     placeorder.Name           = dataReader["Name"].ToString();
                     placeorder.PhoneNumber    = dataReader["PhoneNumber"].ToString();
                     placeorder.Address        = dataReader["Address"].ToString();
                     placeorder.City           = dataReader["City"].ToString();
                     placeorderRsponse.Add(placeorder);
                     break;
                 }
             }
             return(placeorderRsponse);
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
     finally
     {
         this.connection.Close();
     }
 }
Beispiel #11
0
        public PlaceOrderResponse PlaceOrder(PlaceOrderRequest request)
        {
            //Create domain order from the request
            var domainOrder = Domain.Order.Create(
                orderLines: request.Order.OrderLines.Select(line => Domain.OrderLine.Create(
                                                                product: Domain.Product.Create(
                                                                    stockcode: line.Product.Stockcode,
                                                                    productImageUrl: line.Product.ProductImageUrl,
                                                                    volumetricWeight: line.Product.VolumetricWeight
                                                                    ),
                                                                quantity: line.Quantity,
                                                                unitPrice: line.UnitPrice
                                                                )).ToList(),
                customerId: request.Order.CustomerId,
                billingAddress: Domain.Address.Create(request.Order.BillingAddress.AddressLine1,
                                                      request.Order.BillingAddress.AddressLine2,
                                                      request.Order.BillingAddress.Country),
                shippingAddress: Domain.Address.Create(request.Order.ShippingAddress.AddressLine1,
                                                       request.Order.ShippingAddress.AddressLine2,
                                                       request.Order.ShippingAddress.Country),
                promotionCode: request.Order.PromotionCode,
                datePlaced: request.Order.DatePlaced,
                costCalculatorService: _costCalculatorService,
                productAvailabilityService: _productAvailabilityService,
                orderTrackingRepository: _orderTrackingRepository
                );

            //Perform domain validation
            if (domainOrder.CanPlaceOrder(request.ExpectedTotalCost, request.ExpectedShippingCost))
            {
                //store the order in the repository
                var orderId  = _orderRepository.Store(domainOrder);
                var response = PlaceOrderResponse.Create(true, string.Empty, orderId);
                //publish
                _publisher.Publish(MapToContract(domainOrder, orderId));
                return(response);
            }
            else
            {
                var response = PlaceOrderResponse.Create(false, "Order validation failed", null);
                return(response);
            }
        }
        public async Task Handle(PlaceOrder message, IMessageHandlerContext context)
        {
            #region Demo 2 - Request/Response

            Log.Info($"Received PlaceOrder, OrderId = {message.OrderId}, " +
                     $"OrderDate = {message.OrderDate}, ItemName = {message.ItemName}");

            var order = new SubmittedOrder {
                OrderDate = message.OrderDate, OrderId = message.OrderId
            };

            await _dbContext.SubmittedOrders.AddAsync(order);

            await _dbContext.SaveChangesAsync();

            var orderResponse = new PlaceOrderResponse
            {
                OrderId         = message.OrderId,
                StatusCompleted = true
            };

            await context.Reply(orderResponse);

            #endregion

            #region Demo 3 - Pub/Sub

            var orderCompleted = new OrderCompleted
            {
                OrderId = message.OrderId
            };

            await context.Publish(orderCompleted);

            #endregion
        }
 private void DisplayPlaceOrderResponse(PlaceOrderResponse placeOrderResponse)
 {
     AppendReceiverBox($"PlaceOrderResponse - Text: {placeOrderResponse.Text}, OrdID: {placeOrderResponse.OrderId}, OrdRejReason: {placeOrderResponse.OrdRejReason}, ResultCode: {placeOrderResponse.ResultCode}");
 }