本文整理汇总了C#中IAlgorithm.SetDateTime方法的典型用法代码示例。如果您正苦于以下问题:C# IAlgorithm.SetDateTime方法的具体用法?C# IAlgorithm.SetDateTime怎么用?C# IAlgorithm.SetDateTime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IAlgorithm
的用法示例。
在下文中一共展示了IAlgorithm.SetDateTime方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Setup
/// <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>
/// <param name="realTimeHandler">The configured real time handler</param>
/// <returns>Boolean true on successfully initializing the algorithm</returns>
public bool Setup(IAlgorithm algorithm, IBrokerage brokerage, AlgorithmNodePacket baseJob, IResultHandler resultHandler, ITransactionHandler transactionHandler, IRealTimeHandler realTimeHandler)
{
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));
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;
}
var controls = job.Controls;
var isolator = new Isolator();
var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromMinutes(5), () =>
{
try
{
//Set our parameters
algorithm.SetParameters(job.Parameters);
//Algorithm is backtesting, not live:
algorithm.SetLiveMode(false);
//Set the algorithm time before we even initialize:
algorithm.SetDateTime(job.PeriodStart.ConvertToUtc(algorithm.TimeZone));
//Set the source impl for the event scheduling
algorithm.Schedule.SetEventSchedule(realTimeHandler);
//Initialise the algorithm, get the required data:
algorithm.Initialize();
}
catch (Exception err)
{
Errors.Add("Failed to initialize algorithm: Initialize(): " + err.Message);
}
});
//Before continuing, detect if this is ready:
if (!initializeComplete) return false;
algorithm.Transactions.SetOrderProcessor(transactionHandler);
algorithm.PostInitialize();
//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: " + job.UserId + " 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;
}
示例2: Setup
/// <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
{
//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();
}
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: " + job.UserId + " 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;
}
示例3: Setup
/// <summary>
/// Primary entry point to setup a new algorithm
/// </summary>
/// <param name="algorithm">Algorithm instance</param>
/// <param name="brokerage">New brokerage output instance</param>
/// <param name="job">Algorithm job task</param>
/// <param name="resultHandler">The configured result handler</param>
/// <param name="transactionHandler">The configurated transaction handler</param>
/// <param name="realTimeHandler">The configured real time handler</param>
/// <returns>True on successfully setting up the algorithm state, or false on error.</returns>
public bool Setup(IAlgorithm algorithm, out IBrokerage brokerage, AlgorithmNodePacket job, IResultHandler resultHandler, ITransactionHandler transactionHandler, IRealTimeHandler realTimeHandler)
{
_algorithm = algorithm;
brokerage = default(IBrokerage);
// verify we were given the correct job packet type
var liveJob = job as LiveNodePacket;
if (liveJob == null)
{
AddInitializationError("BrokerageSetupHandler requires a LiveNodePacket");
return false;
}
// verify the brokerage was specified
if (string.IsNullOrWhiteSpace(liveJob.Brokerage))
{
AddInitializationError("A brokerage must be specified");
return false;
}
// attach to the message event to relay brokerage specific initialization messages
EventHandler<BrokerageMessageEvent> brokerageOnMessage = (sender, args) =>
{
if (args.Type == BrokerageMessageType.Error)
{
AddInitializationError(string.Format("Brokerage Error Code: {0} - {1}", args.Code, args.Message));
}
};
try
{
Log.Trace("BrokerageSetupHandler.Setup(): Initializing algorithm...");
//Execute the initialize code:
var isolator = new Isolator();
var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromSeconds(10), () =>
{
try
{
//Set the live trading level asset/ram allocation limits.
//Protects algorithm from linux killing the job by excess memory:
switch (job.ServerType)
{
case ServerType.Server1024:
algorithm.SetAssetLimits(100, 20, 10);
break;
case ServerType.Server2048:
algorithm.SetAssetLimits(400, 50, 30);
break;
default: //512
algorithm.SetAssetLimits(50, 25, 15);
break;
}
//Algorithm is live, not backtesting:
algorithm.SetLiveMode(true);
//Initialize the algorithm's starting date
algorithm.SetDateTime(DateTime.UtcNow);
//Set the source impl for the event scheduling
algorithm.Schedule.SetEventSchedule(realTimeHandler);
//Initialise the algorithm, get the required data:
algorithm.Initialize();
}
catch (Exception err)
{
AddInitializationError(err.Message);
}
});
if (!initializeComplete)
{
AddInitializationError("Initialization timed out.");
return false;
}
try
{
// find the correct brokerage factory based on the specified brokerage in the live job packet
_factory = Composer.Instance.Single<IBrokerageFactory>(factory => factory.BrokerageType.MatchesTypeName(liveJob.Brokerage));
}
catch (Exception err)
{
Log.Error("BrokerageSetupHandler.Setup(): Error resolving brokerage factory for " + liveJob.Brokerage + ". " + err.Message);
AddInitializationError("Unable to locate factory for brokerage: " + liveJob.Brokerage);
}
// let the world know what we're doing since logging in can take a minute
resultHandler.SendStatusUpdate(job.AlgorithmId, AlgorithmStatus.LoggingIn, "Logging into brokerage...");
//.........这里部分代码省略.........
示例4: Run
//.........这里部分代码省略.........
//Execute with TimeLimit Monitor:
if (Isolator.IsCancellationRequested) return;
//Refresh the realtime event monitor:
realtime.SetTime(time);
//Fire EOD if the time packet we just processed is greater
if (backtestMode && _previousTime.Date != time.Date)
{
//Sample the portfolio value over time for chart.
results.SampleEquity(_previousTime, Math.Round(algorithm.Portfolio.TotalPortfolioValue, 4));
if (startingPerformance == 0)
{
results.SamplePerformance(_previousTime.Date, 0);
}
else
{
results.SamplePerformance(_previousTime.Date, Math.Round((algorithm.Portfolio.TotalPortfolioValue - startingPerformance) * 100 / startingPerformance, 10));
}
startingPerformance = algorithm.Portfolio.TotalPortfolioValue;
}
//Check if the user's signalled Quit: loop over data until day changes.
if (algorithm.GetQuit())
{
_algorithmState = AlgorithmStatus.Quit;
break;
}
//Pass in the new time first:
algorithm.SetDateTime(time);
//Trigger the data events: Invoke the types we have data for:
var oldBars = new Dictionary<string, TradeBar>();
var oldTicks = new Dictionary<string, List<Tick>>();
var newBars = new TradeBars(time);
var newTicks = new Ticks(time);
//Invoke all non-tradebars, non-ticks methods:
// --> i == Subscription Configuration Index, so we don't need to compare types.
foreach (var i in newData[time].Keys)
{
//Data point and config of this point:
var dataPoints = newData[time][i];
var config = feed.Subscriptions[i];
//Create TradeBars Unified Data --> OR --> invoke generic data event. One loop.
foreach (var dataPoint in dataPoints)
{
//Update the securities properties: first before calling user code to avoid issues with data
algorithm.Securities.Update(time, dataPoint);
//Update registered consolidators for this symbol index
for (var j = 0; j < config.Consolidators.Count; j++)
{
config.Consolidators[j].Update(dataPoint);
}
switch (config.Type.Name)
{
case "TradeBar":
var bar = dataPoint as TradeBar;
try
示例5: Setup
/// <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>
/// <param name="realTimeHandler">The configured real time handler</param>
/// <returns>Boolean true on successfully setting up the console.</returns>
public bool Setup(IAlgorithm algorithm, IBrokerage brokerage, AlgorithmNodePacket baseJob, IResultHandler resultHandler, ITransactionHandler transactionHandler, IRealTimeHandler realTimeHandler)
{
var initializeComplete = false;
try
{
//Set common variables for console programs:
if (baseJob.Type == PacketType.BacktestNode)
{
var backtestJob = baseJob as BacktestNodePacket;
//Set our default markets
algorithm.SetDefaultMarkets(BacktestingBrokerageFactory.DefaultMarketMap.ToDictionary());
algorithm.SetMaximumOrders(int.MaxValue);
// set our parameters
algorithm.SetParameters(baseJob.Parameters);
algorithm.SetLiveMode(false);
//Set the source impl for the event scheduling
algorithm.Schedule.SetEventSchedule(realTimeHandler);
//Setup Base Algorithm:
algorithm.Initialize();
//Set the time frontier of the algorithm
algorithm.SetDateTime(algorithm.StartDate.ConvertToUtc(algorithm.TimeZone));
//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(err);
Errors.Add("Failed to initialize algorithm: Initialize(): " + err.Message);
}
if (Errors.Count == 0)
{
initializeComplete = true;
}
// set the transaction and settlement models based on the brokerage properties
algorithm.UpdateModels(algorithm.BrokerageModel);
algorithm.Transactions.SetOrderProcessor(transactionHandler);
algorithm.PostInitialize();
return initializeComplete;
}
示例6: Setup
/// <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>
/// <param name="realTimeHandler">The configured real time 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, IRealTimeHandler realTimeHandler)
{
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);
algorithm.SetLiveMode(false);
//Set the source impl for the event scheduling
algorithm.Schedule.SetEventSchedule(realTimeHandler);
//Setup Base Algorithm:
algorithm.Initialize();
//Set the time frontier of the algorithm
algorithm.SetDateTime(algorithm.StartDate.ConvertToUtc(algorithm.TimeZone));
//Add currency data feeds that weren't explicity added in Initialize
algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(algorithm.Securities, algorithm.SubscriptionManager, MarketHoursDatabase.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 and settlement models based on the brokerage properties
SetupHandler.UpdateModels(algorithm, algorithm.BrokerageModel);
algorithm.Transactions.SetOrderProcessor(transactionHandler);
algorithm.PostInitialize();
return initializeComplete;
}
示例7: Setup
/// <summary>
/// Primary entry point to setup a new algorithm
/// </summary>
/// <param name="algorithm">Algorithm instance</param>
/// <param name="brokerage">New brokerage output instance</param>
/// <param name="job">Algorithm job task</param>
/// <param name="resultHandler">The configured result handler</param>
/// <param name="transactionHandler">The configurated transaction handler</param>
/// <param name="realTimeHandler">The configured real time handler</param>
/// <returns>True on successfully setting up the algorithm state, or false on error.</returns>
public bool Setup(IAlgorithm algorithm, IBrokerage brokerage, AlgorithmNodePacket job, IResultHandler resultHandler, ITransactionHandler transactionHandler, IRealTimeHandler realTimeHandler)
{
_algorithm = algorithm;
// verify we were given the correct job packet type
var liveJob = job as LiveNodePacket;
if (liveJob == null)
{
AddInitializationError("BrokerageSetupHandler requires a LiveNodePacket");
return false;
}
// verify the brokerage was specified
if (string.IsNullOrWhiteSpace(liveJob.Brokerage))
{
AddInitializationError("A brokerage must be specified");
return false;
}
// attach to the message event to relay brokerage specific initialization messages
EventHandler<BrokerageMessageEvent> brokerageOnMessage = (sender, args) =>
{
if (args.Type == BrokerageMessageType.Error)
{
AddInitializationError(string.Format("Brokerage Error Code: {0} - {1}", args.Code, args.Message));
}
};
try
{
Log.Trace("BrokerageSetupHandler.Setup(): Initializing algorithm...");
resultHandler.SendStatusUpdate(AlgorithmStatus.Initializing, "Initializing algorithm...");
//Execute the initialize code:
var controls = job.Controls;
var isolator = new Isolator();
var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromSeconds(300), () =>
{
try
{
//Set the default brokerage model before initialize
algorithm.SetBrokerageModel(_factory.BrokerageModel);
//Set our parameters
algorithm.SetParameters(job.Parameters);
//Algorithm is live, not backtesting:
algorithm.SetLiveMode(true);
//Initialize the algorithm's starting date
algorithm.SetDateTime(DateTime.UtcNow);
//Set the source impl for the event scheduling
algorithm.Schedule.SetEventSchedule(realTimeHandler);
//Initialise the algorithm, get the required data:
algorithm.Initialize();
if (liveJob.Brokerage != "PaperBrokerage")
{
//Zero the CashBook - we'll populate directly from brokerage
foreach (var kvp in algorithm.Portfolio.CashBook)
{
kvp.Value.SetAmount(0);
}
}
}
catch (Exception err)
{
AddInitializationError(err.Message);
}
});
if (!initializeComplete)
{
AddInitializationError("Initialization timed out.");
return false;
}
// let the world know what we're doing since logging in can take a minute
resultHandler.SendStatusUpdate(AlgorithmStatus.LoggingIn, "Logging into brokerage...");
brokerage.Message += brokerageOnMessage;
algorithm.Transactions.SetOrderProcessor(transactionHandler);
Log.Trace("BrokerageSetupHandler.Setup(): Connecting to brokerage...");
try
{
// this can fail for various reasons, such as already being logged in somewhere else
brokerage.Connect();
}
catch (Exception err)
{
//.........这里部分代码省略.........
示例8: Setup
/// <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);
}
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: " + job.UserId + " 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;
}
示例9: Setup
/// <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>
/// <param name="realTimeHandler">The configured real time handler</param>
/// <returns>Boolean true on successfully setting up the console.</returns>
public bool Setup(IAlgorithm algorithm, IBrokerage brokerage, AlgorithmNodePacket baseJob, IResultHandler resultHandler, ITransactionHandler transactionHandler, IRealTimeHandler realTimeHandler)
{
var initializeComplete = false;
try
{
//Set common variables for console programs:
if (baseJob.Type == PacketType.BacktestNode)
{
var backtestJob = baseJob as BacktestNodePacket;
algorithm.SetMaximumOrders(int.MaxValue);
// set our parameters
algorithm.SetParameters(baseJob.Parameters);
algorithm.SetLiveMode(false);
//Set the source impl for the event scheduling
algorithm.Schedule.SetEventSchedule(realTimeHandler);
//Setup Base Algorithm:
algorithm.Initialize();
//Set the time frontier of the algorithm
algorithm.SetDateTime(algorithm.StartDate.ConvertToUtc(algorithm.TimeZone));
//Construct the backtest job packet:
backtestJob.PeriodStart = algorithm.StartDate;
backtestJob.PeriodFinish = algorithm.EndDate;
backtestJob.BacktestId = "LOCALHOST";
backtestJob.Type = PacketType.BacktestNode;
backtestJob.UserId = !string.IsNullOrWhiteSpace(Config.Get("qc-user-id")) ? Convert.ToInt32(Config.Get("qc-user-id")) : 1001;
backtestJob.Channel = Config.Get("api-access-token");
//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(err);
Errors.Add("Failed to initialize algorithm: Initialize(): " + err.Message);
}
if (Errors.Count == 0)
{
initializeComplete = true;
}
algorithm.Transactions.SetOrderProcessor(transactionHandler);
algorithm.PostInitialize();
return initializeComplete;
}