public async void Cannot_SaveOrder_As_Amount_Is_Wrong_Tests() { //Arrange FileHandler handler = new FileHandler(); handler.ItemCSVPath = @"D:\Upwork\Assignment\VendingMachineSln\inventory.csv"; handler.OrderCSVPath = @"D:\Upwork\Assignment\VendingMachineSln\orders.csv"; IOrderProcessor oproc = new OrderProcessor(handler); IInventoryProcessor invproc = new InventoryProcessor(handler); oproc.InventoryProcessor = invproc; Order order = new Order { Amount = 100.0f, Item = new Item { ID = 1 }, Quantity = 2 }; string expectedErrorMsg = $"Your Order submission is unsuccessful, As order amount is wrong it needs to be $400.00"; //Act Func <Task> ofct = () => oproc.SaveOrder(order); //Assert var ex = await Assert.ThrowsAsync <Exception>(ofct); Assert.Equal(expectedErrorMsg, ex.Message); }
public async void Can_SaveOrder_Tests() { //Arrange FileHandler handler = new FileHandler(); handler.ItemCSVPath = @"D:\Upwork\Assignment\VendingMachineSln\inventory.csv"; handler.OrderCSVPath = @"D:\Upwork\Assignment\VendingMachineSln\orders.csv"; IOrderProcessor oproc = new OrderProcessor(handler); IInventoryProcessor invproc = new InventoryProcessor(handler); oproc.InventoryProcessor = invproc; Order order = new Order { Amount = 400.0f, Item = new Item { ID = 1 }, Quantity = 2 }; var orders = (await oproc.GetOrders()); int newID = orders.Values.Max(o => o.OID) + 1; string successMsg = "Your Order submission is successful."; //Act string message = await oproc.SaveOrder(order); //Assert var porders = await oproc.GetOrders(); var dorders = porders.Values.Except(orders.Values, new OrderComparer()).FirstOrDefault(); order.OID = newID; Assert.NotNull(dorders); Assert.IsType <Order>(dorders); Assert.Equal(order, dorders, new OrderComparer()); Assert.Equal(successMsg, message); }
public async void Cannot_SaveOrder_As_File_Doesnot_Exist_Tests() { //Arrange FileHandler handler = new FileHandler(); handler.ItemCSVPath = @"D:\Upwork\Assignment\VendingMachineSln\inventory.csv"; handler.OrderCSVPath = @"D:\Upwork\Assignment\VendingMachineSln\ordersnotexist.csv"; IOrderProcessor oproc = new OrderProcessor(handler); IInventoryProcessor invproc = new InventoryProcessor(handler); oproc.InventoryProcessor = invproc; Order order = new Order { Amount = 400.0f, Item = new Item { ID = 1 }, Quantity = 2 }; string expectedErrorMsg = "System error with orders.csv file. Please contact your adminstrator for further assistance."; //Act Func <Task> ofct = () => oproc.SaveOrder(order); //Assert var ex = await Assert.ThrowsAsync <Exception>(ofct); Assert.Equal(expectedErrorMsg, ex.Message); }
public async void Cannot_SaveOrder_As_Item_Quantity_Is_UnAvailable_Tests() { //Arrange FileHandler handler = new FileHandler(); handler.ItemCSVPath = @"D:\Upwork\Assignment\VendingMachineSln\inventory.csv"; handler.OrderCSVPath = @"D:\Upwork\Assignment\VendingMachineSln\orders.csv"; IOrderProcessor oproc = new OrderProcessor(handler); IInventoryProcessor invproc = new InventoryProcessor(handler); oproc.InventoryProcessor = invproc; Order order = new Order { Amount = 400.0f, Item = new Item { ID = 1 }, Quantity = 50 }; string expectedErrorMsg = "Your Order submission is unsuccessful, Due to insufficient inventory of item."; //Act Func <Task> ofct = () => oproc.SaveOrder(order); //Assert var ex = await Assert.ThrowsAsync <Exception>(ofct); Assert.Equal(expectedErrorMsg, ex.Message); }
public NetworkMessageBuffer(Game game, IConnection connection) { FrameOrders = new Dictionary <uint, List <Order> >(); _localOrders = new List <Order>(); _connection = connection; _orderProcessor = new OrderProcessor(game); }
protected void ProcessOrder() { if (ClientOrderData.OrderAttributeValues.ContainsKey("amazonrefid") && ClientOrderData.OrderAttributeValues.GetAttributeValue("AmazonRefID") != null) { ClientOrderData = OrderHelper.SaveAmazonOrder(ClientOrderData, (string)Session["OrderRefId"]); if (ClientOrderData.OrderId > 0) { OrderProcessor.ProcessOrderAndRedirect(ClientOrderData.OrderId);//Response.Redirect("PostSale"); } } else { if (CSFactory.OrderProcessCheck() == (int)OrderProcessTypeEnum.InstantOrderProcess) { int orderId = CSResolve.Resolve <IOrderService>().SaveOrder(ClientOrderData); ClientOrderData.OrderId = orderId; //clientData.ResetData(); Session["ClientOrderData"] = ClientOrderData; } Response.Redirect("PostSale.aspx"); } }
public void Setup() { _settings = new SettingsProvider( new[] { new Category { Genre = "C1", Discount = 0 }, new Category { Genre = "C2", Discount = 5 } }, new[] { new Book { Title = "B1", Genre = "C1", UnitPrice = 5 }, new Book { Title = "B2", Genre = "C1", UnitPrice = 15 }, new Book { Title = "B3", Genre = "C2", UnitPrice = 35 }, new Book { Title = "B4", Genre = "C2", UnitPrice = 50 }, }, 10, 20, 30); _processor = new OrderProcessor(_settings); }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSTakePayment started.", 20400); try { // take customer funds // assume success for now // audit orderProcessor.CreateAudit( "Funds deducted from customer credit card account.", 20402); // update order status orderProcessor.Order.UpdateStatus(5); // continue processing orderProcessor.ContinueNow = true; } catch { // fund checking failure throw new OrderProcessorException( "Error occured while taking payment.", 4); } // audit processor.CreateAudit("PSTakePayment finished.", 20401); }
public void TestCopperForGoldOrder() { var askRepositoryMock = new Mock <IAskRepository>(); askRepositoryMock.Setup(f => f.GetAsks()).Returns(GetAsksForCopperForGoldOrder()); var commodityRepositoryMock = new Mock <ICommodityRepository>(); commodityRepositoryMock.Setup(f => f.GetCommodities()).Returns(GetCommodities()); Ask ask = new Ask(); ask.AllowPartialFill = true; ask.ApplyCommissionToBuy = true; ask.BuyQuantity = 1000000; ask.CommodityBuyID = copper; ask.CommoditySellID = gold; ask.SellRatio = 1295; ask.BuyRatio = 3; ask.MaxLegDepth = 4; var askRepository = askRepositoryMock.Object; OrderProcessor proc = new OrderProcessor(askRepository, commodityRepositoryMock.Object); Stopwatch watch = new Stopwatch(); proc.Start().Wait(); watch.Start(); var order = proc.GetQuote(ask); watch.Stop(); TestContext.WriteLine(watch.ElapsedMilliseconds.ToString()); Assert.AreNotEqual(0, order.Sum(o => o.OrderLegs.Where(ol => ol.CommodityBuyID == copper).Sum(ol => ol.BuyQuantity))); }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSCheckStock started.", 20200); try { // send mail to supplier orderProcessor.MailSupplier("BalloonShop stock check.", GetMailBody()); // audit orderProcessor.CreateAudit( "Notification e-mail sent to supplier.", 20202); // update order status orderProcessor.Order.UpdateStatus(3); } catch { // mail sending failure throw new OrderProcessorException( "Unable to send e-mail to supplier.", 2); } // audit processor.CreateAudit("PSCheckStock finished.", 20201); }
public void GetMarginRemainingTests() { const int quantity = 1000; const decimal leverage = 2; var orderProcessor = new OrderProcessor(); var portfolio = GetPortfolio(orderProcessor, quantity); var security = GetSecurity(Symbols.AAPL); var buyingPowerModel = new TestSecurityMarginBuyingPowerModel(leverage); security.BuyingPowerModel = buyingPowerModel; portfolio.Securities.Add(security); security.Holdings.SetHoldings(1m, quantity); var actual1 = buyingPowerModel.GetMarginRemaining(portfolio, security, OrderDirection.Buy); Assert.AreEqual(quantity / leverage, actual1); var actual2 = buyingPowerModel.GetMarginRemaining(portfolio, security, OrderDirection.Sell); Assert.AreEqual(quantity, actual2); security.Holdings.SetHoldings(1m, -quantity); var actual3 = buyingPowerModel.GetMarginRemaining(portfolio, security, OrderDirection.Sell); Assert.AreEqual(quantity / leverage, actual3); var actual4 = buyingPowerModel.GetMarginRemaining(portfolio, security, OrderDirection.Buy); Assert.AreEqual(quantity, actual4); }
public void ProcessOrder_with_multiple_order_item_type() { //arrange var rmanager = new Mock <IRulesManager>(); var processor = new OrderProcessor(rmanager.Object); var order = Helpers.GetOrder(); var product = Helpers.GetProduct(); product.CurrentOrder = order; order.AddOrderItem(product); var book = Helpers.GetBook(); book.CurrentOrder = order; order.AddOrderItem(book); //act processor.ProcessOrder(order); //assert Assert.True(order.OrderStatus == Status.Processing); Assert.True(order.Items.All(t => t.ItemStatus == Status.Processing)); rmanager.Verify(rm => rm.Process(product), Times.Once()); rmanager.Verify(rm => rm.Process(book), Times.Once()); }
static void Main(string[] args) { var orderProcessor = new OrderProcessor(new ShippingCalculator()); var order = new Order { DatePlaced = DateTime.Now, TotalPrice = 100f }; orderProcessor.Process(order); //var circle = new Circle(); //circle.Draw(); //var rectangle = new Rectangle(); //rectangle.Draw(); //var shapes = new List<Shape1>(); //shapes.Add(new Circle()); //shapes.Add(new Rectangle()); //shapes.Add(new Triangle()); //var canvas = new Canvas(); //canvas.DrawShapes(shapes); //Text1 text1 = new Text1(); //Shape shape = text1; //text1.Width = 200; //text1.Width = 100; //Console.WriteLine(text1.Width); // var car = new Car("xyz"); //var customer = new Amazon.CustomerOne(); //var ratecal = new Amazon.RateCalculatore(); }
public ActionResult Index() { OrderProcessor orderProcessor = new OrderProcessor(); List <int> orderNumbers = orderProcessor.GetOrderNumbers(ManualEntryOrdersMock); return(View()); }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSInitialNotification started.", 20000); try { // send mail to customer orderProcessor.MailCustomer("BalloonShop order received.", GetMailBody()); // audit orderProcessor.CreateAudit( "Notification e-mail sent to customer.", 20002); // update order status orderProcessor.Order.UpdateStatus(1); // continue processing orderProcessor.ContinueNow = true; } catch { // mail sending failure throw new OrderProcessorException( "Unable to send e-mail to customer.", 0); } // audit processor.CreateAudit("PSInitialNotification finished.", 20001); }
public void Checking_out_successfully_should_create_a_confirmation_to_the_user() { var subject = new OrderProcessor(InventoryService.Object, PaymentService.Object, NotificationService.Object); subject.Checkout(Order); NotificationService.Verify(s => s.NotifyCustomerOrderCreated(Order.Cart), Times.Once); }
static void Main(string[] args) { string input, output; OrderProcessor orderProcessor = new OrderProcessor(); InitializeOrderProcessor(orderProcessor); for (;;) { Console.Write("Input: "); input = Console.ReadLine(); if (string.IsNullOrWhiteSpace(input)) { break; } output = null; try { output = orderProcessor.ProcessInput(input); } catch (InvalidMealException) { Console.WriteLine("Invalid meal. Valid options are: morning and night"); } if (output != null) { Console.Write("Output: "); Console.WriteLine(output); } Console.WriteLine(); } }
public ActionResult ViewOrdersFilter(string status) { //ViewBag.Message = "Order List"; var data = OrderProcessor.LoadOrder(status); List <Order> orders = new List <Order>(); foreach (var row in data) { orders.Add(new Order { orderId = row.orderId, partId = row.partId, projectName = row.projectName, lastMaterialDate = row.lastMaterialDate, shipDate = row.shipDate, quantity = row.quantity, status = row.status, priority = row.priority }); } return(View(orders)); }
public bool checkOrderExist(int orderId) { int result = 0; List <Order> existingOrderList = new List <Order>(); // gets the list of parts var data = OrderProcessor.LoadOrderIds(); foreach (var row in data) { existingOrderList.Add(new Order { orderId = row.orderId, }); } bool continueCond = false; for (int i = 0; i < existingOrderList.Count; i++) { if (orderId.Equals(existingOrderList[i].orderId)) { continueCond = true; break; } } return(continueCond); }
public void ProcessOrder_returns_exception_while_processing() { //arrange var rmanager = new Mock <IRulesManager>(); var processor = new OrderProcessor(rmanager.Object); rmanager.Setup(r => r.Process(It.IsAny <Product>())).Throws( new AggregateException("test-excptn") ); var order = Helpers.GetOrder(); var product = Helpers.GetProduct(); product.CurrentOrder = order; order.AddOrderItem(product); //act var rslt = processor.ProcessOrder(order); //assert Assert.True(order.OrderStatus == Status.Processing); Assert.True(order.Items.All(t => t.ItemStatus == Status.Processing)); Assert.False(rslt.IsAllSuccessful); Assert.True(rslt.Errors.Count == 1); }
protected void placeOrderButton_Click(object sender, EventArgs e) { // Store the total amount decimal amount = ShoppingCartAccess.GetTotalAmount(); // Get shipping ID or default to 0 int shippingId = 0; int.TryParse(shippingSelection.SelectedValue, out shippingId); // Get tax ID or default to "No tax" string shippingRegion = (HttpContext.Current.Profile as ProfileCommon).ShippingRegion; int taxId; switch (shippingRegion) { case "2": taxId = 1; break; default: taxId = 2; break; } // Create the order and store the order ID string orderId = ShoppingCartAccess.CreateCommerceLibOrder(shippingId, taxId); // Process order OrderProcessor processor = new OrderProcessor(orderId); processor.Process(); // Redirect to the conformation page Response.Redirect("OrderPlaced.aspx"); }
public void Should_set_order_state_to_inventory_reservation_failed() { var subject = new OrderProcessor(InventoryService.Object, PaymentService.Object, NotificationService.Object); subject.Checkout(Order); Assert.That(Order.State, Is.EqualTo(OrderState.InventoryReservationFailed)); }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSCheckStock started.", 20200); try { // send mail to supplier orderProcessor.MailSupplier("BalloonShop stock check.", GetMailBody()); // audit orderProcessor.CreateAudit( "Notification e-mail sent to supplier.", 20202); // update order status orderProcessor.Order.UpdateStatus(3); } catch { // mail sending failure throw new OrderProcessorException( "Unable to send e-mail to supplier.", 2); } // audit processor.CreateAudit("PSCheckStock finished.", 20201); }
public void Reserved_items_should_be_shipped_to_user() { var subject = new OrderProcessor(InventoryService.Object, PaymentService.Object, NotificationService.Object); subject.Checkout(Order); InventoryService.Verify(s => s.HandoutItemsToDelivery(Order.Cart.Items), Times.Once); }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSShipGoods started.", 20500); try { // send mail to supplier orderProcessor.MailSupplier("BalloonShop ship goods.", GetMailBody()); // audit orderProcessor.CreateAudit( "Ship goods e-mail sent to supplier.", 20502); // update order status orderProcessor.Order.UpdateStatus(6); } catch { // mail sending failure throw new OrderProcessorException( "Unable to send e-mail to supplier.", 5); } // audit processor.CreateAudit("PSShipGoods finished.", 20501); }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSTakePayment started.", 20400); try { // take customer funds // assume success for now // audit orderProcessor.CreateAudit( "Funds deducted from customer credit card account.", 20402); // update order status orderProcessor.Order.UpdateStatus(5); // continue processing orderProcessor.ContinueNow = true; } catch { // fund checking failure throw new OrderProcessorException( "Error occured while taking payment.", 4); } // audit processor.CreateAudit("PSTakePayment finished.", 20401); }
public void ProcessMessage(IOwinContext context, OrderProcessor processor) { JsonSerializer serializer = new JsonSerializer(); string requestBody; using (StreamReader sr = new StreamReader(context.Request.Body)) requestBody = sr.ReadToEnd(); RequestMessage reqMsg; using (JsonReader sr = new JsonTextReader(new StringReader(requestBody))) { try { reqMsg = serializer.Deserialize <RequestMessage>(sr); } catch (Exception ex) { Trace.WriteLine("Exception while trying to deserialize message: " + ex, "ParseError"); WriteJsonResponse(context, serializer, HttpStatusCode.BadRequest, requestBody); return; } } ResponseMessage response = processor.ProcessOrder(reqMsg); WriteJsonResponse(context, serializer, response.StatusCode, response.ResponseBody); }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSFinalNotification started.", 20700); try { // send mail to customer orderProcessor.MailCustomer("CdShop order dispatched.", GetMailBody()); // audit orderProcessor.CreateAudit( "Dispatch e-mail sent to customer.", 20702); // update order status orderProcessor.Order.UpdateStatus(8); } catch { // mail sending failure throw new OrderProcessorException( "Unable to send e-mail to customer.", 7); } // audit processor.CreateAudit("PSFinalNotification finished.", 20701); }
public OrderPostProcessorEmergency(OrderProcessor orderProcessor, OrderPostProcessorSequencerCloseThenOpen OPPSequencer) { this.emergencyLocks = new List <OrderPostProcessorEmergencyLock>(); this.interruptedEmergencyLockReasons = new List <Order>(); this.orderProcessor = orderProcessor; this.OPPsequencer = OPPSequencer; }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSFinalNotification started.", 20700); try { // send mail to customer orderProcessor.MailCustomer("BalloonShop order dispatched.", GetMailBody()); // audit orderProcessor.CreateAudit( "Dispatch e-mail sent to customer.", 20702); // update order status orderProcessor.Order.UpdateStatus(8); } catch { // mail sending failure throw new OrderProcessorException( "Unable to send e-mail to customer.", 7); } // audit processor.CreateAudit("PSFinalNotification finished.", 20701); }
public void Should_reserve_items_in_the_inventory() { var subject = new OrderProcessor(InventoryService.Object, PaymentService.Object, NotificationService.Object); subject.Checkout(Order); InventoryService.Verify(s => s.ReserveItems(Order.Cart.Items), Times.Once); }
public ActionResult ShowOrderAdmin(int orderId) { if (IsActiveSession()) { //Getting header data var headerData = OrderProcessor.GetOrderById(orderId); OrderModel orderHeader = new OrderModel { Id = headerData.Id, Name = headerData.Name, Address = headerData.Address, City = headerData.City, State = headerData.State, Zip = headerData.Zip, CompanyName = headerData.CompanyName, DateCreated = headerData.DateCreated }; //Getting details data var detailsData = OrderProcessor.GetOrderProducts(orderId); List <OrderProductsModel> orderDetails = new List <OrderProductsModel>(); float total = 0.0f; int index = 0; foreach (var row in detailsData) { index++; orderDetails.Add(new OrderProductsModel { Id = row.Id, ProductCode = index.ToString(), ProductId = row.ProductId, ProductDescription = row.ProductDescription, ProductPrice = row.ProductPrice, ProductQty = row.ProductQty, ProductImagePath = row.ProductImagePath, OrderId = row.OrderId }); total = total + (row.ProductQty * row.ProductPrice); } CompleteOrderModel completeOrderModel = new CompleteOrderModel { OrderHeader = orderHeader, OrderDetails = orderDetails }; StoreViewModel storeViewModel = new StoreViewModel { StoreProducts = null, CartProducts = new List <CartProductsModel>() }; ViewBag.total = total; ViewBag.taxTotal = total * 0.25; ViewBag.grandTotal = total - (total * 0.25); return(View(completeOrderModel)); } return(RedirectToAction("Login", "Login", null)); }
public void SetUp() { _orderBatcher = new Mock<IOrderBatcher>(); _orderSender = new Mock<IOrderSender>(); _orderRecorder = new Mock<IOrderRecorder>(); _orderProcessor = new OrderProcessor(_orderBatcher.Object, _orderSender.Object, _orderRecorder.Object); }
public OrderPuller(OrderPullerOptionManager optionManager, OrderProcessor processor, FastProvider provider, FastAdapter adapter, EntityRepository entityRepository, ConnectionRepository connectionRepository) : base(optionManager, processor, provider, adapter, entityRepository, connectionRepository) { }
public void Processor(OrderProcessor processor) { processor.CreateAudit("PsTakePayment started.", 20400); processor.CreateAudit("'Funds deducted from customer credit card account.", 20402); processor.UpdateOrderStatus(5); processor.ContinueNow = true; processor.CreateAudit("PsTakePayment finished.", 20401); }
// continue order processing protected void processOrderButton_Click(object sender, EventArgs e) { string orderId = Session["AdminOrderID"].ToString(); OrderProcessor processor = new OrderProcessor(orderId); processor.Process(); PopulateControls(); }
public void Initialize(string rootPath, string subfolder, IStatusReporter statusReporter, RepositoryCustomMarketInfo marketInfoRepository, OrderProcessor orderProcessor) { base.Initialize(rootPath, subfolder, statusReporter, this.dataSourceDeserializedInitializePriorToAdding); this.MarketInfoRepository = marketInfoRepository; this.OrderProcessor = orderProcessor; }
public void Process_OrderIsAlreadyShipped_ThrowsException() { var orderProcessor = new OrderProcessor(new FakeShippingCalculator()); var order = new Order { Shipment = new Shipment() }; orderProcessor.Process(order); }
public override void Context() { interceptedOrderProcessor = new OrderProcessor(); MockPart.Setup(p => p.GetExportedValue(OrderProcessorExportDefinition)).Returns( interceptedOrderProcessor); InterceptedPart = MockPart.Object; MockInterceptor.Setup(p => p.Intercept(interceptedOrderProcessor)).Returns(interceptingOrderProcessor); InterceptingPart = new InterceptingComposablePart(InterceptedPart, MockInterceptor.Object); retrievedOrderProcessor = InterceptingPart.GetExportedValue(OrderProcessorExportDefinition); }
public void Process_OrderIsNotShipping_ShouldSetShipmentPropertyOfOrderToTrue() { var orderProcessor = new OrderProcessor(new FakeShippingCalculator()); var order = new Order(); orderProcessor.Process(order); Assert.IsTrue(order.IsShipped); Assert.AreEqual(1, order.Shipment.Cost); Assert.AreEqual(DateTime.Today.AddDays(1), order.Shipment.ShippingDate); }
/// <summary> /// Initializes a new instance of the <see cref="VisitorOrderProcessor" /> class. /// </summary> /// <param name="innerProcessor">The inner processor.</param> /// <param name="processingStrategy">The processing strategy.</param> /// <param name="repository">The repository.</param> /// <param name="orderSecurity">The order security.</param> public VisitorOrderProcessor(OrderProcessor innerProcessor, ProcessingStrategy processingStrategy, Repository<Order> repository, VisitorOrderSecurity orderSecurity) { Assert.IsNotNull(innerProcessor, "Unable to cancel the order. Inner Order Processor cannot be null."); Assert.IsNotNull(processingStrategy, "Unable to cancel the order. Order Processing Strategy cannot be null."); Assert.IsNotNull(repository, "Unable to cancel the order. Order Repository cannot be null."); Assert.IsNotNull(orderSecurity, Texts.UnableToSaveTheOrdersOrderSecurityCannotBeNull); this.innerProcessor = innerProcessor; this.processingStrategy = processingStrategy; this.repository = repository; this.orderSecurity = orderSecurity; }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSStockOK started.", 20300); // the method is called when the supplier confirms that stock is // available, so we don't have to do anything here except audit orderProcessor.CreateAudit("Stock confirmed by supplier.", 20302); // update order status orderProcessor.Order.UpdateStatus(4); // continue processing orderProcessor.ContinueNow = true; // audit processor.CreateAudit("PSStockOK finished.", 20301); }
private static void InitializeOrderProcessor(OrderProcessor orderProcessor) { DishList morningDishList = new DishList(); DishList nightDishList = new DishList(); morningDishList.Add(new Dish { Code = 1, Description = "eggs" }); morningDishList.Add(new Dish { Code = 2, Description = "toast" }); morningDishList.Add(new Dish { Code = 3, Description = "coffee", AllowMultiple = true }); nightDishList.Add(new Dish { Code = 1, Description = "steak" }); nightDishList.Add(new Dish { Code = 2, Description = "potato", AllowMultiple = true }); nightDishList.Add(new Dish { Code = 3, Description = "wine" }); nightDishList.Add(new Dish { Code = 4, Description = "cake" }); orderProcessor.DishLists.Add("morning", morningDishList); orderProcessor.DishLists.Add("night", nightDishList); }
public void Process(OrderProcessor processor) { // set processor reference orderProcessor = processor; // audit orderProcessor.CreateAudit("PSShipOK started.", 20600); // set order shipment date orderProcessor.Order.SetDateShipped(); // audit orderProcessor.CreateAudit("Order dispatched by supplier.", 20602); // update order status orderProcessor.Order.UpdateStatus(7); // continue processing orderProcessor.ContinueNow = true; // audit processor.CreateAudit("PSShipOK finished.", 20601); }
public OrderProcessorTest() { orderProcessor = new OrderProcessor(); DishList morningDishList = new DishList(); DishList nightDishList = new DishList(); morningDishList.Add(new Dish { Code = 1, Description = "eggs" }); morningDishList.Add(new Dish { Code = 2, Description = "toast" }); morningDishList.Add(new Dish { Code = 3, Description = "coffee", AllowMultiple = true }); nightDishList.Add(new Dish { Code = 1, Description = "steak" }); nightDishList.Add(new Dish { Code = 2, Description = "potato", AllowMultiple = true }); nightDishList.Add(new Dish { Code = 3, Description = "wine" }); nightDishList.Add(new Dish { Code = 4, Description = "cake" }); orderProcessor.DishLists.Add("morning", morningDishList); orderProcessor.DishLists.Add("night", nightDishList); }
public void ComputeMarginProperlyShortCoverZeroLong() { const decimal leverage = 2m; const int amount = 1000; const int quantity = (int)(amount * leverage); var securities = new SecurityManager(TimeKeeper); var transactions = new SecurityTransactionManager(securities); var orderProcessor = new OrderProcessor(); transactions.SetOrderProcessor(orderProcessor); var portfolio = new SecurityPortfolioManager(securities, transactions); portfolio.CashBook["USD"].SetAmount(amount); var config = CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL); securities.Add(new Security(SecurityExchangeHours, config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency))); var security = securities[Symbols.AAPL]; security.SetLeverage(leverage); var time = DateTime.Now; const decimal sellPrice = 1m; security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, sellPrice, sellPrice, sellPrice, sellPrice, 1)); var order = new MarketOrder(Symbols.AAPL, -quantity, time) { Price = sellPrice }; var fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = sellPrice, FillQuantity = -quantity }; orderProcessor.AddOrder(order); var request = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, order.Quantity, 0, 0, order.Time, null); request.SetOrderId(0); orderProcessor.AddTicket(new OrderTicket(null, request)); portfolio.ProcessFill(fill); // we shouldn't be able to place a new short order var newOrder = new MarketOrder(Symbols.AAPL, -1, time.AddSeconds(1)) { Price = sellPrice }; var sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder); Assert.IsFalse(sufficientCapital); // we should be able to place cover to zero newOrder = new MarketOrder(Symbols.AAPL, quantity, time.AddSeconds(1)) { Price = sellPrice }; sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder); Assert.IsTrue(sufficientCapital); // now the stock doubles, so we should have negative margin remaining time = time.AddDays(1); const decimal highPrice = sellPrice * 2; security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, highPrice, highPrice, highPrice, highPrice, 1)); // we still shouldn be able to place cover to zero newOrder = new MarketOrder(Symbols.AAPL, quantity, time.AddSeconds(1)) { Price = highPrice }; sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder); Assert.IsTrue(sufficientCapital); // we shouldn't be able to place cover to long newOrder = new MarketOrder(Symbols.AAPL, quantity + 1, time.AddSeconds(1)) { Price = highPrice }; sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder); Assert.IsFalse(sufficientCapital); }
public void MarginComputesProperlyWithMultipleSecurities() { var securities = new SecurityManager(TimeKeeper); var transactions = new SecurityTransactionManager(securities); var orderProcessor = new OrderProcessor(); transactions.SetOrderProcessor(orderProcessor); var portfolio = new SecurityPortfolioManager(securities, transactions); portfolio.CashBook["USD"].SetAmount(1000); portfolio.CashBook.Add("EUR", 1000, 1.1m); portfolio.CashBook.Add("GBP", -1000, 2.0m); var eurCash = portfolio.CashBook["EUR"]; var gbpCash = portfolio.CashBook["GBP"]; var usdCash = portfolio.CashBook["USD"]; var time = DateTime.Now; var config1 = CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL); securities.Add(new Security(SecurityExchangeHours, config1, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency))); securities[Symbols.AAPL].SetLeverage(2m); securities[Symbols.AAPL].Holdings.SetHoldings(100, 100); securities[Symbols.AAPL].SetMarketPrice(new TradeBar{Time = time, Value = 100}); //Console.WriteLine("AAPL TMU: " + securities[Symbols.AAPL].MarginModel.GetMaintenanceMargin(securities[Symbols.AAPL])); //Console.WriteLine("AAPL Value: " + securities[Symbols.AAPL].Holdings.HoldingsValue); //Console.WriteLine(); var config2 = CreateTradeBarDataConfig(SecurityType.Forex, Symbols.EURUSD); securities.Add(new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, usdCash, config2, SymbolProperties.GetDefault(CashBook.AccountCurrency))); securities[Symbols.EURUSD].SetLeverage(100m); securities[Symbols.EURUSD].Holdings.SetHoldings(1.1m, 1000); securities[Symbols.EURUSD].SetMarketPrice(new TradeBar { Time = time, Value = 1.1m }); //Console.WriteLine("EURUSD TMU: " + securities[Symbols.EURUSD].MarginModel.GetMaintenanceMargin(securities[Symbols.EURUSD])); //Console.WriteLine("EURUSD Value: " + securities[Symbols.EURUSD].Holdings.HoldingsValue); //Console.WriteLine(); var config3 = CreateTradeBarDataConfig(SecurityType.Forex, Symbols.EURGBP); securities.Add(new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, gbpCash, config3, SymbolProperties.GetDefault(gbpCash.Symbol))); securities[Symbols.EURGBP].SetLeverage(100m); securities[Symbols.EURGBP].Holdings.SetHoldings(1m, 1000); securities[Symbols.EURGBP].SetMarketPrice(new TradeBar { Time = time, Value = 1m }); //Console.WriteLine("EURGBP TMU: " + securities[Symbols.EURGBP].MarginModel.GetMaintenanceMargin(securities[Symbols.EURGBP])); //Console.WriteLine("EURGBP Value: " + securities[Symbols.EURGBP].Holdings.HoldingsValue); //Console.WriteLine(); //Console.WriteLine(portfolio.CashBook["USD"]); //Console.WriteLine(portfolio.CashBook["EUR"]); //Console.WriteLine(portfolio.CashBook["GBP"]); //Console.WriteLine("CashBook: " + portfolio.CashBook.TotalValueInAccountCurrency); //Console.WriteLine(); //Console.WriteLine("Total Margin Used: " + portfolio.TotalMarginUsed); //Console.WriteLine("Total Free Margin: " + portfolio.MarginRemaining); //Console.WriteLine("Total Portfolio Value: " + portfolio.TotalPortfolioValue); var acceptedOrder = new MarketOrder(Symbols.AAPL, 101, DateTime.Now) { Price = 100 }; orderProcessor.AddOrder(acceptedOrder); var request = new SubmitOrderRequest(OrderType.Market, acceptedOrder.SecurityType, acceptedOrder.Symbol, acceptedOrder.Quantity, 0, 0, acceptedOrder.Time, null); request.SetOrderId(0); orderProcessor.AddTicket(new OrderTicket(null, request)); var sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, acceptedOrder); Assert.IsTrue(sufficientCapital); var rejectedOrder = new MarketOrder(Symbols.AAPL, 102, DateTime.Now) { Price = 100 }; sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, rejectedOrder); Assert.IsFalse(sufficientCapital); }
public void ComputeMarginProperlyAsSecurityPriceFluctuates() { const decimal leverage = 1m; const int quantity = (int) (1000*leverage); var securities = new SecurityManager(TimeKeeper); var transactions = new SecurityTransactionManager(securities); var orderProcessor = new OrderProcessor(); transactions.SetOrderProcessor(orderProcessor); var portfolio = new SecurityPortfolioManager(securities, transactions); portfolio.CashBook["USD"].SetAmount(quantity); var config = CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL); securities.Add(new Security(SecurityExchangeHours, config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency))); var security = securities[Symbols.AAPL]; security.SetLeverage(leverage); var time = DateTime.Now; const decimal buyPrice = 1m; security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, buyPrice, buyPrice, buyPrice, buyPrice, 1)); var order = new MarketOrder(Symbols.AAPL, quantity, time) {Price = buyPrice}; var fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity }; orderProcessor.AddOrder(order); var request = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, order.Quantity, 0, 0, order.Time, null); request.SetOrderId(0); orderProcessor.AddTicket(new OrderTicket(null, request)); Assert.AreEqual(portfolio.CashBook["USD"].Amount, fill.FillPrice*fill.FillQuantity); portfolio.ProcessFill(fill); Assert.AreEqual(0, portfolio.MarginRemaining); Assert.AreEqual(quantity, portfolio.TotalMarginUsed); Assert.AreEqual(quantity, portfolio.TotalPortfolioValue); // we shouldn't be able to place a trader var newOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) {Price = buyPrice}; bool sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder); Assert.IsFalse(sufficientCapital); // now the stock doubles, so we should have margin remaining time = time.AddDays(1); const decimal highPrice = buyPrice * 2; security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, highPrice, highPrice, highPrice, highPrice, 1)); Assert.AreEqual(quantity, portfolio.MarginRemaining); Assert.AreEqual(quantity, portfolio.TotalMarginUsed); Assert.AreEqual(quantity * 2, portfolio.TotalPortfolioValue); // we shouldn't be able to place a trader var anotherOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) { Price = highPrice }; sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, anotherOrder); Assert.IsTrue(sufficientCapital); // now the stock plummets, so we should have negative margin remaining time = time.AddDays(1); const decimal lowPrice = buyPrice/2; security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, lowPrice, lowPrice, lowPrice, lowPrice, 1)); Assert.AreEqual(-quantity/2m, portfolio.MarginRemaining); Assert.AreEqual(quantity, portfolio.TotalMarginUsed); Assert.AreEqual(quantity/2m, portfolio.TotalPortfolioValue); // this would not cause a margin call due to leverage = 1 bool issueMarginCallWarning; var marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning); Assert.AreEqual(0, marginCallOrders.Count); // now change the leverage and buy more and we'll get a margin call security.SetLeverage(leverage * 2); order = new MarketOrder(Symbols.AAPL, quantity, time) { Price = buyPrice }; fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity }; portfolio.ProcessFill(fill); Assert.AreEqual(0, portfolio.TotalPortfolioValue); marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning); Assert.AreNotEqual(0, marginCallOrders.Count); Assert.AreEqual(-security.Holdings.Quantity, marginCallOrders[0].Quantity); // we bought twice Assert.GreaterOrEqual(-portfolio.MarginRemaining, security.Price * marginCallOrders[0].Quantity); }
public void GenerateMarginCallOrderTests() { const int quantity = 1000; const decimal leverage = 1m; var orderProcessor = new OrderProcessor(); var portfolio = GetPortfolio(orderProcessor, quantity); var security = GetSecurity(Symbols.AAPL); security.MarginModel = new NoMarginCallMarginModel(leverage); portfolio.Securities.Add(security); var time = DateTime.Now; const decimal buyPrice = 1m; security.SetMarketPrice(new Tick(time, Symbols.AAPL, buyPrice, buyPrice)); var order = new MarketOrder(Symbols.AAPL, quantity, time) {Price = buyPrice}; var fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity }; orderProcessor.AddOrder(order); var request = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, order.Quantity, 0, 0, order.Time, null); request.SetOrderId(0); orderProcessor.AddTicket(new OrderTicket(null, request)); Assert.AreEqual(portfolio.Cash, fill.FillPrice*fill.FillQuantity); portfolio.ProcessFill(fill); Assert.AreEqual(0, portfolio.MarginRemaining); Assert.AreEqual(quantity, portfolio.TotalMarginUsed); Assert.AreEqual(quantity, portfolio.TotalPortfolioValue); // we shouldn't be able to place a trader var newOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) {Price = buyPrice}; bool sufficientCapital = portfolio.Transactions.GetSufficientCapitalForOrder(portfolio, newOrder); Assert.IsFalse(sufficientCapital); // now the stock doubles, so we should have margin remaining time = time.AddDays(1); const decimal highPrice = buyPrice * 2; security.SetMarketPrice(new Tick(time, Symbols.AAPL, highPrice, highPrice)); Assert.AreEqual(quantity, portfolio.MarginRemaining); Assert.AreEqual(quantity, portfolio.TotalMarginUsed); Assert.AreEqual(quantity * 2, portfolio.TotalPortfolioValue); // we shouldn't be able to place a trader var anotherOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) { Price = highPrice }; sufficientCapital = portfolio.Transactions.GetSufficientCapitalForOrder(portfolio, anotherOrder); Assert.IsTrue(sufficientCapital); // now the stock plummets, so we should have negative margin remaining time = time.AddDays(1); const decimal lowPrice = buyPrice/2; security.SetMarketPrice(new Tick(time, Symbols.AAPL, lowPrice, lowPrice)); Assert.AreEqual(-quantity/2m, portfolio.MarginRemaining); Assert.AreEqual(quantity, portfolio.TotalMarginUsed); Assert.AreEqual(quantity/2m, portfolio.TotalPortfolioValue); // this would not cause a margin call due to leverage = 1 bool issueMarginCallWarning; var marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning); Assert.IsFalse(issueMarginCallWarning); Assert.AreEqual(0, marginCallOrders.Count); // now change the leverage to test margin call warning and margin call logic security.SetLeverage(leverage * 2); // Stock price increase by minimum variation const decimal newPrice = lowPrice + 0.01m; security.SetMarketPrice(new Tick(time, Symbols.AAPL, newPrice, newPrice)); // this would not cause a margin call, only a margin call warning marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning); Assert.IsTrue(issueMarginCallWarning); Assert.AreEqual(0, marginCallOrders.Count); // Price drops again to previous low, margin call orders will be issued security.SetMarketPrice(new Tick(time, Symbols.AAPL, lowPrice, lowPrice)); order = new MarketOrder(Symbols.AAPL, quantity, time) { Price = buyPrice }; fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity }; portfolio.ProcessFill(fill); Assert.AreEqual(0, portfolio.TotalPortfolioValue); // Even with TotalPortfolioValue == 0, do not issue warning or orders marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning); Assert.IsFalse(issueMarginCallWarning); Assert.AreEqual(0, marginCallOrders.Count); }
public void GetMarginRemainingTests() { const int quantity = 1000; const decimal leverage = 2; var orderProcessor = new OrderProcessor(); var portfolio = GetPortfolio(orderProcessor, quantity); var security = GetSecurity(Symbols.AAPL); portfolio.Securities.Add(security); security.MarginModel = new NoMarginCallMarginModel(leverage); security.Holdings.SetHoldings(1m, quantity); var actual1 = security.MarginModel.GetMarginRemaining(portfolio, security, OrderDirection.Buy); Assert.AreEqual(quantity / leverage, actual1); var actual2 = security.MarginModel.GetMarginRemaining(portfolio, security, OrderDirection.Sell); Assert.AreEqual(quantity, actual2); security.Holdings.SetHoldings(1m, -quantity); var actual3 = security.MarginModel.GetMarginRemaining(portfolio, security, OrderDirection.Sell); Assert.AreEqual(quantity / leverage, actual3); var actual4 = security.MarginModel.GetMarginRemaining(portfolio, security, OrderDirection.Buy); Assert.AreEqual(quantity, actual4); }
/// <summary> /// A hook to do any appropriate work immediately prior to the Process() method. /// </summary> protected override void PreProcessOrder() { base.PreProcessOrder(); _orderProcessor = CreateOrderProcessor(); }
protected ScriptExecutor(ChartShadow chartShadow, Strategy strategy, OrderProcessor orderProcessor, IStatusReporter statusReporter) : this() { this.Initialize(chartShadow, strategy, orderProcessor, statusReporter); }
public void Initialize(ChartShadow chartShadow, Strategy strategy, OrderProcessor orderProcessor, IStatusReporter statusReporter) { string msg = " at this time, FOR SURE this.Bars==null, strategy.Script?=null"; this.ChartShadow = chartShadow; this.Strategy = strategy; this.OrderProcessor = orderProcessor; this.StatusReporter = statusReporter; if (this.Strategy != null) { if (this.Bars != null) { this.Strategy.ScriptContextCurrent.Symbol = this.Bars.Symbol; this.Strategy.ScriptContextCurrent.DataSourceName = this.DataSource.Name; } if (this.Strategy.Script == null) { msg = "I will be compiling this.Strategy.Script when in ChartFormsManager.StrategyCompileActivatePopulateSliders()"; //} else if (this.Bars == null) { // msg = "InitializeStrategyAfterDeserialization will Script.Initialize(this) later with bars"; } else { this.Strategy.Script.Initialize(this); } } this.ExecutionDataSnapshot.Initialize(); // Executor.Bars are NULL in ScriptExecutor.ctor() and NOT NULL in SetBars //this.Performance.Initialize(); this.MarketSimStreaming.Initialize(); }
static void Main(string[] args) { var orderProcessor = new OrderProcessor(new ShippingCalculator()); var order = new Order { DatePlaced = DateTime.Now, TotalPrice = 100f }; orderProcessor.Process(order); }
public void TestProcessOrder() { var printer = CreatePrinter(); var sut = new OrderProcessor(a, b); var actual = sut.Process(c, d); printer.Assert.AreEqual("1", printer.PrintObject(actual.OrderNumber)); printer.Assert.AreEqual("X-mas present", printer.PrintObject(actual.OrderDescription)); printer.Assert.AreEqual("43", printer.PrintObject(actual.Total)); }
public void TestProcessOrderImproved() { var assert = CreatePrinter().Assert; var sut = new OrderProcessor(a, b); var actual = sut.Process(c, d); assert.PrintEquals("1", actual.OrderNumber); assert.PrintEquals("X-mas present", actual.OrderDescription); assert.PrintEquals("43", actual.Total); }