コード例 #1
0
ファイル: Program.cs プロジェクト: lukeamaral/GFTPracticum
        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();
            }
        }
コード例 #2
0
ファイル: PSShipGoods.cs プロジェクト: altras/fmi_projects
 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);
 }
コード例 #3
0
ファイル: PSCheckStock.cs プロジェクト: altras/fmi_projects
        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);
        }
コード例 #4
0
        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);
        }
コード例 #5
0
 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);
 }
コード例 #6
0
ファイル: PSTakePayment.cs プロジェクト: altras/fmi_projects
 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);
 }
コード例 #7
0
ファイル: OrderProcessorTests.cs プロジェクト: odw1/Blog
        public void SetUp()
        {
            _orderBatcher = new Mock<IOrderBatcher>();
            _orderSender = new Mock<IOrderSender>();
            _orderRecorder = new Mock<IOrderRecorder>();

            _orderProcessor = new OrderProcessor(_orderBatcher.Object, _orderSender.Object, _orderRecorder.Object);
        }
コード例 #8
0
 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);
 }
コード例 #9
0
        public void Process_OrderIsAlreadyShipped_ThrowsException()
        {
            var orderProcessor = new OrderProcessor(new FakeShippingCalculator());
            var order = new Order
            {
                Shipment = new Shipment()
            };

            orderProcessor.Process(order);
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        /// <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;
        }
コード例 #12
0
ファイル: PSShipOK.cs プロジェクト: altras/fmi_projects
 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);
 }
コード例 #13
0
ファイル: Program.cs プロジェクト: lukeamaral/GFTPracticum
        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);
        }
コード例 #14
0
ファイル: PSStockOK.cs プロジェクト: altras/fmi_projects
 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);
 }
コード例 #15
0
        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);
        }
コード例 #16
0
        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);
        }
コード例 #17
0
        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);
        }
コード例 #18
0
        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);
        }
コード例 #19
0
        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));
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: jimxshaw/samples-csharp
 static void Main(string[] args)
 {
     var orderProcessor = new OrderProcessor(new ShippingCalculator());
     var order = new Order { DatePlaced = DateTime.Now, TotalPrice = 100f };
     orderProcessor.Process(order);
 }
コード例 #21
0
		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();
		}
コード例 #22
0
        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);
        }
コード例 #23
0
        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);
        }
コード例 #24
0
        /// <summary>
        /// A hook to do any appropriate work immediately prior to the Process() method.
        /// </summary>
        protected override void PreProcessOrder()
        {
            base.PreProcessOrder();

            _orderProcessor = CreateOrderProcessor();
        }
コード例 #25
0
        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);
        }
コード例 #26
0
		protected ScriptExecutor(ChartShadow chartShadow, Strategy strategy, 
		                         OrderProcessor orderProcessor, IStatusReporter statusReporter) : this() {
			this.Initialize(chartShadow, strategy, orderProcessor, statusReporter);
		}