private void GetOrder(int order_key)
        {
            ExecuteFaultHandledOperation(() =>
            {
                IOrderService order_service = service_factory.CreateClient <IOrderService>();
                using (order_service)
                {
                    Order           = new OrderWrapper(order_service.GetOrder(order_key));
                    AccountContacts = new ObservableCollection <AccountPerson>(Order.Account.Model.Employees.Where(item =>
                                                                                                                   item.CompanyRoleType == QIQOPersonType.AccountContact).ToList());
                    Order.PropertyChanged += Context_PropertyChanged;
                    Order.AcceptChanges();
                    _currentAccount = Order.Account.Model;
                }

                DefaultBillingAddress  = Order.OrderItems[0].OrderItemBillToAddress;
                DefaultShippingAddress = Order.OrderItems[0].OrderItemShipToAddress;
                ViewTitle     = Order.OrderNumber;
                GridIsEnabled = Order.OrderStatus != QIQOOrderStatus.Complete ? true : false;
                //AccountContacts = new ObservableCollection<AccountPerson>(Order.Account.Model.Employees.Where(item =>
                //                                                            item.CompanyRoleType == QIQOPersonType.AccountContact).ToList());
                event_aggregator.GetEvent <GeneralMessageEvent>().Publish($"Order {Order.OrderNumber} loaded successfully");
                event_aggregator.GetEvent <OrderLoadedEvent>().Publish(Order.OrderNumber);
            });
        }
Beispiel #2
0
        public InterpreterTests()
        {
            var container = new UnityContainer();

            //container.RegisterType<IExpression<string, object>, IndexExpression>();

            _contextMock = new Mock <IContext>();
            _contextMock.Setup(o => o.Input).Returns("[%o_number%] [%c_firstName%] [%c_lastName%]");

            var context = new Context("[%o_number%] [%c_firstName%] [%c_lastName%] [%h_SerialNumber%]");

            var contextInput = "Numer zlecenia [%numer%], Data: [%data%] ";

            _context2 = new Context(contextInput);

            var orderModel = new CustomerWrapper(new Customer()
            {
                Id = Guid.NewGuid(), FirstName = "Jan", LastName = "Nowak"
            });
            var customerModel = new OrderWrapper(new Order()
            {
                Id = Guid.NewGuid(), Number = "01/092019"
            });
            var hardwareModel = new HardwareWrapper(new Hardware()
            {
                Id = Guid.NewGuid(), SerialNumber = "12332151HD"
            });

            //_interpreter = new Interpreter(context, Expression.IndexExpression, orderModel, customerModel, hardwareModel);
        }
Beispiel #3
0
        private void SendNewOrderRequest(Orders order)
        {
            var orderWrapper = new OrderWrapper();

            orderWrapper.Order = new Order();

            orderWrapper.Order.OrderId      = order.Id;
            orderWrapper.Order.IsBuy        = order.Side;
            orderWrapper.Order.Price        = order.Rate;
            orderWrapper.Order.OpenQuantity = order.QuantityRemaining;
            orderWrapper.Order.IsStop       = order.StopRate != 0;
            orderWrapper.OrderCondition     = (OrderCondition)((byte)order.OrderCondition);
            orderWrapper.StopPrice          = order.StopRate;
            orderWrapper.TipQuantity        = order.IcebergQuantity > 0 ? order.Quantity : 0;
            orderWrapper.TotalQuantity      = order.IcebergQuantity ?? 0;
            if (order.CancelOn.HasValue)
            {
                DateTime Jan1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                orderWrapper.Order.CancelOn = (int)order.CancelOn.Value.Subtract(Jan1970).TotalSeconds;
            }

            var bytes = OrderSerializer.Serialize(orderWrapper);

            _queueProducer.Produce(bytes);
        }
        private OrderlineUniter UniteOrderlines(List <OrderLine> unSortedOrderlines)
        {
            OrderlineUniter uniter = new OrderlineUniter();

            foreach (OrderLine orderLine in unSortedOrderlines)
            {
                OrderWrapper key = uniter.QuantityPerProduct.FirstOrDefault(x => x.ProdV.Id == orderLine.ProductVersion.Id);


                if (key != null && key.OrderedUnit == orderLine.Unit)
                {
                    //The orderline already exists in the list, so we simply add the quantity of the current orderline.
                    key.Quantity += orderLine.Quantity;
                }
                else
                {
                    //The orderlines does not exsist, so we add a new one to the list.
                    uniter.QuantityPerProduct.Add(new OrderWrapper(orderLine.Quantity, orderLine.Unit, orderLine.ProductVersion));
                }
            }
            //Sorts the orderlines by name. Orderlines with the same name but different units will be two different entries, but grouped together.
            uniter.Sort();

            return(uniter);
        }
Beispiel #5
0
        public void Deserialize_Doesnotthrowexception()
        {
            var order1 = new Order {
                CancelOn = 12345678, IsBuy = true, OrderId = 56789, Price = 404, FeeId = 69
            };
            var orderWrapper = new OrderWrapper()
            {
                StopPrice = 9534, TotalQuantity = 7878234, TipQuantity = 2356, OrderCondition = OrderCondition.ImmediateOrCancel, OrderAmount = 12345.6789m, Order = order1
            };
            var bytes         = OrderSerializer.Serialize(orderWrapper);
            var messageLength = BitConverter.ToInt32(bytes, 0);

            Assert.Equal(99, messageLength);
            var order = OrderSerializer.Deserialize(bytes);

            Assert.Equal(12345678, order.Order.CancelOn);
            Assert.True(order.Order.IsBuy);
            Assert.Equal(OrderCondition.ImmediateOrCancel, order.OrderCondition);
            Assert.Equal((OrderId)56789, order.Order.OrderId);
            Assert.Equal(404, order.Order.Price);
            Assert.Equal(2356, order.TipQuantity);
            Assert.True(order.Order.IsStop);
            Assert.Equal(9534, order.StopPrice);
            Assert.Equal(7878234, order.TotalQuantity);
            Assert.Equal((Quantity)12345.6789m, order.OrderAmount);
            Assert.Equal(69, order.Order.FeeId);
        }
Beispiel #6
0
        public async Task <OpenOrderResult> PlaceOpeningOrder(TradeDetail trade, IEnumerable <TradeDetail> relatedTrades)
        {
            var market           = trade.Match.BetfairData.Markets.Single(x => x.MarketName == trade.MarketName);
            var runnerId         = market.Runners.Single(x => x.Name == trade.RunnerName).Id;
            var latestRunnerBook = await _runnerService.GetRunnerDetails(market.MarketId, runnerId);

            var orderTick           = _orderPriceFinder.GetPrice(trade.Side, latestRunnerBook.ExchangePrices);
            var openingOrderWrapper = new OrderWrapper(market.MarketId, runnerId, trade.Side, orderTick, PersistenceType.LAPSE);

            var policy = Policy.Handle <MarketSuspendedException>().Or <OrderActionErrorException>().Or <OrderNotPlaceableException>().WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt * 4)));

            var betReport = await policy.Execute(() => _orderPlacer.PlaceOrder(openingOrderWrapper));

            var betId = betReport.InstructionReports.Single().BetId;

            openingOrderWrapper.AddBetId(betId);
            _sleepService.Sleep(5000);

            var matchReport = await _runnerService.GetRunnerDetails(market.MarketId, runnerId);

            var orderReport = matchReport.Orders.Where(x => x.BetId == betId).Sum(x => x.SizeRemaining);

            if (orderReport != 0)
            {
                var cancelReport = await _orderPlacer.CancelOrder(betId, market.MarketId);

                if (cancelReport.Status == ExecutionReportStatus.SUCCESS)
                {
                    throw new OrderCancelledException(betId);
                }
            }

            return(new OpenOrderResult(trade, openingOrderWrapper));
        }
Beispiel #7
0
        public IActionResult AddOrder(OrderWrapper fromForm)
        {
            if (ModelState.IsValid)
            {
                Product Product = dbContext.Products
                                  .FirstOrDefault(p => p.ProductId == fromForm.Order.ProductId);
                Product.QuantityInStore = (Product.QuantityInStore - fromForm.Order.OrderQuantity);
                dbContext.Update(Product);
                dbContext.Entry(Product).Property("CreatedAt").IsModified = false;
                dbContext.SaveChanges();
                dbContext.Add(fromForm.Order);
                dbContext.SaveChanges();
                return(RedirectToAction("Orders"));
            }
            else
            {
                OrderWrapper OrderWrapper = new OrderWrapper();
                OrderWrapper.AllCustomers = dbContext.Customers.ToList();
                OrderWrapper.AllProducts  = dbContext.Products.ToList();
                OrderWrapper.AllOrders    = dbContext.Orders
                                            .Include(o => o.Product)
                                            .Include(o => o.Customer)
                                            .ToList();

                return(View("Orders", OrderWrapper));
            }
        }
        private OrderList SeparateOrders(OrderBase[] orders)
        {
            var result = new OrderList(_assetPairsCachedReader);

            foreach (var orderBase in orders)
            {
                var marketOrder = orderBase as MarketOrder;
                if (marketOrder != null)
                {
                    result.MarketOrders.Add(marketOrder);
                }

                var limitOrder = orderBase as LimitOrder;
                if (limitOrder != null)
                {
                    if (limitOrder.Action == OrderAction.Buy)
                    {
                        result.LimitOrdersBuy.Add(OrderWrapper.Create(limitOrder));
                    }

                    if (limitOrder.Action == OrderAction.Sell)
                    {
                        result.LimitOrdersSell.Add(OrderWrapper.Create(limitOrder));
                    }
                }
            }

            result.MarketOrders    = result.MarketOrders.OrderBy(itm => itm.Id).ToList();
            result.LimitOrdersBuy  = result.LimitOrdersBuy.OrderByDescending(itm => itm.Order.Price).ToList();
            result.LimitOrdersSell = result.LimitOrdersSell.OrderBy(itm => itm.Order.Price).ToList();

            return(result);
        }
 public OrderNotification(OrderWrapper<Notification> notificationInfo)
 {
     Id = notificationInfo.Order.Id;
     Status = notificationInfo.Order.Status;
     Description = notificationInfo.Order.Description;
     Warnings = notificationInfo.Warnings;
 }
Beispiel #10
0
        public void Deserialize_Doesnotthrowexception_Min()
        {
            var order1 = new Order {
                CancelOn = int.MinValue, IsBuy = false, OrderId = OrderId.MinValue, Price = int.MinValue, FeeId = short.MinValue
            };
            var orderWrapper = new OrderWrapper()
            {
                StopPrice = int.MinValue, TotalQuantity = int.MinValue, TipQuantity = int.MinValue, OrderCondition = OrderCondition.None, OrderAmount = Quantity.MinValue, Order = order1
            };
            var bytes         = OrderSerializer.Serialize(orderWrapper);
            var messageLength = BitConverter.ToInt32(bytes, 0);

            Assert.Equal(99, messageLength);
            var order = OrderSerializer.Deserialize(bytes);

            Assert.Equal(int.MinValue, order.Order.CancelOn);
            Assert.False(order.Order.IsBuy);
            Assert.Equal(OrderCondition.None, order.OrderCondition);
            Assert.Equal(OrderId.MinValue, order.Order.OrderId);
            Assert.Equal(int.MinValue, order.Order.Price);
            Assert.Equal(0, order.TipQuantity);
            Assert.False(order.Order.IsStop);
            Assert.Equal(int.MinValue, order.StopPrice);
            Assert.Equal(int.MinValue, order.TotalQuantity);
            Assert.Equal(Quantity.MinValue, order.OrderAmount);
            Assert.Equal(short.MinValue, order.Order.FeeId);
        }
Beispiel #11
0
        public void Deserialize_Doesnotthrowexception_Max()
        {
            var order1 = new Order {
                CancelOn = int.MaxValue, IsBuy = true, OrderId = OrderId.MaxValue, Price = int.MaxValue, OrderAmount = decimal.MaxValue
            };
            var orderWrapper = new OrderWrapper()
            {
                StopPrice = int.MaxValue, TotalQuantity = int.MaxValue, TipQuantity = int.MaxValue, OrderCondition = OrderCondition.FillOrKill, Order = order1
            };
            var bytes         = OrderSerializer.Serialize(orderWrapper);
            var messageLength = BitConverter.ToInt32(bytes, 0);

            Assert.Equal(97, messageLength);
            var order = OrderSerializer.Deserialize(bytes);

            Assert.Equal(int.MaxValue, order.Order.CancelOn);
            Assert.True(order.Order.IsBuy);
            Assert.Equal(OrderCondition.FillOrKill, order.OrderCondition);
            Assert.Equal(OrderId.MaxValue, order.Order.OrderId);
            Assert.Equal((Price)int.MaxValue, order.Order.Price);
            Assert.Equal((Quantity)int.MaxValue, order.TipQuantity);
            Assert.True(order.Order.IsStop);
            Assert.Equal((Price)int.MaxValue, order.StopPrice);
            Assert.Equal((Quantity)int.MaxValue, order.TotalQuantity);
            Assert.Equal((Quantity)decimal.MaxValue, order.Order.OrderAmount);
        }
Beispiel #12
0
        public async void PostTitleOrderAsync_Processing_Timeout()
        {
            // Arrange
            var helper = new TestHelper();
            var user   = PrincipalHelper.CreateForPermission();

            var options = Options.Create(new LtsaOptions());
            var service = helper.Create <LtsaService>(options, user);

            var token = new TokenModel()
            {
                AccessToken = "test"
            };
            var response = new OrderWrapper <OrderParent <Title> >(new TitleOrder()
            {
                Status = OrderParent <Title> .StatusEnum.Processing, OrderId = "1"
            });

            var client = helper.GetService <Mock <IHttpRequestClient> >();

            client.Setup(m => m.PostJsonAsync(It.IsAny <string>(), It.IsAny <IntegratorCredentials>())).ReturnsAsync <IHttpRequestClient, HttpResponseMessage>(new HttpResponseMessage()
            {
                Content = new StringContent(accessTokenResponse)
            });
            client.Setup(m => m.SendJsonAsync <OrderWrapper <OrderParent <Title> >, OrderWrapper <TitleOrder> >(It.IsAny <string>(), It.IsAny <HttpMethod>(), It.IsAny <OrderWrapper <TitleOrder> >(), It.IsAny <Func <HttpResponseMessage, bool> >())).ReturnsAsync(response);
            client.Setup(m => m.SendAsync <OrderWrapper <OrderParent <Title> > >(It.IsAny <string>(), It.IsAny <HttpMethod>(), It.IsAny <HttpContent>(), It.IsAny <Func <HttpResponseMessage, bool> >())).ReturnsAsync(response);

            // Act
            await Assert.ThrowsAsync <LtsaException>(async() => await service.PostTitleOrder("titleNumber", "VA"));

            // Assert
            client.Verify(m => m.SendJsonAsync <OrderWrapper <OrderParent <Title> >, OrderWrapper <TitleOrder> >(options.Value.HostUri.AppendToURL(options.Value.OrdersEndpoint), HttpMethod.Post,
                                                                                                                 It.IsAny <OrderWrapper <TitleOrder> >(), null), Times.Once());
            client.Verify(m => m.SendAsync <OrderWrapper <OrderParent <Title> > >(It.IsAny <string>(), It.IsAny <HttpMethod>(), It.IsAny <HttpContent>(), It.IsAny <Func <HttpResponseMessage, bool> >()), Times.AtLeastOnce());
        }
Beispiel #13
0
        public async void PostSpcpOrderAsync_Valid()
        {
            // Arrange
            var helper = new TestHelper();
            var user   = PrincipalHelper.CreateForPermission();

            var options = Options.Create(new LtsaOptions());
            var service = helper.Create <LtsaService>(options, user);

            var token = new TokenModel()
            {
                AccessToken = "test"
            };
            var response = new OrderWrapper <OrderParent <StrataPlanCommonProperty> >(new SpcpOrder());

            var client = helper.GetService <Mock <IHttpRequestClient> >();

            client.Setup(m => m.PostJsonAsync(It.IsAny <string>(), It.IsAny <IntegratorCredentials>())).ReturnsAsync <IHttpRequestClient, HttpResponseMessage>(new HttpResponseMessage()
            {
                Content = new StringContent(accessTokenResponse)
            });
            client.Setup(m => m.SendJsonAsync <OrderWrapper <OrderParent <StrataPlanCommonProperty> >, OrderWrapper <SpcpOrder> >(It.IsAny <string>(), It.IsAny <HttpMethod>(), It.IsAny <OrderWrapper <SpcpOrder> >(), It.IsAny <Func <HttpResponseMessage, bool> >())).ReturnsAsync(response);

            // Act
            var result = await service.PostSpcpOrder("123-456-789");

            // Assert
            Assert.NotNull(result);
            Assert.IsAssignableFrom <OrderWrapper <OrderParent <StrataPlanCommonProperty> > >(result);
            client.Verify(m => m.SendJsonAsync <OrderWrapper <OrderParent <StrataPlanCommonProperty> >, OrderWrapper <SpcpOrder> >(options.Value.HostUri.AppendToURL(options.Value.OrdersEndpoint), HttpMethod.Post,
                                                                                                                                   It.IsAny <OrderWrapper <SpcpOrder> >(), null), Times.Once());
            result.Order.Should().Be(response.Order);
        }
Beispiel #14
0
 private void InitializeOrder(Order order)
 {
     Order = new OrderWrapper(order);
     Order.PropertyChanged += (s, e) =>
     {
         if (!HasChanges)
         {
             HasChanges = _orderRepository.HasChanges();
         }
         if (e.PropertyName == nameof(Order.HasErrors))
         {
             ((DelegateCommand)SaveCommand).RaiseCanExecuteChanged();
         }
         if (e.PropertyName == nameof(Order.OrderNumber) ||
             e.PropertyName == nameof(Order.OrderDate))
         {
             SetTitle();
         }
     };
     ((DelegateCommand)SaveCommand).RaiseCanExecuteChanged();
     if (Order.Id == 0)
     {
         // little trick to trigger the validation
         Order.OrderDate = DateTime.Now.Date;
     }
     SetTitle();
 }
Beispiel #15
0
        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);

            if (navigationContext.Parameters.ContainsKey("CustomerId"))
            {
                //Order is a new order
                SetBusy("OrderLoad", true);
                var customerId = navigationContext.Parameters.GetValue <Guid>("CustomerId");
                await DispatcherHelper.ExecuteOnUIThreadAsync(
                    async() =>
                {
                    var customer = await _contosoRepository.Customers.GetAsync(customerId);
                    Order        = new OrderWrapper(_contosoRepository, new Order(customer));
                });

                SetBusy("OrderLoad", false);
            }

            if (navigationContext.Parameters.ContainsKey("OrderId"))
            {
                //Order is an existing order
                SetBusy("OrderLoad", true);
                var orderId = navigationContext.Parameters.GetValue <Guid>("OrderId");
                await DispatcherHelper.ExecuteOnUIThreadAsync(
                    async() =>
                {
                    var order = await _contosoRepository.Orders.GetAsync(orderId);
                    Order     = new OrderWrapper(_contosoRepository, order);
                });

                SetBusy("OrderLoad", false);
            }
        }
Beispiel #16
0
 internal OrderNotification(OrderWrapper <Notification> notificationInfo)
 {
     Id          = notificationInfo.Order.Id;
     Status      = notificationInfo.Order.Status;
     Description = notificationInfo.Order.Description;
     Custom      = notificationInfo.Order.Custom;
     Warnings    = notificationInfo.Warnings;
 }
Beispiel #17
0
        static void Main(string[] args)
        {
            try
            {
                do
                {
                    Console.WriteLine("Type \"INITIALIZE\" (in caps) to initialize process.");
                } while (Console.ReadLine() != "INITIALIZE");

                int marketId;
                do
                {
                    Console.Write("Enter Market Id > ");
                } while (!int.TryParse(Console.ReadLine(), out marketId));
                Console.WriteLine(marketId);

                do
                {
                    Console.Write("Re-Enter Market Id > ");
                } while (!int.TryParse(Console.ReadLine(), out var f) || f != marketId);
                Console.WriteLine(marketId);

                QueueProducer queueProducer = new QueueProducer("engine-in", "fanout", "engine-reader", "#", "localhost", "/", "guest", "guest");
                var           dbContext     = new ExchangeContext(new GlobalQueryFilterRegisterer(), "Host=localhost;Database=Exchange;Username=postgres;Password=root");
                var           orders        = dbContext.Orders.Where(x => x.IsDeleted == false && x.MarketId == marketId && (x.OrderStatus == Entity.Partials.OrderStatus.Accepted || x.OrderStatus == Entity.Partials.OrderStatus.Received)).OrderBy(x => x.CreatedOn).ToList();
                foreach (var order in orders)
                {
                    var orderWrapper = new OrderWrapper();
                    orderWrapper.Order = new Order();

                    orderWrapper.Order.OrderId      = order.Id;
                    orderWrapper.Order.IsBuy        = order.Side;
                    orderWrapper.Order.Price        = order.Rate;
                    orderWrapper.Order.OpenQuantity = order.QuantityRemaining;
                    orderWrapper.Order.IsStop       = order.StopRate != 0;
                    orderWrapper.OrderCondition     = (OrderCondition)((byte)order.OrderCondition);
                    orderWrapper.StopPrice          = order.StopRate;
                    orderWrapper.TipQuantity        = order.IcebergQuantity > 0 ? order.Quantity : 0;
                    orderWrapper.TotalQuantity      = order.IcebergQuantity ?? 0;
                    if (order.CancelOn.HasValue)
                    {
                        DateTime Jan1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                        orderWrapper.Order.CancelOn = (int)order.CancelOn.Value.Subtract(Jan1970).TotalSeconds;
                    }

                    var bytes = OrderSerializer.Serialize(orderWrapper);
                    queueProducer.Produce(bytes);
                }
                queueProducer.Flush();
                queueProducer.Close();
                Console.WriteLine("Finished..");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Console.ReadLine();
        }
        public async Task <PlaceExecutionReport> PlaceOrder(OrderWrapper orderWrapper)
        {
            var method = "SportsAPING/v1.0/placeOrders";

            var args = new Dictionary <string, object>
            {
                ["marketId"] = orderWrapper.MarketId
            };

            var limitOrder = new LimitOrder
            {
                PersistenceType = orderWrapper.Persistencetype,
                Price           = orderWrapper.OrderTick.Price,
                Size            = orderWrapper.OrderTick.Stake
            };

            var placeInstructions = new List <PlaceInstruction>()
            {
                new PlaceInstruction
                {
                    Handicap    = 0,
                    Side        = orderWrapper.Side,
                    OrderType   = OrderType.LIMIT,
                    LimitOrder  = limitOrder,
                    SelectionId = orderWrapper.SelectionId,
                }
            };

            args["instructions"] = placeInstructions;

            var apiClient = await _apiClientFactory.GetApiClient();

            var placeOrderReport = apiClient.GetData <JsonResponse <PlaceExecutionReport> >(method, args);

            if (placeOrderReport.Result.Status == ExecutionReportStatus.SUCCESS)
            {
                return(placeOrderReport.Result);
            }

            if (placeOrderReport.Result.ErrorCode == ExecutionReportErrorCode.MARKET_SUSPENDED)
            {
                throw new MarketSuspendedException();
            }

            if (placeOrderReport.Result.ErrorCode == ExecutionReportErrorCode.BET_ACTION_ERROR)
            {
                throw new OrderActionErrorException();
            }

            if (placeOrderReport.Result.ErrorCode == ExecutionReportErrorCode.INSUFFICIENT_FUNDS)
            {
                throw new InsufficientFundsException();
            }

            throw new OrderNotPlaceableException();
        }
 public void orderJsonSerialize()
 {
     var order = new Order {
         IsBuy = true, IsTip = false, OpenQuantity = 100, OrderId = 1001, Price = 400, Sequnce = 0
     };
     var orderWrapper = new OrderWrapper()
     {
         TotalQuantity = 100, OrderCondition = OrderCondition.None, StopPrice = 0
     };
     var orderJsonString = JsonConvert.SerializeObject(orderWrapper);
 }
 public void orderBinarySerialize()
 {
     var order = new Order {
         IsBuy = true, IsTip = false, OpenQuantity = 100, OrderId = 1001, Price = 400, Sequnce = 0
     };
     var orderWrapper = new OrderWrapper()
     {
         TotalQuantity = 100, OrderCondition = OrderCondition.None, StopPrice = 0
     };
     var bytes = OrderSerializer.Serialize(orderWrapper);
 }
Beispiel #21
0
 public void Serialize_Doesnotthrowexception_Max()
 {
     var order1 = new Order {
         CancelOn = int.MaxValue, IsBuy = true, OrderId = OrderId.MaxValue, Price = int.MaxValue, OrderAmount = decimal.MaxValue
     };
     var orderWrapper = new OrderWrapper()
     {
         StopPrice = int.MaxValue, TotalQuantity = int.MaxValue, TipQuantity = int.MaxValue, OrderCondition = OrderCondition.FillOrKill, Order = order1
     };
     var bytes = OrderSerializer.Serialize(orderWrapper);
 }
Beispiel #22
0
 internal OrderNotification(OrderWrapper <Notification> notificationInfo)
 {
     Id           = notificationInfo.Order.Id;
     Status       = notificationInfo.Order.Status;
     OldStatus    = notificationInfo.Order.OldStatus;
     Description  = notificationInfo.Order.Description;
     Custom       = notificationInfo.Order.Custom;
     Category     = notificationInfo.Order.Category;
     DecisionCode = notificationInfo.Order.DecisionCode;
     Warnings     = notificationInfo.Warnings;
 }
 public bool CloseOrder(OrderWrapper order)
 {
     if (open_orders.ContainsValue(order))
     {
         var key = open_orders.FirstOrDefault(x => x.Value == order).Key;
         open_orders.Remove(key);
         event_aggregator.GetEvent <OpenOrderServiceEvent>().Publish(open_orders.Count);
         return(true);
     }
     return(false);
 }
Beispiel #24
0
 public void Serialize_Doesnotthrowexception_Min()
 {
     var order1 = new Order {
         CancelOn = int.MinValue, IsBuy = false, OrderId = OrderId.MinValue, Price = int.MinValue, FeeId = short.MinValue
     };
     var orderWrapper = new OrderWrapper()
     {
         StopPrice = int.MinValue, TotalQuantity = int.MinValue, TipQuantity = int.MinValue, OrderCondition = OrderCondition.None, OrderAmount = Quantity.MinValue, Order = order1
     };
     var bytes = OrderSerializer.Serialize(orderWrapper);
 }
        /// <summary>
        /// Validates the Order object fields
        /// Sends the order to riskified server endpoint as configured in the ctor
        /// </summary>
        /// <param name="order">The order object to send</param>
        /// <param name="riskifiedEndpointUrl">the endpoint to which the order should be sent</param>
        /// <returns>The order tranaction result containing status and order id  in riskified servers (for followup only - not used latter) in case of successful transfer</returns>
        /// <exception cref="OrderFieldBadFormatException">On bad format of the order (missing fields data or invalid data)</exception>
        /// <exception cref="RiskifiedTransactionException">On errors with the transaction itself (network errors, bad response data)</exception>
        private OrderNotification SendOrder(AbstractOrder order, Uri riskifiedEndpointUrl)
        {
            if (_validationMode != Validations.Skip)
            {
                order.Validate(_validationMode);
            }
            var wrappedOrder      = new OrderWrapper <AbstractOrder>(order);
            var transactionResult = HttpUtils.JsonPostAndParseResponseToObject <OrderWrapper <Notification>, OrderWrapper <AbstractOrder> >(riskifiedEndpointUrl, wrappedOrder, _authToken, _shopDomain);

            return(new OrderNotification(transactionResult));
        }
 public bool OpenOrder(OrderWrapper order)
 {
     if (!open_orders.ContainsValue(order))
     {
         string new_key = GenOrderKey();
         order.OrderNumber = new_key;
         open_orders.Add(new_key, order);
         event_aggregator.GetEvent <OpenOrderServiceEvent>().Publish(open_orders.Count);
         return(true);
     }
     return(false);
 }
Beispiel #27
0
        public async void PostLtsaFieldsAsync_Valid()
        {
            // Arrange
            var helper = new TestHelper();
            var user   = PrincipalHelper.CreateForPermission();

            var options = Options.Create(new LtsaOptions());
            var service = helper.Create <LtsaService>(options, user);

            var token = new TokenModel()
            {
                AccessToken = "test"
            };
            var titleResponse          = new OrderWrapper <OrderParent <Title> >(new TitleOrder());
            var parcelInfoResponse     = new OrderWrapper <OrderParent <ParcelInfo> >(new ParcelInfoOrder());
            var titleSummariesResponse = new TitleSummariesResponse()
            {
                TitleSummaries = new List <TitleSummary>()
                {
                    new TitleSummary()
                    {
                        TitleNumber           = "titleNumber",
                        LandTitleDistrictCode = LandTitleDistrictCode.VA,
                    }
                }
            };

            var client = helper.GetService <Mock <IHttpRequestClient> >();

            client.Setup(m => m.PostJsonAsync(It.IsAny <string>(), It.IsAny <IntegratorCredentials>())).ReturnsAsync <IHttpRequestClient, HttpResponseMessage>(new HttpResponseMessage()
            {
                Content = new StringContent(accessTokenResponse)
            });
            client.Setup(m => m.SendJsonAsync <OrderWrapper <OrderParent <Title> >, OrderWrapper <TitleOrder> >(It.IsAny <string>(), It.IsAny <HttpMethod>(), It.IsAny <OrderWrapper <TitleOrder> >(), It.IsAny <Func <HttpResponseMessage, bool> >())).ReturnsAsync(titleResponse);
            client.Setup(m => m.SendJsonAsync <OrderWrapper <OrderParent <ParcelInfo> >, OrderWrapper <ParcelInfoOrder> >(It.IsAny <string>(), It.IsAny <HttpMethod>(), It.IsAny <OrderWrapper <ParcelInfoOrder> >(), It.IsAny <Func <HttpResponseMessage, bool> >())).ReturnsAsync(parcelInfoResponse);
            client.Setup(m => m.SendAsync <TitleSummariesResponse>(It.IsAny <string>(), It.IsAny <HttpMethod>(), It.IsAny <HttpContent>(), It.IsAny <Func <HttpResponseMessage, bool> >())).ReturnsAsync(titleSummariesResponse);

            // Act
            var result = await service.PostLtsaFields("123-456-789");

            // Assert
            Assert.NotNull(result);
            Assert.IsAssignableFrom <LtsaOrders>(result);
            client.Verify(m => m.SendJsonAsync <OrderWrapper <OrderParent <Title> >, OrderWrapper <TitleOrder> >(options.Value.HostUri.AppendToURL(options.Value.OrdersEndpoint), HttpMethod.Post,
                                                                                                                 It.IsAny <OrderWrapper <TitleOrder> >(), null), Times.Once());
            client.Verify(m => m.SendJsonAsync <OrderWrapper <OrderParent <ParcelInfo> >, OrderWrapper <ParcelInfoOrder> >(options.Value.HostUri.AppendToURL(options.Value.OrdersEndpoint), HttpMethod.Post,
                                                                                                                           It.IsAny <OrderWrapper <ParcelInfoOrder> >(), null), Times.Once());
            result.ParcelInfo.Should().Be(parcelInfoResponse.Order);
            result.TitleOrders.Should().BeEquivalentTo(new List <OrderParent <Title> >()
            {
                titleResponse.Order
            });
        }
        private bool VerifyDetails(Dictionary <string, object> y, OrderWrapper orderWrapper)
        {
            var success     = false;
            var instruction = y["instructions"] as List <PlaceInstruction>;

            success = 1 == instruction.Count;
            success = instruction.Single().Handicap == 0;
            success = instruction.Single().Side == orderWrapper.Side;
            success = instruction.Single().OrderType == OrderType.LIMIT;
            success = instruction.Single().LimitOrder.PersistenceType == orderWrapper.Persistencetype;
            success = instruction.Single().LimitOrder.Price == orderWrapper.OrderTick.Price;
            success = instruction.Single().LimitOrder.Size == orderWrapper.OrderTick.Stake;
            success = instruction.Single().SelectionId == orderWrapper.SelectionId;
            return(success);
        }
        private async Task CloseoutBet(OpenOrderResult openingOrderSummary)
        {
            var marketId = openingOrderSummary.OpenOrderResponse.MarketId;
            var runnerId = openingOrderSummary.OpenOrderResponse.SelectionId;
            var betId    = openingOrderSummary.OpenOrderResponse.BetId;

            var latestRunnerBook = await _runnerService.GetRunnerDetails(marketId, runnerId);

            var openingOrders = latestRunnerBook.Orders.Where(x => x.BetId == betId).ToList();

            double closingPrice = 0;

            if (openingOrderSummary.OpenOrderRequest.TrackingTradeOffset.HasValue)
            {
                closingPrice = PriceLadderUtility.GetWinningPriceTarget(Side.BACK, openingOrderSummary.OpenOrderResponse.OrderTick.Price, openingOrderSummary.OpenOrderRequest.TrackingTradeOffset.Value);
            }
            else if (openingOrderSummary.OpenOrderResponse.Side == Side.BACK)
            {
                closingPrice = latestRunnerBook.ExchangePrices.AvailableToLay.Min(x => x.Price);
            }
            else if (openingOrderSummary.OpenOrderResponse.Side == Side.LAY)
            {
                closingPrice = latestRunnerBook.ExchangePrices.AvailableToBack.Max(x => x.Price);
            }
            else
            {
                throw new System.Exception("No closing side specified");
            }

            var closeoutStake = _closingStakeCalculator.GetFullHedgeStake(openingOrders, closingPrice);

            var orderWrapper        = new OrderWrapper(marketId, runnerId, closeoutStake.Key, new OrderTick(closingPrice, closeoutStake.Value), PersistenceType.LAPSE);
            var closeoutOrderReport = await _orderPlacer.PlaceOrder(orderWrapper);

            if (closeoutOrderReport.Status != ExecutionReportStatus.SUCCESS)
            {
                throw new System.Exception("Closeout bet not placed!");
            }

            var closeoutBetId = closeoutOrderReport.InstructionReports.Single().BetId;

            _sleepService.Sleep(10000);
            await ManageCloseoutOrderMatching(marketId, runnerId, closeoutBetId);
        }
Beispiel #30
0
        public IActionResult Orders()
        {
            RegisterUser fromLogin = HttpContext.Session.GetObjectFromJson <RegisterUser>("LoggedInUser");

            if (fromLogin == null)
            {
                return(RedirectToAction("Index"));
            }
            OrderWrapper OrderWrapper = new OrderWrapper();

            OrderWrapper.AllCustomers = dbContext.Customers.ToList();
            OrderWrapper.AllProducts  = dbContext.Products.ToList();
            OrderWrapper.AllOrders    = dbContext.Orders
                                        .Include(o => o.Product)
                                        .Include(o => o.Customer)
                                        .ToList();

            return(View("Orders", OrderWrapper));
        }
        private void InitNewOrder()
        {
            Order new_order = new Order() //*** GET this initializatoin stuff into the objects themselves!! (complete)
            {
                OrderEntryDate  = DateTime.Now,
                OrderStatusDate = DateTime.Now,
                DeliverByDate   = DateTime.Now.AddDays(7), // think about a defaul lead time for each account
                SalesRep        = SalesRepList[0],
                AccountRep      = AccountRepList[0]
            };

            new_order.OrderItems.Add(InitNewOrderItem(1));
            SelectedOrderItemIndex = 0;

            Order = new OrderWrapper(new_order);
            DefaultBillingAddress  = new AddressWrapper(new Address());
            DefaultShippingAddress = new AddressWrapper(new Address());
            Order.PropertyChanged += Context_PropertyChanged;
            Order.AcceptChanges();
            GridIsEnabled = false;
        }
        private void OnChangeSelectedCustomer(CustomerWrapper selectedCustomer)
        {
            selectedCustomer.Orders =
                    new ObservableCollection<OrderWrapper>(
                        _ordersRepository.GetAllOrders().Where(o => o.CustomerId == SelectedCustomer.Id).Select(
                            x => new OrderWrapper(x)));

            var order = new Order
                            {
                                CustomerId = selectedCustomer.Id,
                                ItemsTotal = 1,
                                OrderDate = DateTime.Now,
                                StoreId = selectedCustomer.StoreId,
                                Phone = SelectedCustomer.Phone,
                                DeliveryCity = SelectedCustomer.City,
                                DeliveryState = selectedCustomer.State,
                                DeliveryStreet = selectedCustomer.Street,
                                DeliveryZip = selectedCustomer.Zip,
                                DeliveryDate = DateTime.Now.AddDays(2)
                            };

            NewOrder = new OrderWrapper(order);
        }
 private void OnCancel(object obj)
 {
    if(NewOrder.IsChanged)
    {
        var result = _messageDialogService.ShowYesNoDialog("Cancel", "Do you want to cancel");
        if(result == MessageDialogResult.Yes)
        {
            NewOrder = new OrderWrapper(new Order());
        }
    }
 }
Beispiel #34
0
 /// <summary>
 /// Validates the Order object fields
 /// Sends the order to riskified server endpoint as configured in the ctor
 /// </summary>
 /// <param name="order">The order object to send</param>
 /// <param name="riskifiedEndpointUrl">the endpoint to which the order should be sent</param>
 /// <returns>The order tranaction result containing status and order id  in riskified servers (for followup only - not used latter) in case of successful transfer</returns>
 /// <exception cref="OrderFieldBadFormatException">On bad format of the order (missing fields data or invalid data)</exception>
 /// <exception cref="RiskifiedTransactionException">On errors with the transaction itself (network errors, bad response data)</exception>
 private OrderNotification SendOrder(AbstractOrder order, Uri riskifiedEndpointUrl)
 {
     if(_validationMode != Validations.Skip)
     {
         order.Validate(_validationMode);
     }
     var wrappedOrder = new OrderWrapper<AbstractOrder>(order);
     var transactionResult = HttpUtils.JsonPostAndParseResponseToObject<OrderWrapper<Notification>, OrderWrapper<AbstractOrder>>(riskifiedEndpointUrl, wrappedOrder, _authToken, _shopDomain);
     return new OrderNotification(transactionResult);
 }