Live Algorithms

Reading Results

Introduction

This page explains how to read the results from live trading algorithms in the research environment.

Prerequisites

Working knowledge of C#.

If you use Python, you must understand how to work with pandas DataFrames and Series. If you are not familiar with pandas, refer to the pandas documentation.

You'll need to understand how to do Project Management and Live Deployment Management through the QuantConnect Api.

Read Deployment Instance

Follow these steps to read a live-deploying algorithm instance by the QuantConnect Api.

  1. Load the required assembly files and data types.
  2. #load "../Initialize.csx"
    #load "../QuantConnect.csx"
    
    using QuantConnect;
    using QuantConnect.Api;
  3. Call ReadLiveAlgorithm with the project ID and deploy ID.
  4. var projectId = <yourProjectId>;
    var deployId = "<yourDeploymentId>";
    var liveAlgorithm = api.ReadLiveAlgorithm(projectId, deployId);
    project_id = <your_project_id>
    deploy_id = "<your_deployment_id>"
    live_algorithm = api.ReadLiveAlgorithm(project_id, deploy_id)
  5. Call Success attribute to check if the request is successful.
  6. Console.WriteLine($"{liveAlgorithm.Success}");
    print(live_algorithm.Success)
  7. Call LiveResults.Results attribute to obtain the live algorithm's results.
  8. In this tutorial, DefaultLiveAlgorithmSettings is used for using QuantConnect's paper trading. For other brokerages, please refer to LiveAlgorithmSettings.cs for reference.

    var results = liveAlgorithm.LiveResults.Results;
    results = live_algorithm.LiveResults.Results

Note that this would be a snapshot of the live algorithm at this instance. If more updated information is needed, you'll need to re-read it.

Asset Holdings

You need to understand how to Read Deployment Instance to read the asset holdings.

Follow these steps to read the securities and cash holdings of a live algorithm.

  1. Call Holdings and Cash attributes to retrieve the asset holdings.
  2. var holdings = results.Holdings;
    var cash = results.Cash;
    holdings = results.Holdings
    cash = results.Cash
  3. Display the assets holdings.
  4. foreach(var h in holdings.Values)
    {
        Console.WriteLine($@"{h.Symbol} 
        Quantity: {h.Quantity} 
        Average Price: {h.AveragePrice} 
        Market Price: {h.MarketPrice}
        Market Value: {h.MarketValue}
        ");
    }
    foreach(var c in cash.Values)
    {
        Console.WriteLine($"{c.Symbol}: {c.CurrencySymbol} {c.Amount}");
    }
    for h in holdings.Values:
        print(f"""{h.Symbol} 
        Quantity: {h.Quantity} 
        Average Price: {h.AveragePrice} 
        Market Price: {h.MarketPrice}
        Market Value: {h.MarketValue}
        """)
        
    for c in cash.Values:
        print(f"{c.Symbol}: {c.CurrencySymbol} {c.Amount}")

Statistics

You need to understand how to Read Deployment Instance to read the statistics.

Follow these steps to get the statistics of the live algorithm.

  1. Call Statistics attribute to display the statistics of the live algorithm.
  2. var statistics = results.Statistics;
    foreach(var kvp in statistics)
    {
        Console.WriteLine($"{kvp.Key}: {kvp.Value}");
    }
    statistics = results.Statistics
    for kvp in statistics:
        print(f"{kvp.Key}: {kvp.Value}")
  3. Call RuntimeStatistics attribute to display the runtime statistics of the live algorithm.
  4. var runtimeStatistics = results.RuntimeStatistics;
    foreach(var kvp in runtimeStatistics)
    {
        Console.WriteLine($"{kvp.Key}: {kvp.Value}");
    }
    runtime_statistics = results.RuntimeStatistics
    for kvp in runtime_statistics:
        print(f"{kvp.Key}: {kvp.Value}")
  5. Call AlphaRuntimeStatistics attribute to display the alpha runtime statistics of the live algorithm.
  6. var alphaStatistics = results.AlphaRuntimeStatistics.ToDictionary();
    foreach(var kvp in alphaStatistics)
    {
        Console.WriteLine($"{kvp.Key}: {kvp.Value}");
    }
    alpha_statistics = results.AlphaRuntimeStatistics.ToDictionary()
    for kvp in alpha_statistics:
        print(f"{kvp.Key}: {kvp.Value}")

Orders

You need to understand how to Read Deployment Instance to read the orders.

Follow these steps to read the orders and order events of a live algorithm.

  1. Call Orders attribute to read the orders.
  2. var orders = results.Orders;
    foreach(var o in orders.Values)
    {
        Console.WriteLine($"{o.LastFillTime}: {o.Direction} {o.Symbol.Value} Type: {o.Type} Price: {o.Price} Quantity: {o.Quantity}");
    }
    direction = {1: "Buy", 2: "Sell", 3: "Hold"}
    type_ = {1: "Market", 2: "Limit", 3: "Stop Market", 4: "Stop Limit", 5: "Market On Open", 6: "Market On Close", 7: "Option Exercise"}
    
    orders = results.Orders
    for o in orders.Values:
        print(f"{o.LastFillTime.strftime('%Y/%m/%d %H:%M:%S')}: {direction[o.Direction]} {o.Symbol.Value} Type: {type_[o.Type]} Price: {o.Price} Quantity: {o.Quantity}")
  3. Call OrderEvents attribute to read the order events.
  4. var orderEvents = results.OrderEvents;
    foreach(var o in orderEvents)
    {
        Console.WriteLine($"{o.UtcTime}: {o.Direction} {o.Symbol.Value} Price: {o.FillPrice} Quantity: {o.FillQuantity} Fee: {o.OrderFee}");
    }
    orderEvents = results.OrderEvents;
    for o in orderEvents:
        print(f"{o.UtcTime}: {direction[o.Direction]} {o.Symbol.Value} Price: {o.FillPrice} Quantity: {o.FillQuantity} Fee: {o.OrderFee}")

Charts

You need to understand how to Read Deployment Instance to read the charts.

Follow these steps to read chart data of a backtest.

Follow these steps to read and plot chart data of a backtest.

  1. Call Charts attribute of the live algorithm.
  2. var charts = results.Charts;
    charts = results.Charts
  3. Hash the chart's name to obtain a particular chart's data.
  4. var equityChart = charts["Strategy Equity"];
    equity_chart = charts["Strategy Equity"]
  5. Call Series attribute of the charts, then hash with the name of the desired series to obtain particular series's data.
  6. var equitySeries = equityChart.Series["Equity"].Values;
    equity_series = equity_chart.Series["Equity"].Values
  7. Iterate each data point of each series, store them in (nested) Dictionary.
  8. var equityData = equitySeries
                     .Where(kvp => kvp != null)
                     .ToDictionary(kvp => kvp.x, kvp => kvp.y);
    equity_data = {kvp.x: kvp.y for kvp in equity_series if kvp}
  9. Display the data.
  10. Console.WriteLine("Equity Curve:");
    foreach(var kvp in equityData.Take(5))
    {
        var time = DateTimeOffset.FromUnixTimeSeconds(kvp.Key).DateTime;
        Console.WriteLine($"{time} : {kvp.Value}");
    }
  11. Convert the dictionaries into pandas.Series.
  12. equity_data = pd.Series(equity_data)
  13. Call plot to plot the data.
  14. equity_data.plot(figsize=(10, 6), title="Equity Curve")
    plt.show()

Read Logs

Follow these steps to read the logs from a live algorithm by using the QuantConnect Api.

  1. Call ReadLiveLogs with the project ID, deploy ID, (optional) start and (optional) end time of the logs.
  2. var liveLogs = api.ReadLiveLogs(projectId: projectId, 
                                    algorithmId: deployId,
                                    startTime: new DateTime(2022, 1, 31),
                                    endTime: new DateTime(2022, 2, 3));
    liveLogs = api.ReadLiveLogs(projectId=project_id, 
                                algorithmId=deploy_id,
                                startTime=datetime(2022, 1, 31),
                                endTime=datetime(2022, 2, 3))
  3. Call Logs attribute to get the logs message.
  4. var logs = liveLogs.Logs;
    logs = liveLogs.Logs
  5. Display the logs.
  6. foreach(var l in logs.Take(5))
    {
        Console.WriteLine(l);
    }
    for l in logs[:5]:
        print(l)

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: