/// <summary> /// Setup the algorithm cash, dates and data subscriptions as desired. /// </summary> /// <param name="parameters">The parameters object to use</param> /// <returns>Boolean true on successfully initializing the algorithm</returns> public bool Setup(SetupHandlerParameters parameters) { var algorithm = parameters.Algorithm; var job = parameters.AlgorithmNodePacket as BacktestNodePacket; if (job == null) { throw new ArgumentException("Expected BacktestNodePacket but received " + parameters.AlgorithmNodePacket.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)); if (algorithm == null) { Errors.Add(new AlgorithmSetupException("Could not create instance of algorithm")); return(false); } algorithm.Name = job.GetAlgorithmName(); //Make sure the algorithm start date ok. if (job.PeriodStart == default(DateTime)) { Errors.Add(new AlgorithmSetupException("Algorithm start date was never set")); return(false); } var controls = job.Controls; var isolator = new Isolator(); var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromMinutes(5), () => { try { parameters.ResultHandler.SendStatusUpdate(AlgorithmStatus.Initializing, "Initializing algorithm..."); //Set our parameters algorithm.SetParameters(job.Parameters); //Algorithm is backtesting, not live: algorithm.SetLiveMode(false); //Set the source impl for the event scheduling algorithm.Schedule.SetEventSchedule(parameters.RealTimeHandler); // set the option chain provider algorithm.SetOptionChainProvider(new CachingOptionChainProvider(new BacktestingOptionChainProvider())); // set the future chain provider algorithm.SetFutureChainProvider(new CachingFutureChainProvider(new BacktestingFutureChainProvider())); //Initialise the algorithm, get the required data: algorithm.Initialize(); // finalize initialization algorithm.PostInitialize(); } catch (Exception err) { Log.Error(err); Errors.Add(new AlgorithmSetupException("During the algorithm initialization, the following exception has occurred: ", err)); } }, controls.RamAllocation, sleepIntervalMillis: 50); // entire system is waiting on this, so be as fast as possible //Before continuing, detect if this is ready: if (!initializeComplete) { return(false); } // TODO: Refactor the BacktestResultHandler to use algorithm not job to set times job.PeriodStart = algorithm.StartDate; job.PeriodFinish = algorithm.EndDate; //Calculate the max runtime for the strategy _maxRuntime = GetMaximumRuntime(job.PeriodStart, job.PeriodFinish, algorithm.SubscriptionManager, algorithm.UniverseManager, parameters.AlgorithmNodePacket.Controls); // Python takes forever; lets give it 10x longer to finish. if (job.Language == Language.Python) { _maxRuntime = _maxRuntime.Add(TimeSpan.FromSeconds(_maxRuntime.TotalSeconds * 9)); } BaseSetupHandler.SetupCurrencyConversions(algorithm, parameters.UniverseSelection); StartingPortfolioValue = 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: " + StartingPortfolioValue.ToString("C")); if (Errors.Count > 0) { initializeComplete = false; } return(initializeComplete); }
/// <summary> /// Setup the algorithm cash, dates and data subscriptions as desired. /// </summary> /// <param name="parameters">The parameters object to use</param> /// <returns>Boolean true on successfully initializing the algorithm</returns> public bool Setup(SetupHandlerParameters parameters) { var algorithm = parameters.Algorithm; var job = parameters.AlgorithmNodePacket as BacktestNodePacket; if (job == null) { throw new ArgumentException("Expected BacktestNodePacket but received " + parameters.AlgorithmNodePacket.GetType().Name); } Log.Trace($"BacktestingSetupHandler.Setup(): Setting up job: Plan: {job.UserPlan}, UID: {job.UserId.ToStringInvariant()}, " + $"PID: {job.ProjectId.ToStringInvariant()}, Version: {job.Version}, Source: {job.RequestSource}" ); if (algorithm == null) { Errors.Add(new AlgorithmSetupException("Could not create instance of algorithm")); return(false); } algorithm.Name = job.GetAlgorithmName(); //Make sure the algorithm start date ok. if (job.PeriodStart == default(DateTime)) { Errors.Add(new AlgorithmSetupException("Algorithm start date was never set")); return(false); } var controls = job.Controls; var isolator = new Isolator(); var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromMinutes(5), () => { try { parameters.ResultHandler.SendStatusUpdate(AlgorithmStatus.Initializing, "Initializing algorithm..."); //Set our parameters algorithm.SetParameters(job.Parameters); //Algorithm is backtesting, not live: algorithm.SetLiveMode(false); //Set the source impl for the event scheduling algorithm.Schedule.SetEventSchedule(parameters.RealTimeHandler); // set the option chain provider algorithm.SetOptionChainProvider(new CachingOptionChainProvider(new BacktestingOptionChainProvider())); // set the future chain provider algorithm.SetFutureChainProvider(new CachingFutureChainProvider(new BacktestingFutureChainProvider())); // set the object store algorithm.SetObjectStore(parameters.ObjectStore); // before we call initialize BaseSetupHandler.LoadBacktestJobAccountCurrency(algorithm, job); //Initialise the algorithm, get the required data: algorithm.Initialize(); // set start and end date if present in the job if (job.PeriodStart.HasValue) { algorithm.SetStartDate(job.PeriodStart.Value); } if (job.PeriodFinish.HasValue) { algorithm.SetEndDate(job.PeriodFinish.Value); } // after we call initialize BaseSetupHandler.LoadBacktestJobCashAmount(algorithm, job); // finalize initialization algorithm.PostInitialize(); } catch (Exception err) { Log.Error(err); Errors.Add(new AlgorithmSetupException("During the algorithm initialization, the following exception has occurred: ", err)); } }, controls.RamAllocation, sleepIntervalMillis: 10, // entire system is waiting on this, so be as fast as possible workerThread: WorkerThread); //Before continuing, detect if this is ready: if (!initializeComplete) { return(false); } //Calculate the max runtime for the strategy MaximumRuntime = GetMaximumRuntime(algorithm.StartDate, algorithm.EndDate, algorithm.SubscriptionManager, algorithm.UniverseManager, parameters.AlgorithmNodePacket.Controls); // Python takes forever; lets give it 10x longer to finish. if (job.Language == Language.Python) { MaximumRuntime = MaximumRuntime.Add(TimeSpan.FromSeconds(MaximumRuntime.TotalSeconds * 9)); } BaseSetupHandler.SetupCurrencyConversions(algorithm, parameters.UniverseSelection); StartingPortfolioValue = algorithm.Portfolio.Cash; // we set the free portfolio value based on the initial total value and the free percentage value algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; //Max Orders: 10k per backtest: if (job.UserPlan == UserPlan.Free) { MaxOrders = 10000; } else { MaxOrders = int.MaxValue; MaximumRuntime += MaximumRuntime; } MaxOrders = job.Controls.BacktestingMaxOrders; //Set back to the algorithm, algorithm.SetMaximumOrders(MaxOrders); //Starting date of the algorithm: StartingDate = algorithm.StartDate; //Put into log for debugging: Log.Trace("SetUp Backtesting: User: "******" ProjectId: " + job.ProjectId + " AlgoId: " + job.AlgorithmId); Log.Trace($"Dates: Start: {algorithm.StartDate.ToStringInvariant("d")} " + $"End: {algorithm.EndDate.ToStringInvariant("d")} " + $"Cash: {StartingPortfolioValue.ToStringInvariant("C")}"); if (Errors.Count > 0) { initializeComplete = false; } return(initializeComplete); }