public void Initialize() { _algorithm = new QCAlgorithm(); _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm)); _portfolio = _algorithm.Portfolio; _portfolio.CashBook.Add("EUR", 0, 1.20m); _portfolio.CashBook.Add("BTC", 0, 15000m); _portfolio.CashBook.Add("ETH", 0, 1000m); _algorithm.SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash); _transactionHandler = new BacktestingTransactionHandler(); _brokerage = new BacktestingBrokerage(_algorithm); _transactionHandler.Initialize(_algorithm, _brokerage, new TestResultHandler()); _algorithm.Transactions.SetOrderProcessor(_transactionHandler); var tz = TimeZones.NewYork; _btcusd = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook[Currencies.USD], new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCUSD, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("BTCUSD", Currencies.USD, 1, 0.01m, 0.00000001m), ErrorCurrencyConverter.Instance ); _ethusd = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook[Currencies.USD], new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHUSD, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("ETHUSD", Currencies.USD, 1, 0.01m, 0.00000001m), ErrorCurrencyConverter.Instance ); _btceur = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook["EUR"], new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCEUR, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("BTCEUR", "EUR", 1, 0.01m, 0.00000001m), ErrorCurrencyConverter.Instance ); _ethbtc = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook["BTC"], new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHBTC, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("ETHBTC", "BTC", 1, 0.00001m, 0.00000001m), ErrorCurrencyConverter.Instance ); _buyingPowerModel = new CashBuyingPowerModel(); _timeKeeper = new LocalTimeKeeper(new DateTime(2019, 4, 22), DateTimeZone.Utc); _btcusd.SetLocalTimeKeeper(_timeKeeper); _ethusd.SetLocalTimeKeeper(_timeKeeper); _btceur.SetLocalTimeKeeper(_timeKeeper); _ethbtc.SetLocalTimeKeeper(_timeKeeper); }
/// <summary> /// Setup the algorithm cash, dates and portfolio as desired. /// </summary> /// <param name="algorithm">Existing algorithm instance</param> /// <param name="brokerage">New brokerage instance</param> /// <param name="baseJob">Backtesting job</param> /// <param name="resultHandler">The configured result handler</param> /// <param name="transactionHandler">The configuration transaction handler</param> /// <returns>Boolean true on successfully setting up the console.</returns> public bool Setup(IAlgorithm algorithm, out IBrokerage brokerage, AlgorithmNodePacket baseJob, IResultHandler resultHandler, ITransactionHandler transactionHandler) { var initializeComplete = false; try { //Set common variables for console programs: if (baseJob.Type == PacketType.BacktestNode) { var backtestJob = baseJob as BacktestNodePacket; //Set the limits on the algorithm assets (for local no limits) algorithm.SetAssetLimits(999, 999, 999); algorithm.SetMaximumOrders(int.MaxValue); //Setup Base Algorithm: algorithm.Initialize(); //Add currency data feeds that weren't explicity added in Initialize algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(algorithm.Securities, algorithm.SubscriptionManager, SecurityExchangeHoursProvider.FromDataFolder()); //Construct the backtest job packet: backtestJob.PeriodStart = algorithm.StartDate; backtestJob.PeriodFinish = algorithm.EndDate; backtestJob.BacktestId = "LOCALHOST"; backtestJob.UserId = 1001; backtestJob.Type = PacketType.BacktestNode; //Backtest Specific Parameters: StartingDate = backtestJob.PeriodStart; StartingPortfolioValue = algorithm.Portfolio.Cash; } else { throw new Exception("The ConsoleSetupHandler is for backtests only. Use the BrokerageSetupHandler."); } } catch (Exception err) { Log.Error("ConsoleSetupHandler().Setup(): " + err.Message); Errors.Add("Failed to initialize algorithm: Initialize(): " + err.Message); } if (Errors.Count == 0) { initializeComplete = true; } // we need to do this after algorithm initialization brokerage = new BacktestingBrokerage(algorithm); // set the transaction models base on the requested brokerage properties SetupHandler.UpdateTransactionModels(algorithm, algorithm.BrokerageModel); algorithm.Transactions.SetOrderProcessor(transactionHandler); return(initializeComplete); }
/// <summary> /// Creates a new BacktestingTransactionHandler using the BacktestingBrokerage /// </summary> /// <param name="algorithm">The algorithm instance</param> /// <param name="brokerage">The BacktestingBrokerage</param> /// <param name="resultHandler"></param> public override void Initialize(IAlgorithm algorithm, IBrokerage brokerage, IResultHandler resultHandler) { if (!(brokerage is BacktestingBrokerage)) { throw new ArgumentException("Brokerage must be of type BacktestingBrokerage for use wth the BacktestingTransactionHandler"); } _brokerage = (BacktestingBrokerage)brokerage; base.Initialize(algorithm, brokerage, resultHandler); }
/// <summary> /// Creates a new BacktestingTransactionHandler using the BacktestingBrokerage /// </summary> /// <param name="algorithm">The algorithm instance</param> /// <param name="brokerage">The BacktestingBrokerage</param> /// <param name="resultHandler"></param> public override void Initialize(IAlgorithm algorithm, IBrokerage brokerage, IResultHandler resultHandler) { if (!(brokerage is BacktestingBrokerage)) { throw new ArgumentException("Brokerage must be of type BacktestingBrokerage for use wth the BacktestingTransactionHandler"); } _brokerage = (BacktestingBrokerage)brokerage; base.Initialize(algorithm, brokerage, resultHandler); // non blocking implementation _orderRequestQueue = new BusyCollection <OrderRequest>(); }
public void Initialize() { _algorithm = new QCAlgorithm(); _portfolio = _algorithm.Portfolio; _portfolio.CashBook.Add("EUR", 0, 1.20m); _portfolio.CashBook.Add("BTC", 0, 15000m); _portfolio.CashBook.Add("ETH", 0, 1000m); _algorithm.SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash); _transactionHandler = new BacktestingTransactionHandler(); _brokerage = new BacktestingBrokerage(_algorithm); _transactionHandler.Initialize(_algorithm, _brokerage, new TestResultHandler()); new Thread(_transactionHandler.Run) { IsBackground = true }.Start(); _algorithm.Transactions.SetOrderProcessor(_transactionHandler); var tz = TimeZones.NewYork; _btcusd = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook[CashBook.AccountCurrency], new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCUSD, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("BTCUSD", "USD", 1, 0.01m, 0.00000001m)); _ethusd = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook[CashBook.AccountCurrency], new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHUSD, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("ETHUSD", "USD", 1, 0.01m, 0.00000001m)); _btceur = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook["EUR"], new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCEUR, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("BTCEUR", "EUR", 1, 0.01m, 0.00000001m)); _ethbtc = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook["BTC"], new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHBTC, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("ETHBTC", "BTC", 1, 0.00001m, 0.00000001m)); _buyingPowerModel = new CashBuyingPowerModel(); }
public void UpdateOrderRequestShouldFailForFilledOrder() { // Initializes the transaction handler var transactionHandler = new BrokerageTransactionHandler(); var broker = new BacktestingBrokerage(_algorithm); transactionHandler.Initialize(_algorithm, broker, new BacktestingResultHandler()); // Creates a limit order var security = _algorithm.Securities[Ticker]; var price = 1.12m; security.SetMarketPrice(new Tick(DateTime.Now, security.Symbol, price, price, price)); var orderRequest = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, 1000, 0, 1.11m, DateTime.Now, ""); // Mock the the order processor var orderProcessorMock = new Mock <IOrderProcessor>(); orderProcessorMock.Setup(m => m.GetOrderTicket(It.IsAny <int>())).Returns(new OrderTicket(_algorithm.Transactions, orderRequest)); _algorithm.Transactions.SetOrderProcessor(orderProcessorMock.Object); // Submit and process a limit order var orderTicket = transactionHandler.Process(orderRequest); transactionHandler.HandleOrderRequest(orderRequest); Assert.IsTrue(orderRequest.Response.IsProcessed); Assert.IsTrue(orderRequest.Response.IsSuccess); Assert.AreEqual(orderTicket.Status, OrderStatus.Submitted); broker.Scan(); Assert.AreEqual(orderTicket.Status, OrderStatus.Filled); var updateRequest = new UpdateOrderRequest(DateTime.Now, orderTicket.OrderId, new UpdateOrderFields()); transactionHandler.Process(updateRequest); Assert.AreEqual(updateRequest.Status, OrderRequestStatus.Error); Assert.IsTrue(updateRequest.Response.IsError); Assert.AreEqual(updateRequest.Response.ErrorCode, OrderResponseErrorCode.InvalidOrderStatus); Assert.AreEqual(orderTicket.Status, OrderStatus.Filled); Assert.AreEqual(_algorithm.OrderEvents.Count, 2); Assert.AreEqual(_algorithm.OrderEvents.Count(orderEvent => orderEvent.Status == OrderStatus.Submitted), 1); Assert.AreEqual(_algorithm.OrderEvents.Count(orderEvent => orderEvent.Status == OrderStatus.Filled), 1); }
public void OptionExerciseWhenFullyInvested() { var algorithm = new AlgorithmStub(); algorithm.SetFinishedWarmingUp(); var backtestingTransactionHandler = new BacktestingTransactionHandler(); var brokerage = new BacktestingBrokerage(algorithm); algorithm.Transactions.SetOrderProcessor(backtestingTransactionHandler); backtestingTransactionHandler.Initialize(algorithm, brokerage, new TestResultHandler()); const decimal price = 2600m; var time = new DateTime(2020, 10, 14); var expDate = new DateTime(2021, 3, 19); // For this symbol we dont have any history, but only one date and margins line var ticker = QuantConnect.Securities.Futures.Indices.SP500EMini; var future = Symbol.CreateFuture(ticker, Market.CME, expDate); var symbol = Symbol.CreateOption(future, Market.CME, OptionStyle.American, OptionRight.Call, 2550m, new DateTime(2021, 3, 19)); var optionSecurity = algorithm.AddOptionContract(symbol); optionSecurity.Underlying = algorithm.AddFutureContract(future); optionSecurity.Underlying.SetMarketPrice(new Tick { Value = price, Time = time }); optionSecurity.SetMarketPrice(new Tick { Value = 150, Time = time }); optionSecurity.Holdings.SetHoldings(1.5m, 10); var ticket = algorithm.ExerciseOption(optionSecurity.Symbol, 10, true); Assert.AreEqual(OrderStatus.Filled, ticket.Status); }
public void GetOpenOrdersWorksForSubmittedFilledStatus() { // Initializes the transaction handler var transactionHandler = new BrokerageTransactionHandler(); var broker = new BacktestingBrokerage(_algorithm); transactionHandler.Initialize(_algorithm, broker, new BacktestingResultHandler()); // Creates a limit order var security = _algorithm.Securities[Ticker]; var price = 1.12m; security.SetMarketPrice(new Tick(DateTime.Now, security.Symbol, price, price, price)); var orderRequest = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, 1000, 0, 1.11m, DateTime.Now, ""); // Mock the the order processor var orderProcessorMock = new Mock <IOrderProcessor>(); orderProcessorMock.Setup(m => m.GetOrderTicket(It.IsAny <int>())).Returns(new OrderTicket(_algorithm.Transactions, orderRequest)); _algorithm.Transactions.SetOrderProcessor(orderProcessorMock.Object); Assert.AreEqual(transactionHandler.GetOpenOrders().Count, 0); // Submit and process a limit order var orderTicket = transactionHandler.Process(orderRequest); transactionHandler.HandleOrderRequest(orderRequest); Assert.AreEqual(orderTicket.Status, OrderStatus.Submitted); var openOrders = transactionHandler.GetOpenOrders(); Assert.AreEqual(openOrders.Count, 1); Assert.AreEqual(openOrders[0].Id, orderTicket.OrderId); broker.Scan(); Assert.AreEqual(orderTicket.Status, OrderStatus.Filled); Assert.AreEqual(transactionHandler.GetOpenOrders().Count, 0); }
/// <summary> /// Setup the algorithm cash, dates and data subscriptions as desired. /// </summary> /// <param name="algorithm">Algorithm instance</param> /// <param name="brokerage">Brokerage instance</param> /// <param name="baseJob">Algorithm job</param> /// <param name="resultHandler">The configured result handler</param> /// <param name="transactionHandler">The configurated transaction handler</param> /// <returns>Boolean true on successfully initializing the algorithm</returns> public bool Setup(IAlgorithm algorithm, out IBrokerage brokerage, AlgorithmNodePacket baseJob, IResultHandler resultHandler, ITransactionHandler transactionHandler) { var job = baseJob as BacktestNodePacket; if (job == null) { throw new ArgumentException("Expected BacktestNodePacket but received " + baseJob.GetType().Name); } Log.Trace(string.Format("BacktestingSetupHandler.Setup(): Setting up job: Plan: {0}, UID: {1}, PID: {2}, Version: {3}, Source: {4}", job.UserPlan, job.UserId, job.ProjectId, job.Version, job.RequestSource)); brokerage = null; if (algorithm == null) { Errors.Add("Could not create instance of algorithm"); return(false); } //Make sure the algorithm start date ok. if (job.PeriodStart == default(DateTime)) { Errors.Add("Algorithm start date was never set"); return(false); } //Execute the initialize code: var isolator = new Isolator(); var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromSeconds(10), () => { try { //Algorithm is backtesting, not live: algorithm.SetLiveMode(false); //Set the backtest level asset ram allocation limits algorithm.SetAssetLimits(500, 100, 30); //Set the algorithm time before we even initialize: algorithm.SetDateTime(job.PeriodStart); //Initialise the algorithm, get the required data: algorithm.Initialize(); //Add currency data feeds that weren't explicity added in Initialize algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(algorithm.Securities, algorithm.SubscriptionManager, SecurityExchangeHoursProvider.FromDataFolder()); } catch (Exception err) { Errors.Add("Failed to initialize algorithm: Initialize(): " + err.Message); } }); //Before continuing, detect if this is ready: if (!initializeComplete) { return(false); } // this needs to be done after algorithm initialization brokerage = new BacktestingBrokerage(algorithm); SetupHandler.UpdateTransactionModels(algorithm, algorithm.BrokerageModel); algorithm.Transactions.SetOrderProcessor(transactionHandler); //Calculate the max runtime for the strategy _maxRuntime = GetMaximumRuntime(job.PeriodStart, job.PeriodFinish, algorithm.SubscriptionManager.Count); //Get starting capital: _startingCaptial = algorithm.Portfolio.Cash; //Max Orders: 10k per backtest: if (job.UserPlan == UserPlan.Free) { _maxOrders = 10000; } else { _maxOrders = int.MaxValue; _maxRuntime += _maxRuntime; } //Set back to the algorithm, algorithm.SetMaximumOrders(_maxOrders); //Starting date of the algorithm: _startingDate = job.PeriodStart; //Put into log for debugging: Log.Trace("SetUp Backtesting: User: "******" ProjectId: " + job.ProjectId + " AlgoId: " + job.AlgorithmId); Log.Trace("Dates: Start: " + job.PeriodStart.ToShortDateString() + " End: " + job.PeriodFinish.ToShortDateString() + " Cash: " + _startingCaptial.ToString("C")); if (Errors.Count > 0) { initializeComplete = false; } return(initializeComplete); }
public void SendingNewOrderFromOnOrderEvent() { //Initializes the transaction handler var transactionHandler = new BacktestingTransactionHandler(); var brokerage = new BacktestingBrokerage(_algorithm); transactionHandler.Initialize(_algorithm, brokerage, new BacktestingResultHandler()); // Creates a market order var security = _algorithm.Securities[Ticker]; var price = 1.12m; security.SetMarketPrice(new Tick(DateTime.UtcNow.AddDays(-1), security.Symbol, price, price, price)); var orderRequest = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, 1000, 0, 0, 0, DateTime.UtcNow, ""); var orderRequest2 = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, -1000, 0, 0, 0, DateTime.UtcNow, ""); orderRequest.SetOrderId(1); orderRequest2.SetOrderId(2); // Mock the the order processor var orderProcessorMock = new Mock <IOrderProcessor>(); orderProcessorMock.Setup(m => m.GetOrderTicket(It.Is <int>(i => i == 1))).Returns(new OrderTicket(_algorithm.Transactions, orderRequest)); orderProcessorMock.Setup(m => m.GetOrderTicket(It.Is <int>(i => i == 2))).Returns(new OrderTicket(_algorithm.Transactions, orderRequest2)); _algorithm.Transactions.SetOrderProcessor(orderProcessorMock.Object); var orderEventCalls = 0; brokerage.OrderStatusChanged += (sender, orderEvent) => { orderEventCalls++; switch (orderEventCalls) { case 1: Assert.AreEqual(1, orderEvent.OrderId); Assert.AreEqual(OrderStatus.Submitted, orderEvent.Status); // we send a new order request var ticket2 = transactionHandler.Process(orderRequest2); break; case 2: Assert.AreEqual(2, orderEvent.OrderId); Assert.AreEqual(OrderStatus.Submitted, orderEvent.Status); break; case 3: Assert.AreEqual(1, orderEvent.OrderId); Assert.AreEqual(OrderStatus.Filled, orderEvent.Status); break; case 4: Assert.AreEqual(2, orderEvent.OrderId); Assert.AreEqual(OrderStatus.Filled, orderEvent.Status); break; } Log.Trace($"{orderEvent}"); }; var ticket = transactionHandler.Process(orderRequest); Assert.IsTrue(orderRequest.Response.IsProcessed); Assert.IsTrue(orderRequest.Response.IsSuccess); Assert.AreEqual(OrderRequestStatus.Processed, orderRequest.Status); Assert.IsTrue(orderRequest2.Response.IsProcessed); Assert.IsTrue(orderRequest2.Response.IsSuccess); Assert.AreEqual(OrderRequestStatus.Processed, orderRequest2.Status); var order1 = transactionHandler.GetOrderById(1); Assert.AreEqual(OrderStatus.Filled, order1.Status); var order2 = transactionHandler.GetOrderById(2); Assert.AreEqual(OrderStatus.Filled, order2.Status); // 2 submitted and 2 filled Assert.AreEqual(4, orderEventCalls); }
/// <summary> /// Setup the algorithm cash, dates and data subscriptions as desired. /// </summary> /// <param name="algorithm">Algorithm instance</param> /// <param name="brokerage">Brokerage instance</param> /// <param name="baseJob">Algorithm job</param> /// <returns>Boolean true on successfully initializing the algorithm</returns> public bool Setup(IAlgorithm algorithm, out IBrokerage brokerage, AlgorithmNodePacket baseJob) { var job = baseJob as BacktestNodePacket; if (job == null) { throw new ArgumentException("Expected BacktestNodePacket but received " + baseJob.GetType().Name); } // Must be set since its defined as an out parameters brokerage = new BacktestingBrokerage(algorithm); if (algorithm == null) { Errors.Add("Could not create instance of algorithm"); return(false); } //Make sure the algorithm start date ok. if (job.PeriodStart == default(DateTime)) { Errors.Add("Algorithm start date was never set"); return(false); } //Execute the initialize code: var initializeComplete = Isolator.ExecuteWithTimeLimit(TimeSpan.FromSeconds(10), () => { try { //0.0 Set the algorithm time before we even initialize: algorithm.SetDateTime(job.PeriodStart); //1.0 Initialise the algorithm, get the required data: algorithm.Initialize(); //1.2 Set the algorithm to locked to avoid messing with cash: algorithm.SetLocked(); } catch (Exception err) { Errors.Add("Failed to initialize algorithm: Initialize(): " + err.Message); } }); //Before continuing, detect if this is ready: if (!initializeComplete) { return(false); } //Calculate the max runtime for the strategy _maxRuntime = GetMaximumRuntime(job.PeriodStart, job.PeriodFinish, algorithm.SubscriptionManager.Count); //Get starting capital: _startingCaptial = algorithm.Portfolio.Cash; //Max Orders: 100 per day: _maxOrders = (int)(job.PeriodFinish - job.PeriodStart).TotalDays * 100; //Starting date of the algorithm: _startingDate = job.PeriodStart; //Put into log for debugging: Log.Trace("SetUp Backtesting: User: "******" ProjectId: " + job.ProjectId + " AlgoId: " + job.AlgorithmId); Log.Trace("Dates: Start: " + job.PeriodStart.ToShortDateString() + " End: " + job.PeriodFinish.ToShortDateString() + " Cash: " + _startingCaptial.ToString("C")); if (Errors.Count > 0) { initializeComplete = false; } return(initializeComplete); }
/// <summary> /// Setup the algorithm cash, dates and portfolio as desired. /// </summary> /// <param name="algorithm">Existing algorithm instance</param> /// <param name="brokerage">New brokerage instance</param> /// <param name="baseJob">Backtesting job</param> /// <returns>Boolean true on successfully setting up the console.</returns> public bool Setup(IAlgorithm algorithm, out IBrokerage brokerage, AlgorithmNodePacket baseJob) { var initializeComplete = false; brokerage = new BacktestingBrokerage(algorithm); try { //Set common variables for console programs: if (baseJob.Type == PacketType.BacktestNode) { var backtestJob = baseJob as BacktestNodePacket; //Set the limits on the algorithm assets (for local no limits) algorithm.SetAssetLimits(999, 999, 999); algorithm.SetMaximumOrders(int.MaxValue); //Setup Base Algorithm: algorithm.Initialize(); //Add currency data feeds that weren't explicity added in Initialize algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(algorithm.Securities, algorithm.SubscriptionManager); //Construct the backtest job packet: backtestJob.PeriodStart = algorithm.StartDate; backtestJob.PeriodFinish = algorithm.EndDate; backtestJob.BacktestId = "LOCALHOST"; backtestJob.UserId = 1001; backtestJob.Type = PacketType.BacktestNode; //Backtest Specific Parameters: StartingDate = backtestJob.PeriodStart; StartingPortfolioValue = algorithm.Portfolio.Cash; } else { var liveJob = baseJob as LiveNodePacket; //Live Job Parameters: liveJob.DeployId = "LOCALHOST"; liveJob.Type = PacketType.LiveNode; //Call in the brokerage setup: var setup = new BrokerageSetupHandler(); setup.Setup(algorithm, out brokerage, baseJob); //Live Specific Parameters: StartingDate = DateTime.Now; StartingPortfolioValue = algorithm.Portfolio.Cash; } } catch (Exception err) { Log.Error("ConsoleSetupHandler().Setup(): " + err.Message); Errors.Add("Failed to initialize algorithm: Initialize(): " + err.Message); } if (Errors.Count == 0) { initializeComplete = true; } return(initializeComplete); }
/// <summary> /// Setup the algorithm cash, dates and portfolio as desired. /// </summary> /// <param name="algorithm">Existing algorithm instance</param> /// <param name="brokerage">New brokerage instance</param> /// <param name="baseJob">Backtesting job</param> /// <returns>Boolean true on successfully setting up the console.</returns> public bool Setup(IAlgorithm algorithm, out IBrokerage brokerage, AlgorithmNodePacket baseJob) { var initializeComplete = false; brokerage = new BacktestingBrokerage(algorithm); try { //Set common variables for console programs: if (baseJob.Type == PacketType.BacktestNode) { var backtestJob = baseJob as BacktestNodePacket; //Setup Base Algorithm: algorithm.Initialize(); //Construct the backtest job packet: backtestJob.PeriodStart = algorithm.StartDate; backtestJob.PeriodFinish = algorithm.EndDate; backtestJob.BacktestId = "LOCALHOST"; backtestJob.UserId = 1001; backtestJob.Type = PacketType.BacktestNode; //Endpoints: backtestJob.TransactionEndpoint = TransactionHandlerEndpoint.Backtesting; backtestJob.ResultEndpoint = ResultHandlerEndpoint.Console; backtestJob.DataEndpoint = DataFeedEndpoint.FileSystem; backtestJob.RealTimeEndpoint = RealTimeEndpoint.Backtesting; backtestJob.SetupEndpoint = SetupHandlerEndpoint.Console; //Backtest Specific Parameters: StartingDate = backtestJob.PeriodStart; StartingCapital = algorithm.Portfolio.Cash; } else { var liveJob = baseJob as LiveNodePacket; //Live Job Parameters: liveJob.UserId = liveJob.UserId; liveJob.DeployId = "LOCALHOST"; liveJob.IssuedAt = DateTime.Now.Subtract(TimeSpan.FromSeconds(86399 - 60)); //For testing, first access token expires in 60 sec. refresh. liveJob.LifeTime = TimeSpan.FromSeconds(86399); liveJob.AccessToken = "123456"; liveJob.AccountId = 123456; liveJob.RefreshToken = ""; liveJob.Type = PacketType.LiveNode; //Endpoints: liveJob.TransactionEndpoint = TransactionHandlerEndpoint.Backtesting; liveJob.ResultEndpoint = ResultHandlerEndpoint.LiveTrading; bool testLiveTradingEnabled = Config.GetBool("test-live-trading-enabled", defaultValue: false); liveJob.DataEndpoint = testLiveTradingEnabled ? DataFeedEndpoint.Test : DataFeedEndpoint.LiveTrading; liveJob.RealTimeEndpoint = RealTimeEndpoint.LiveTrading; liveJob.SetupEndpoint = SetupHandlerEndpoint.Console; //Call in the paper trading setup: var setup = new PaperTradingSetupHandler(); setup.Setup(algorithm, out brokerage, baseJob); //Live Specific Parameters: StartingDate = DateTime.Now; StartingCapital = algorithm.Portfolio.Cash; } } catch (Exception err) { Log.Error("ConsoleSetupHandler().Setup(): " + err.Message); } if (Errors.Count == 0) { initializeComplete = true; } return(initializeComplete); }
/// <summary> /// Creates a new BacktestingTransactionHandler using the BacktestingBrokerage /// </summary> /// <param name="algorithm">The algorithm instance</param> /// <param name="brokerage">The BacktestingBrokerage</param> public BacktestingTransactionHandler(IAlgorithm algorithm, BacktestingBrokerage brokerage) : base(algorithm, brokerage) { _brokerage = brokerage; }
/// <summary> /// Setup the algorithm cash, dates and portfolio as desired. /// </summary> /// <param name="algorithm">Existing algorithm instance</param> /// <param name="brokerage">New brokerage instance</param> /// <param name="baseJob">Backtesting job</param> /// <returns>Boolean true on successfully setting up the console.</returns> public bool Setup(IAlgorithm algorithm, out IBrokerage brokerage, AlgorithmNodePacket baseJob) { var initializeComplete = false; brokerage = new BacktestingBrokerage(algorithm); try { //Set common variables for console programs: if (baseJob.Type == PacketType.BacktestNode) { var backtestJob = baseJob as BacktestNodePacket; //Set the limits on the algorithm assets (for local no limits) algorithm.SetAssetLimits(999, 999, 999); algorithm.SetMaximumOrders(int.MaxValue); //Setup Base Algorithm: algorithm.Initialize(); //Add currency data feeds that weren't explicity added in Initialize algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(algorithm.SubscriptionManager, algorithm.Securities); //Construct the backtest job packet: backtestJob.PeriodStart = algorithm.StartDate; backtestJob.PeriodFinish = algorithm.EndDate; backtestJob.BacktestId = "LOCALHOST"; backtestJob.UserId = 1001; backtestJob.Type = PacketType.BacktestNode; //Endpoints: backtestJob.TransactionEndpoint = TransactionHandlerEndpoint.Backtesting; backtestJob.ResultEndpoint = ResultHandlerEndpoint.Console; backtestJob.DataEndpoint = DataFeedEndpoint.FileSystem; backtestJob.RealTimeEndpoint = RealTimeEndpoint.Backtesting; backtestJob.SetupEndpoint = SetupHandlerEndpoint.Console; //Backtest Specific Parameters: StartingDate = backtestJob.PeriodStart; StartingCapital = algorithm.Portfolio.Cash; } else { var liveJob = baseJob as LiveNodePacket; //Live Job Parameters: liveJob.DeployId = "LOCALHOST"; liveJob.IssuedAt = DateTime.Now.Subtract(TimeSpan.FromSeconds(86399 - 60)); //For testing, first access token expires in 60 sec. refresh. liveJob.LifeTime = TimeSpan.FromSeconds(86399); liveJob.AccessToken = "123456"; liveJob.AccountId = "123456"; liveJob.RefreshToken = ""; liveJob.Type = PacketType.LiveNode; //Endpoints: liveJob.TransactionEndpoint = TransactionHandlerEndpoint.Backtesting; liveJob.ResultEndpoint = ResultHandlerEndpoint.LiveTrading; liveJob.DataEndpoint = DataFeedEndpoint.LiveTrading; liveJob.RealTimeEndpoint = RealTimeEndpoint.LiveTrading; liveJob.SetupEndpoint = SetupHandlerEndpoint.Console; //Call in the paper trading setup: var setup = new PaperTradingSetupHandler(); setup.Setup(algorithm, out brokerage, baseJob); //Live Specific Parameters: StartingDate = DateTime.Now; StartingCapital = algorithm.Portfolio.Cash; } } catch (Exception err) { Log.Error("ConsoleSetupHandler().Setup(): " + err.Message); Errors.Add("Failed to initialize algorithm: Initialize(): " + err.Message); } if (Errors.Count == 0) { initializeComplete = true; } return(initializeComplete); }