Lean
$LEAN_TAG$
|
Backtesting result handler passes messages back from the Lean to the User. More...
Public Member Functions | |
BacktestingResultHandler () | |
Creates a new instance More... | |
override void | Initialize (ResultHandlerInitializeParameters parameters) |
Initialize the result handler with this result packet. More... | |
virtual IEnumerable< BacktestResultPacket > | SplitPackets (Dictionary< string, Chart > deltaCharts, Dictionary< int, Order > deltaOrders, SortedDictionary< string, string > runtimeStatistics, decimal progress, Dictionary< string, string > serverStatistics) |
Run over all the data and break it into smaller packets to ensure they all arrive at the terminal More... | |
virtual void | SetAlgorithm (IAlgorithm algorithm, decimal startingPortfolioValue) |
Set the Algorithm instance for ths result. More... | |
virtual void | AlgorithmNameUpdated (string name) |
Handles updates to the algorithm's name More... | |
virtual void | AlgorithmTagsUpdated (HashSet< string > tags) |
Sends a packet communicating an update to the algorithm's tags More... | |
virtual void | DebugMessage (string message) |
Send a debug message back to the browser console. More... | |
virtual void | SystemDebugMessage (string message) |
Send a system debug message back to the browser console. More... | |
virtual void | LogMessage (string message) |
Send a logging message to the log list for storage. More... | |
virtual void | SecurityType (List< SecurityType > types) |
Send list of security asset types the algorithm uses to browser. More... | |
virtual void | ErrorMessage (string message, string stacktrace="") |
Send an error message back to the browser highlighted in red with a stacktrace. More... | |
virtual void | RuntimeError (string message, string stacktrace="") |
Send a runtime error message back to the browser highlighted with in red More... | |
virtual void | BrokerageMessage (BrokerageMessageEvent brokerageMessageEvent) |
Process brokerage message events More... | |
override void | Exit () |
Terminate the result thread and apply any required exit procedures like sending final results. More... | |
virtual void | SendStatusUpdate (AlgorithmStatus status, string message="") |
Send an algorithm status update to the browser. More... | |
virtual void | RuntimeStatistic (string key, string value) |
Set the current runtime statistics of the algorithm. These are banner/title statistics which show at the top of the live trading results. More... | |
override void | OrderEvent (OrderEvent newEvent) |
Handle order event More... | |
virtual void | ProcessSynchronousEvents (bool forceProcess=false) |
Process the synchronous result events, sampling and message reading. This method is triggered from the algorithm manager thread. More... | |
StatisticsResults | StatisticsResults () |
Calculates and gets the current statistics for the algorithm More... | |
void | SetSummaryStatistic (string name, string value) |
Sets or updates a custom summary statistic More... | |
Public Member Functions inherited from QuantConnect.Lean.Engine.Results.BaseResultsHandler | |
virtual void | OnSecuritiesChanged (SecurityChanges changes) |
Event fired each time that we add/remove securities from the data feed More... | |
virtual string | SaveLogs (string id, List< LogEntry > logs) |
Returns the location of the logs More... | |
virtual void | SaveResults (string name, Result result) |
Save the results to disk More... | |
virtual void | Sample (DateTime time) |
Samples portfolio equity, benchmark, and daily performance Called by scheduled event every night at midnight algorithm time More... | |
Public Member Functions inherited from QuantConnect.Lean.Engine.Results.IResultHandler | |
void | OnSecuritiesChanged (SecurityChanges changes) |
Event fired each time that we add/remove securities from the data feed More... | |
void | Sample (DateTime time) |
Method to update the IResultHandler with various performance metrics. Called once a day by scheduled event in AlgorithmManager More... | |
void | SaveResults (string name, Result result) |
Save the results More... | |
Protected Member Functions | |
override void | Run () |
The main processing method steps through the messaging queue and processes the messages one by one. More... | |
override void | StoreResult (Packet packet) |
Save the snapshot of the total results to storage. More... | |
void | SendFinalResult () |
Send a final analysis result back to the IDE. More... | |
override void | AddToLogStore (string message) |
Add message to LogStore More... | |
override void | Sample (string chartName, string seriesName, int seriesIndex, SeriesType seriesType, ISeriesPoint value, string unit="$") |
Add a sample to the chart specified by the chartName, and seriesName. More... | |
override void | SampleCapacity (DateTime time) |
Sample estimated strategy capacity More... | |
void | SampleRange (IEnumerable< Chart > updates) |
Add a range of samples from the users algorithms to the end of our current list. More... | |
virtual void | ConfigureConsoleTextWriter (IAlgorithm algorithm) |
Configures the Console.Out and Console.Error TextWriter instances. By default, we forward Console.WriteLine(string) to IAlgorithm.Debug. This is perfect for running in the cloud, but since they're processed asynchronously, the ordering of these messages with respect to Log messages is broken. This can lead to differences in regression test logs based solely on the ordering of messages. To disable this forwarding, set More... | |
Protected Member Functions inherited from QuantConnect.Lean.Engine.Results.BaseResultsHandler | |
BaseResultsHandler () | |
Creates a new instance More... | |
virtual Dictionary< string, string > | GetServerStatistics (DateTime utcNow) |
Gets the current Server statistics More... | |
virtual void | StoreOrderEvents (DateTime utcTime, List< OrderEvent > orderEvents) |
Stores the order events More... | |
virtual void | StoreInsights () |
Save insight results to persistent storage More... | |
virtual Dictionary< int, Order > | GetDeltaOrders (int orderEventsStartPosition, Func< int, bool > shouldStop) |
Gets the orders generated starting from the provided ITransactionHandler.OrderEvents position More... | |
string | GetResultsPath (string filename) |
Gets the full path for a results file More... | |
void | PurgeQueue () |
Purge/clear any outstanding messages in message queue. More... | |
void | StopUpdateRunner () |
Stops the update runner task More... | |
decimal | GetNetReturn () |
Gets the algorithm net return More... | |
virtual decimal | GetPortfolioValue () |
Gets the current portfolio value More... | |
virtual decimal | GetBenchmarkValue (DateTime time) |
Gets the current benchmark value More... | |
virtual void | SampleEquity (DateTime time) |
Sample the current equity of the strategy directly with time and using the current algorithm equity value in CurrentAlgorithmEquity More... | |
virtual void | SamplePerformance (DateTime time, decimal value) |
Sample the current daily performance directly with a time-value pair. More... | |
virtual void | SampleBenchmark (DateTime time, decimal value) |
Sample the current benchmark performance directly with a time-value pair. More... | |
virtual void | SampleDrawdown (DateTime time, decimal currentPortfolioValue) |
Sample drawdown of equity of the strategy More... | |
virtual void | SamplePortfolioTurnover (DateTime time, decimal currentPortfolioValue) |
Sample portfolio turn over of the strategy More... | |
virtual void | SampleSalesVolume (DateTime time) |
Sample assets sales volume More... | |
virtual void | SampleExposure (DateTime time, decimal currentPortfolioValue) |
Sample portfolio exposure long/short ratios by security type More... | |
SortedDictionary< string, string > | GetAlgorithmRuntimeStatistics (Dictionary< string, string > summary, CapacityEstimate capacityEstimate=null) |
Gets the algorithm runtime statistics More... | |
void | SetAlgorithmState (string error, string stack) |
Sets the algorithm state data More... | |
Dictionary< string, string > | GetAlgorithmState (DateTime? endTime=null) |
Gets the algorithm state data More... | |
StatisticsResults | GenerateStatisticsResults (Dictionary< string, Chart > charts, SortedDictionary< DateTime, decimal > profitLoss=null, CapacityEstimate estimatedStrategyCapacity=null) |
Will generate the statistics results and update the provided runtime statistics More... | |
int | TotalTradesCount () |
Helper method to get the total trade count statistic More... | |
StatisticsResults | GenerateStatisticsResults (CapacityEstimate estimatedStrategyCapacity=null) |
Calculates and gets the current statistics for the algorithm. It will use the current Charts and profit loss information calculated from the current transaction record to generate the results. More... | |
void | ProcessAlgorithmLogs (int? messageQueueLimit=null) |
Processes algorithm logs. Logs of the same type are batched together one per line and are sent out More... | |
void | SummaryStatistic (string name, string value) |
Sets or updates a custom summary statistic More... | |
void | UpdateAlgorithmEquity () |
Updates the current equity bar with the current equity value from GetPortfolioValue More... | |
Properties | |
Dictionary< string, string > | FinalStatistics [get] |
A dictionary containing summary statistics More... | |
Properties inherited from QuantConnect.Lean.Engine.Results.BaseResultsHandler | |
virtual TimeSpan | MainUpdateInterval = TimeSpan.FromSeconds(3) [get] |
The main loop update interval More... | |
TimeSpan | ChartUpdateInterval = TimeSpan.FromMinutes(1) [get, set] |
The chart update interval More... | |
int | LastDeltaOrderPosition [get, set] |
The last position consumed from the ITransactionHandler.OrderEvents by GetDeltaOrders More... | |
int | LastDeltaOrderEventsPosition [get, set] |
The last position consumed from the ITransactionHandler.OrderEvents while determining delta order events More... | |
JsonSerializerSettings | SerializerSettings [get, set] |
Serializer settings to use More... | |
Bar | CurrentAlgorithmEquity [get, set] |
The current aggregated equity bar for sampling. It will be aggregated with values from the GetPortfolioValue More... | |
ConcurrentQueue< Packet > | Messages [get, set] |
Live packet messaging queue. Queue the messages here and send when the result queue is ready. More... | |
ConcurrentDictionary< string, Chart > | Charts [get, set] |
Storage for the price and equity charts of the live results. More... | |
ManualResetEvent | ExitEvent [get] |
Event set when exit is triggered More... | |
List< LogEntry > | LogStore [get] |
The log store instance More... | |
List< string > | AlgorithmPerformanceCharts = new List<string> { StrategyEquityKey, BenchmarkKey } [get] |
Algorithms performance related chart names More... | |
object | ChartLock [get] |
Lock to be used when accessing the chart collection More... | |
int | ProjectId [get, set] |
The algorithm project id More... | |
string | RamAllocation [get, set] |
The maximum amount of RAM (in MB) this algorithm is allowed to utilize More... | |
string | CompileId [get, set] |
The algorithm unique compilation id More... | |
string | AlgorithmId [get, set] |
The algorithm job id. This is the deploy id for live, backtesting id for backtesting More... | |
DateTime | StartTime [get] |
The result handler start time More... | |
Dictionary< string, string > | RuntimeStatistics [get] |
Customizable dynamic statistics IAlgorithm.RuntimeStatistics More... | |
Dictionary< string, string > | State [get, set] |
State of the algorithm More... | |
IMessagingHandler | MessagingHandler [get, set] |
The handler responsible for communicating messages to listeners More... | |
ITransactionHandler | TransactionHandler [get, set] |
The transaction handler used to get the algorithms Orders information More... | |
decimal | StartingPortfolioValue [get, set] |
The algorithms starting portfolio value. Used to calculate the portfolio return More... | |
virtual IAlgorithm | Algorithm [get, set] |
The algorithm instance More... | |
string | AlgorithmCurrencySymbol [get, set] |
Algorithm currency symbol, used in charting More... | |
decimal | DailyPortfolioValue [get, set] |
Closing portfolio value. Used to calculate daily performance. More... | |
decimal | CumulativeMaxPortfolioValue [get, set] |
Cumulative max portfolio value. Used to calculate drawdown underwater. More... | |
TimeSpan | ResamplePeriod [get, set] |
Sampling period for timespans between resamples of the charting equity. More... | |
TimeSpan | NotificationPeriod [get, set] |
How frequently the backtests push messages to the browser. More... | |
string | ResultsDestinationFolder [get, set] |
Directory location to store results More... | |
IMapFileProvider | MapFileProvider [get, set] |
The map file provider instance to use More... | |
Properties inherited from QuantConnect.Lean.Engine.Results.IResultHandler | |
ConcurrentQueue< Packet > | Messages [get, set] |
Put messages to process into the queue so they are processed by this thread. More... | |
bool | IsActive [get] |
Boolean flag indicating the result hander thread is busy. False means it has completely finished and ready to dispose. More... | |
Additional Inherited Members | |
Public Attributes inherited from QuantConnect.Lean.Engine.Results.BaseResultsHandler | |
bool | IsActive => _updateRunner != null && _updateRunner.IsAlive |
Boolean flag indicating the thread is still active. More... | |
Static Public Attributes inherited from QuantConnect.Lean.Engine.Results.BaseResultsHandler | |
const string | StrategyEquityKey = "Strategy Equity" |
String message saying: Strategy Equity More... | |
const string | EquityKey = "Equity" |
String message saying: Equity More... | |
const string | ReturnKey = "Return" |
String message saying: Return More... | |
const string | BenchmarkKey = "Benchmark" |
String message saying: Benchmark More... | |
const string | DrawdownKey = "Drawdown" |
String message saying: Drawdown More... | |
const string | PortfolioTurnoverKey = "Portfolio Turnover" |
String message saying: PortfolioTurnover More... | |
const string | PortfolioMarginKey = "Portfolio Margin" |
String message saying: Portfolio Margin More... | |
const string | AssetsSalesVolumeKey = "Assets Sales Volume" |
String message saying: Portfolio Margin More... | |
Protected Attributes inherited from QuantConnect.Lean.Engine.Results.BaseResultsHandler | |
volatile bool | ExitTriggered |
True if the exit has been triggered More... | |
Backtesting result handler passes messages back from the Lean to the User.
Definition at line 36 of file BacktestingResultHandler.cs.
QuantConnect.Lean.Engine.Results.BacktestingResultHandler.BacktestingResultHandler | ( | ) |
Creates a new instance
Definition at line 70 of file BacktestingResultHandler.cs.
|
virtual |
Initialize the result handler with this result packet.
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 85 of file BacktestingResultHandler.cs.
|
protectedvirtual |
The main processing method steps through the messaging queue and processes the messages one by one.
Implements QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 102 of file BacktestingResultHandler.cs.
|
virtual |
Run over all the data and break it into smaller packets to ensure they all arrive at the terminal
Definition at line 248 of file BacktestingResultHandler.cs.
|
protectedvirtual |
Save the snapshot of the total results to storage.
packet | Packet to store. |
Implements QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 281 of file BacktestingResultHandler.cs.
|
protected |
Send a final analysis result back to the IDE.
Definition at line 336 of file BacktestingResultHandler.cs.
|
virtual |
Set the Algorithm instance for ths result.
algorithm | Algorithm we're working on. |
startingPortfolioValue | Algorithm starting capital for statistics calculations |
While setting the algorithm the backtest result handler.
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 400 of file BacktestingResultHandler.cs.
|
virtual |
Handles updates to the algorithm's name
name | The new name |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 439 of file BacktestingResultHandler.cs.
|
virtual |
Sends a packet communicating an update to the algorithm's tags
tags | The new tags |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 448 of file BacktestingResultHandler.cs.
|
virtual |
Send a debug message back to the browser console.
message | Message we'd like shown in console. |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 457 of file BacktestingResultHandler.cs.
|
virtual |
Send a system debug message back to the browser console.
message | Message we'd like shown in console. |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 467 of file BacktestingResultHandler.cs.
|
virtual |
Send a logging message to the log list for storage.
message | Message we'd in the log. |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 477 of file BacktestingResultHandler.cs.
|
protectedvirtual |
Add message to LogStore
message | Message to add |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 487 of file BacktestingResultHandler.cs.
|
virtual |
Send list of security asset types the algorithm uses to browser.
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 499 of file BacktestingResultHandler.cs.
|
virtual |
Send an error message back to the browser highlighted in red with a stacktrace.
message | Error message we'd like shown in console. |
stacktrace | Stacktrace information string |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 513 of file BacktestingResultHandler.cs.
|
virtual |
Send a runtime error message back to the browser highlighted with in red
message | Error message. |
stacktrace | Stacktrace information string |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 526 of file BacktestingResultHandler.cs.
|
virtual |
Process brokerage message events
brokerageMessageEvent | The brokerage message event |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 538 of file BacktestingResultHandler.cs.
|
protectedvirtual |
Add a sample to the chart specified by the chartName, and seriesName.
chartName | String chart name to place the sample. |
seriesIndex | Type of chart we should create if it doesn't already exist. |
seriesName | Series name for the chart. |
seriesType | Series type for the chart. |
value | Value for the chart sample. |
unit | Unit of the sample |
Implements QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 552 of file BacktestingResultHandler.cs.
|
protectedvirtual |
Sample estimated strategy capacity
time | Time of the sample |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 593 of file BacktestingResultHandler.cs.
|
protected |
Add a range of samples from the users algorithms to the end of our current list.
updates | Chart updates since the last request. |
Definition at line 604 of file BacktestingResultHandler.cs.
|
virtual |
Terminate the result thread and apply any required exit procedures like sending final results.
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 672 of file BacktestingResultHandler.cs.
|
virtual |
Send an algorithm status update to the browser.
status | Status enum value. |
message | Additional optional status message. |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 705 of file BacktestingResultHandler.cs.
|
virtual |
Set the current runtime statistics of the algorithm. These are banner/title statistics which show at the top of the live trading results.
key | Runtime headline statistic name |
value | Runtime headline statistic value |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 717 of file BacktestingResultHandler.cs.
|
virtual |
Handle order event
newEvent | Event to process |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 729 of file BacktestingResultHandler.cs.
|
virtual |
Process the synchronous result events, sampling and message reading. This method is triggered from the algorithm manager thread.
Prime candidate for putting into a base class. Is identical across all result handlers.
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 739 of file BacktestingResultHandler.cs.
|
protectedvirtual |
Configures the Console.Out and Console.Error TextWriter instances. By default, we forward Console.WriteLine(string) to IAlgorithm.Debug. This is perfect for running in the cloud, but since they're processed asynchronously, the ordering of these messages with respect to Log messages is broken. This can lead to differences in regression test logs based solely on the ordering of messages. To disable this forwarding, set
"forward-console-messages"
to false
in the configuration.
Reimplemented in QuantConnect.Lean.Engine.Results.RegressionResultHandler.
Definition at line 781 of file BacktestingResultHandler.cs.
StatisticsResults QuantConnect.Lean.Engine.Results.BacktestingResultHandler.StatisticsResults | ( | ) |
Calculates and gets the current statistics for the algorithm
Implements QuantConnect.Statistics.IStatisticsService.
Definition at line 801 of file BacktestingResultHandler.cs.
void QuantConnect.Lean.Engine.Results.BacktestingResultHandler.SetSummaryStatistic | ( | string | name, |
string | value | ||
) |
Sets or updates a custom summary statistic
name | The statistic name |
value | The statistic value |
Implements QuantConnect.Statistics.IStatisticsService.
Definition at line 811 of file BacktestingResultHandler.cs.
|
get |
A dictionary containing summary statistics
Definition at line 65 of file BacktestingResultHandler.cs.