Lean
$LEAN_TAG$
|
Live trading result handler implementation passes the messages to the QC live trading interface. More...
Public Member Functions | |
LiveTradingResultHandler () | |
Creates a new instance More... | |
override void | Initialize (ResultHandlerInitializeParameters parameters) |
Initialize the result handler with this result packet. More... | |
void | DebugMessage (string message) |
Send a live trading debug message to the live console. More... | |
void | SystemDebugMessage (string message) |
Send a live trading system debug message to the live console. More... | |
void | LogMessage (string message) |
Log string messages and send them to the console. More... | |
void | ErrorMessage (string message, string stacktrace="") |
Send an error message back to the browser console and highlight it read. More... | |
void | SecurityType (List< SecurityType > types) |
Send a list of secutity types that the algorithm trades to the browser to show the market clock - is this market open or closed! More... | |
virtual void | RuntimeError (string message, string stacktrace="") |
Send a runtime error back to the users browser and highlight it red. More... | |
virtual void | BrokerageMessage (BrokerageMessageEvent brokerageMessageEvent) |
Process brokerage message events More... | |
virtual void | SetAlgorithm (IAlgorithm algorithm, decimal startingPortfolioValue) |
Set the algorithm of the result handler after its been initialized. More... | |
void | SendStatusUpdate (AlgorithmStatus status, string message="") |
Send a algorithm status update to the user of the algorithms running state. More... | |
void | RuntimeStatistic (string key, string value) |
Set a dynamic runtime statistic to show in the (live) algorithm header More... | |
override string | SaveLogs (string id, List< LogEntry > logs) |
Process the log entries and save it to permanent storage More... | |
override void | OrderEvent (OrderEvent newEvent) |
New order event for the algorithm More... | |
override void | Exit () |
Terminate the result thread and apply any required exit procedures like sending final results 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... | |
override void | OnSecuritiesChanged (SecurityChanges changes) |
Event fired each time that we add/remove securities from the data feed. On Security change we re determine when should we sample charts, if the user added Crypto, Forex or an extended market hours subscription we will always sample charts. Else, we will keep the exchange per market to query later on demand More... | |
void | Sample (DateTime time) |
Samples portfolio equity, benchmark, and daily performance 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... | |
virtual void | AlgorithmNameUpdated (string name) |
Handles updates to the algorithm's name More... | |
virtual void | AlgorithmTagsUpdated (HashSet< string > tags) |
Handles updates to the algorithm's tags More... | |
Public Member Functions inherited from QuantConnect.Lean.Engine.Results.BaseResultsHandler | |
virtual void | SaveResults (string name, Result result) |
Save the results to disk More... | |
Public Member Functions inherited from QuantConnect.Lean.Engine.Results.IResultHandler | |
void | SaveResults (string name, Result result) |
Save the results More... | |
Static Public Member Functions | |
static Dictionary< string, Holding > | GetHoldings (IEnumerable< Security > securities, ISubscriptionDataConfigService subscriptionDataConfigService, bool onlyInvested=false) |
Helper method to fetch the algorithm holdings More... | |
Protected Member Functions | |
override void | Run () |
Live trading result handler thread. More... | |
virtual void | SetNextStatusUpdate () |
Assigns the next earliest status update time More... | |
override void | StoreOrderEvents (DateTime utcTime, List< OrderEvent > orderEvents) |
Stores the order events More... | |
override void | AddToLogStore (string message) |
Save an algorithm message to the log store. Uses a different timestamped method of adding messaging to interweve debug and logging messages. 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... | |
void | SampleRange (IEnumerable< Chart > updates) |
Add a range of samples from the users algorithms to the end of our current list. More... | |
void | SendFinalResult () |
Send a final analysis result back to the IDE. More... | |
override void | StoreResult (Packet packet) |
Save the snapshot of the total results to storage. More... | |
virtual string | CreateSafeChartName (string chartName) |
Escape the chartname so that it can be saved to a file system More... | |
override decimal | GetPortfolioValue () |
Gets the current portfolio value More... | |
override decimal | GetBenchmarkValue (DateTime time) |
Gets the current benchmark value 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 | 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 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... | |
virtual void | SampleCapacity (DateTime time) |
Sample estimated strategy capacity 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... | |
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... | |
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... | |
Live trading result handler implementation passes the messages to the QC live trading interface.
Live trading result handler is quite busy. It sends constant price updates, equity updates and order/holdings updates.
Definition at line 45 of file LiveTradingResultHandler.cs.
QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.LiveTradingResultHandler | ( | ) |
Creates a new instance
Definition at line 89 of file LiveTradingResultHandler.cs.
|
virtual |
Initialize the result handler with this result packet.
parameters | DTO parameters class to initialize a result handler |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 107 of file LiveTradingResultHandler.cs.
|
protectedvirtual |
Live trading result handler thread.
Implements QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 122 of file LiveTradingResultHandler.cs.
|
protectedvirtual |
Assigns the next earliest status update time
Definition at line 380 of file LiveTradingResultHandler.cs.
|
protectedvirtual |
Stores the order events
utcTime | The utc date associated with these order events |
orderEvents | The order events to store |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 391 of file LiveTradingResultHandler.cs.
void QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.DebugMessage | ( | string | message | ) |
Send a live trading debug message to the live console.
message | Message we'd like shown in console. |
When there are already 500 messages in the queue it stops adding new messages.
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 540 of file LiveTradingResultHandler.cs.
void QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.SystemDebugMessage | ( | string | message | ) |
Send a live trading system debug message to the live console.
message | Message we'd like shown in console. |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 551 of file LiveTradingResultHandler.cs.
void QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.LogMessage | ( | string | message | ) |
Log string messages and send them to the console.
message | String message wed like logged. |
When there are already 500 messages in the queue it stops adding new messages.
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 563 of file LiveTradingResultHandler.cs.
|
protectedvirtual |
Save an algorithm message to the log store. Uses a different timestamped method of adding messaging to interweve debug and logging messages.
message | String message to send to browser. |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 575 of file LiveTradingResultHandler.cs.
void QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.ErrorMessage | ( | string | message, |
string | stacktrace = "" |
||
) |
Send an error message back to the browser console and highlight it read.
message | Message we'd like shown in console. |
stacktrace | Stacktrace to show in the console. |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 587 of file LiveTradingResultHandler.cs.
void QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.SecurityType | ( | List< SecurityType > | types | ) |
Send a list of secutity types that the algorithm trades to the browser to show the market clock - is this market open or closed!
types | List of security types |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 598 of file LiveTradingResultHandler.cs.
|
virtual |
Send a runtime error back to the users browser and highlight it red.
message | Runtime error message |
stacktrace | Associated error stack trace. |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 609 of file LiveTradingResultHandler.cs.
|
virtual |
Process brokerage message events
brokerageMessageEvent | The brokerage message event |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 620 of file LiveTradingResultHandler.cs.
|
protectedvirtual |
Add a sample to the chart specified by the chartName, and seriesName.
chartName | String chart name to place the sample. |
seriesName | Series name for the chart. |
seriesIndex | Series chart index - which chart should this series belong |
seriesType | Series type for the chart. |
value | Value for the chart sample. |
unit | Unit for the chart axis |
Sample can be used to create new charts or sample equity - daily performance.
Implements QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 635 of file LiveTradingResultHandler.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 672 of file LiveTradingResultHandler.cs.
|
virtual |
Set the algorithm of the result handler after its been initialized.
algorithm | Algorithm object matching IAlgorithm interface |
startingPortfolioValue | Algorithm starting capital for statistics calculations |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 718 of file LiveTradingResultHandler.cs.
void QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.SendStatusUpdate | ( | AlgorithmStatus | status, |
string | message = "" |
||
) |
Send a algorithm status update to the user of the algorithms running state.
status | Status enum of the algorithm. |
message | Optional string message describing reason for status change. |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 755 of file LiveTradingResultHandler.cs.
void QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.RuntimeStatistic | ( | string | key, |
string | value | ||
) |
Set a dynamic runtime statistic to show in the (live) algorithm header
key | Runtime headline statistic name |
value | Runtime headline statistic value |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 768 of file LiveTradingResultHandler.cs.
|
protected |
Send a final analysis result back to the IDE.
Definition at line 785 of file LiveTradingResultHandler.cs.
|
virtual |
Process the log entries and save it to permanent storage
id | Id that will be incorporated into the algorithm log name |
logs | Log list |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 853 of file LiveTradingResultHandler.cs.
|
protectedvirtual |
Save the snapshot of the total results to storage.
packet | Packet to store. |
Implements QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 874 of file LiveTradingResultHandler.cs.
|
virtual |
New order event for the algorithm
newEvent | New event details |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 964 of file LiveTradingResultHandler.cs.
|
virtual |
Terminate the result thread and apply any required exit procedures like sending final results
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 981 of file LiveTradingResultHandler.cs.
|
protectedvirtual |
Escape the chartname so that it can be saved to a file system
chartName | The name of a chart |
Definition at line 1054 of file LiveTradingResultHandler.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.
Definition at line 1064 of file LiveTradingResultHandler.cs.
|
virtual |
Event fired each time that we add/remove securities from the data feed. On Security change we re determine when should we sample charts, if the user added Crypto, Forex or an extended market hours subscription we will always sample charts. Else, we will keep the exchange per market to query later on demand
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 1149 of file LiveTradingResultHandler.cs.
|
virtual |
Samples portfolio equity, benchmark, and daily performance
time | Current UTC time in the AlgorithmManager loop |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 1187 of file LiveTradingResultHandler.cs.
|
protectedvirtual |
Gets the current portfolio value
Useful so that live trading implementation can freeze the returned value if there is no user exchange open so we ignore extended market hours updates
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 1200 of file LiveTradingResultHandler.cs.
|
protectedvirtual |
Gets the current benchmark value
Useful so that live trading implementation can freeze the returned value if there is no user exchange open so we ignore extended market hours updates
time | Time to resolve benchmark value at |
Reimplemented from QuantConnect.Lean.Engine.Results.BaseResultsHandler.
Definition at line 1211 of file LiveTradingResultHandler.cs.
|
static |
Helper method to fetch the algorithm holdings
Definition at line 1299 of file LiveTradingResultHandler.cs.
StatisticsResults QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.StatisticsResults | ( | ) |
Calculates and gets the current statistics for the algorithm
Implements QuantConnect.Statistics.IStatisticsService.
Definition at line 1321 of file LiveTradingResultHandler.cs.
void QuantConnect.Lean.Engine.Results.LiveTradingResultHandler.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 1331 of file LiveTradingResultHandler.cs.
|
virtual |
Handles updates to the algorithm's name
name | The new name |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 1340 of file LiveTradingResultHandler.cs.
|
virtual |
Handles updates to the algorithm's tags
tags | The new tags |
Implements QuantConnect.Lean.Engine.Results.IResultHandler.
Definition at line 1349 of file LiveTradingResultHandler.cs.