---
title: "Create Backtest"
description: "Create a new backtest request and get the backtest Id."
canonical: https://www.quantconnect.com/docs/v2/cloud-platform/api-reference/backtest-management/create-backtest
markdown: https://www.quantconnect.com/docs/v2/cloud-platform/api-reference/backtest-management/create-backtest.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/01%20Cloud%20Platform/99%20API%20Reference/05%20Backtest%20Management/01%20Create%20Backtest
modified: 2026-10-29
index: https://www.quantconnect.com/llms.txt
---

# Create Backtest

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Cloud Platform](https://www.quantconnect.com/docs/v2/cloud-platform.md) > [API Reference](https://www.quantconnect.com/docs/v2/cloud-platform/api-reference.md) > [Backtest Management](https://www.quantconnect.com/docs/v2/cloud-platform/api-reference/backtest-management.md) > Create Backtest

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## Introduction

Create a new backtest request and get the backtest Id.

## Request

Create a new backtest given a project Id and compile Id. The `/backtests/create` API accepts requests in the following format:

| `CreateBacktestRequest` Model - Request to create a new backtest. |  |
| --- | --- |
| projectId | `integer required example: 23456789` Id of the project to backtest. |
| compileId | `string required example: 5d1f2cba3a0ec7407c566614300502b5-173e0419674daf4144ce7c9931155ca8` Compile Id for the project to backtest. |
| backtestName | `string required example: New Backtest` Name for the new backtest. |
| parameters | `string/number/integer object` Parameters to use for the backtest. |
| Example | `{ "projectId": 23456789, "compileId": "5d1f2cba3a0ec7407c566614300502b5-173e0419674daf4144ce7c9931155ca8", "backtestName": "New Backtest", "parameters": { "key": 0 } }` |

## Responses

The `/backtests/create` API provides a response in the following format:

### 200 Success

| `BacktestResponse` Model - Collection container for a list of backtests for a project. |  |
| --- | --- |
| backtest | `BacktestResult object` Results object class. Results are exhaust from backtest or live algorithms running in LEAN. |
| debugging | `boolean` Indicates if the backtest is run under debugging mode. |
| success | `boolean` Indicate if the API request was successful. |
| errors | `string Array` List of errors with the API call. |
| Example | `{ "backtest": { "note": "string", "name": "string", "organizationId": "d6d62db48592c72e67b534553413b602", "projectId": 23456789, "completed": true, "optimizationId": "O-401d3d40b5a0e9f8c46c954a303f3ddd", "backtestId": "26c7bb06b8487cff1c7b3c44652b30f1", "tradeableDates": 0, "researchGuide": { "minutes": 0, "backtestCount": 0, "parameters": 0 }, "backtestStart": "2021-11-26T15:18:27.693Z", "backtestEnd": "2021-11-26T15:18:27.693Z", "created": "2021-11-26T15:18:27.693Z", "snapshotId": 0, "status": "Completed.", "error": "string", "stacktrace": "string", "progress": 0, "hasInitializeError": true, "charts": { "name": "string" }, "parameterSet": , "rollingWindow": { }, "runtimeStatistics": { "Equity": "$100.00", "Fees": "-$100.00", "Holdings": "$100.00", "Net Profit": "$100.00", "Probabilistic Sharpe Ratio": "50.00%", "Return": "50.00%", "Unrealized": "$100.00", "Volume": "$100.00" }, "serverStatistics": { "CPU Usage": "0.0%", "Used RAM (MB)": "241", "Total RAM (MB)": "16384", "Hostname": "BACKTESTING-48-b663526eb061eda8efa07d9bde55c24f", "LEAN Version": "v2.5.0.0.18009", "Up Time": "0d 00:00:03" }, "statistics": { "Total Orders": "string", "Average Win": "string", "Average Loss": "string", "Compounding Annual Return": "string", "Drawdown": "string", "Expectancy": "string", "Start Equity": "string", "End Equity": "string", "Net Profit": "string", "Sharpe Ratio": "string", "Sortino Ratio": "string", "Probabilistic Sharpe Ratio": "string", "Loss Rate": "string", "Win Rate": "string", "Profit-Loss Ratio": "string", "Alpha": "string", "Beta": "string", "Annual Standard Deviation": "string", "Annual Variance": "string", "Information Ratio": "string", "Tracking Error": "string", "Treynor Ratio": "string", "Total Fees": "string", "Estimated Strategy Capacity": "string", "Lowest Capacity Asset": "string", "Portfolio Turnover": "string", "Drawdown Recovery": "string" }, "totalPerformance": { "tradeStatistics": { "startDateTime": "2021-11-26T15:18:27.693Z", "endDateTime": "2021-11-26T15:18:27.693Z", "totalNumberOfTrades": 0, "numberOfWinningTrades": 0, "numberOfLosingTrades": 0, "totalProfitLoss": "string", "totalProfit": "string", "totalLoss": "string", "largestProfit": "string", "largestLoss": "string", "averageProfitLoss": "string", "averageProfit": "string", "averageLoss": "string", "averageTradeDuration": "string", "averageWinningTradeDuration": "string", "averageLosingTradeDuration": "string", "medianTradeDuration": "string", "medianWinningTradeDuration": "string", "medianLosingTradeDuration": "string", "maxConsecutiveWinningTrades": 0, "maxConsecutiveLosingTrades": 0, "profitLossRatio": "string", "winLossRatio": "string", "winRate": "string", "lossRate": "string", "averageMAE": "string", "averageMFE": "string", "largestMAE": "string", "largestMFE": "string", "maximumClosedTradeDrawdown": "string", "maximumIntraTradeDrawdown": "string", "profitLossStandardDeviation": "string", "profitLossDownsideDeviation": "string", "profitFactor": "string", "sharpeRatio": "string", "sortinoRatio": "string", "profitToMaxDrawdownRatio": "string", "maximumEndTradeDrawdown": "string", "averageEndTradeDrawdown": "string", "maximumDrawdownDuration": "string", "totalFees": "string" }, "portfolioStatistics": { "averageWinRate": "string", "averageLossRate": "string", "profitLossRatio": "string", "winRate": "string", "lossRate": "string", "expectancy": "string", "startEquity": "string", "endEquity": "string", "compoundingAnnualReturn": "string", "drawdown": "string", "totalNetProfit": "string", "sharpeRatio": "string", "probabilisticSharpeRatio": "string", "sortinoRatio": "string", "alpha": "string", "beta": "string", "annualStandardDeviation": "string", "annualVariance": "string", "informationRatio": "string", "trackingError": "string", "treynorRatio": "string", "portfolioTurnover": "string", "valueAtRisk99": "string", "valueAtRisk95": "string", "drawdownRecovery": "string" }, "closedTrades": [ { "id": "e1936b18-446b-4d57-95a6-6fd1a420e261", "symbols": [ { "value": "string", "id": "string", "permtick": "string" } ], "entryTime": "2021-11-26T15:18:27.693Z", "entryPrice": 0, "direction": 0, "quantity": 0, "exitTime": "2021-11-26T15:18:27.693Z", "exitPrice": 0, "profitLoss": 0, "totalFees": 0, "mae": 0, "mfe": 0, "duration": "string", "endTradeDrawdown": 0, "isWin": true, "orderIds": [ "integer" ] } ] }, "nodeName": "string", "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z", "outOfSampleDays": 0, "analysis": [ { "name": "PerformanceRelativeToBenchmarkAnalysis", "issue": "The strategy has a lower Sharpe ratio than the benchmark.", "sample": { "backtestSharpe": -0.2281345806218534, "benchmarkSharpe": -0.22182175736916387 }, "count": 5, "solutions": [ "Try adjusting the trading rules and/or the universe to get a strategy that outperforms the benchmark." ] } ] }, "debugging": true, "success": true, "errors": [ "string" ] }` |

| `BacktestResult` Model - Results object class. Results are exhaust from backtest or live algorithms running in LEAN. |  |
| --- | --- |
| note | `string` Note on the backtest attached by the user. |
| name | `string required` Name of the backtest. |
| organizationId | `string required example: d6d62db48592c72e67b534553413b602` The Id of the organization. |
| projectId | `integer required example: 23456789` Id of the project. |
| completed | `boolean required` Boolean true when the backtest is completed. |
| optimizationId | `string example: O-401d3d40b5a0e9f8c46c954a303f3ddd` Optimization task ID, if the backtest is part of an optimization. |
| backtestId | `string required example: 26c7bb06b8487cff1c7b3c44652b30f1` Assigned backtest ID. |
| tradeableDates | `integer required` Number of tradeable days in the backtest. |
| researchGuide | `ResearchGuide object` A power gauge for backtests, time and parameters to estimate the overfitting risk. |
| backtestStart | `string($date-time) required` The starting time of the backtest. |
| backtestEnd | `string($date-time) required` The ending time of the backtest. |
| created | `string($date-time) required` Backtest creation date and time. |
| snapshotId | `integer required` Snapshot Id of this backtest result. |
| status | `string Enum required` Status of the backtest. Options : ['Completed.', 'In Queue...', 'In Progress...', 'Runtime Error'] |
| error | `string required` Backtest error message. |
| stacktrace | `string required` Backtest error stacktrace. |
| progress | `number required` Progress of the backtest in percent 0-1. |
| hasInitializeError | `boolean` Indicates if the backtest has error during initialization. |
| charts | `ChartSummary object required` Charts updates for the live algorithm since the last result packet. |
| parameterSet | `ParameterSet object required` Parameters used in the backtest. |
| rollingWindow | `object` Rolling window detailed statistics. |
| runtimeStatistics | `RuntimeStatistics object required` Runtime banner/updating statistics in the title banner of the live algorithm GUI. |
| serverStatistics | `ServerStatistics object` Status of the node that ran the backtest, including its CPU and RAM usage. The available keys depend on the version of LEAN that produced the results. |
| statistics | `StatisticsResult object required` Statistics information sent during the algorithm operations. |
| totalPerformance | `AlgorithmPerformance object required` The AlgorithmPerformance class is a wrapper for TradeStatistics and PortfolioStatistics. |
| nodeName | `string required` The backtest node name. |
| outOfSampleMaxEndDate | `string($date-time)` End date of out of sample data. |
| outOfSampleDays | `integer` Number of days of out of sample days. |
| analysis | `AnalysisResult Array` /. |
| Example | `{ "note": "string", "name": "string", "organizationId": "d6d62db48592c72e67b534553413b602", "projectId": 23456789, "completed": true, "optimizationId": "O-401d3d40b5a0e9f8c46c954a303f3ddd", "backtestId": "26c7bb06b8487cff1c7b3c44652b30f1", "tradeableDates": 0, "researchGuide": { "minutes": 0, "backtestCount": 0, "parameters": 0 }, "backtestStart": "2021-11-26T15:18:27.693Z", "backtestEnd": "2021-11-26T15:18:27.693Z", "created": "2021-11-26T15:18:27.693Z", "snapshotId": 0, "status": "Completed.", "error": "string", "stacktrace": "string", "progress": 0, "hasInitializeError": true, "charts": { "name": "string" }, "parameterSet": , "rollingWindow": { }, "runtimeStatistics": { "Equity": "$100.00", "Fees": "-$100.00", "Holdings": "$100.00", "Net Profit": "$100.00", "Probabilistic Sharpe Ratio": "50.00%", "Return": "50.00%", "Unrealized": "$100.00", "Volume": "$100.00" }, "serverStatistics": { "CPU Usage": "0.0%", "Used RAM (MB)": "241", "Total RAM (MB)": "16384", "Hostname": "BACKTESTING-48-b663526eb061eda8efa07d9bde55c24f", "LEAN Version": "v2.5.0.0.18009", "Up Time": "0d 00:00:03" }, "statistics": { "Total Orders": "string", "Average Win": "string", "Average Loss": "string", "Compounding Annual Return": "string", "Drawdown": "string", "Expectancy": "string", "Start Equity": "string", "End Equity": "string", "Net Profit": "string", "Sharpe Ratio": "string", "Sortino Ratio": "string", "Probabilistic Sharpe Ratio": "string", "Loss Rate": "string", "Win Rate": "string", "Profit-Loss Ratio": "string", "Alpha": "string", "Beta": "string", "Annual Standard Deviation": "string", "Annual Variance": "string", "Information Ratio": "string", "Tracking Error": "string", "Treynor Ratio": "string", "Total Fees": "string", "Estimated Strategy Capacity": "string", "Lowest Capacity Asset": "string", "Portfolio Turnover": "string", "Drawdown Recovery": "string" }, "totalPerformance": { "tradeStatistics": { "startDateTime": "2021-11-26T15:18:27.693Z", "endDateTime": "2021-11-26T15:18:27.693Z", "totalNumberOfTrades": 0, "numberOfWinningTrades": 0, "numberOfLosingTrades": 0, "totalProfitLoss": "string", "totalProfit": "string", "totalLoss": "string", "largestProfit": "string", "largestLoss": "string", "averageProfitLoss": "string", "averageProfit": "string", "averageLoss": "string", "averageTradeDuration": "string", "averageWinningTradeDuration": "string", "averageLosingTradeDuration": "string", "medianTradeDuration": "string", "medianWinningTradeDuration": "string", "medianLosingTradeDuration": "string", "maxConsecutiveWinningTrades": 0, "maxConsecutiveLosingTrades": 0, "profitLossRatio": "string", "winLossRatio": "string", "winRate": "string", "lossRate": "string", "averageMAE": "string", "averageMFE": "string", "largestMAE": "string", "largestMFE": "string", "maximumClosedTradeDrawdown": "string", "maximumIntraTradeDrawdown": "string", "profitLossStandardDeviation": "string", "profitLossDownsideDeviation": "string", "profitFactor": "string", "sharpeRatio": "string", "sortinoRatio": "string", "profitToMaxDrawdownRatio": "string", "maximumEndTradeDrawdown": "string", "averageEndTradeDrawdown": "string", "maximumDrawdownDuration": "string", "totalFees": "string" }, "portfolioStatistics": { "averageWinRate": "string", "averageLossRate": "string", "profitLossRatio": "string", "winRate": "string", "lossRate": "string", "expectancy": "string", "startEquity": "string", "endEquity": "string", "compoundingAnnualReturn": "string", "drawdown": "string", "totalNetProfit": "string", "sharpeRatio": "string", "probabilisticSharpeRatio": "string", "sortinoRatio": "string", "alpha": "string", "beta": "string", "annualStandardDeviation": "string", "annualVariance": "string", "informationRatio": "string", "trackingError": "string", "treynorRatio": "string", "portfolioTurnover": "string", "valueAtRisk99": "string", "valueAtRisk95": "string", "drawdownRecovery": "string" }, "closedTrades": [ { "id": "e1936b18-446b-4d57-95a6-6fd1a420e261", "symbols": [ { "value": "string", "id": "string", "permtick": "string" } ], "entryTime": "2021-11-26T15:18:27.693Z", "entryPrice": 0, "direction": 0, "quantity": 0, "exitTime": "2021-11-26T15:18:27.693Z", "exitPrice": 0, "profitLoss": 0, "totalFees": 0, "mae": 0, "mfe": 0, "duration": "string", "endTradeDrawdown": 0, "isWin": true, "orderIds": [ "integer" ] } ] }, "nodeName": "string", "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z", "outOfSampleDays": 0, "analysis": [ { "name": "PerformanceRelativeToBenchmarkAnalysis", "issue": "The strategy has a lower Sharpe ratio than the benchmark.", "sample": { "backtestSharpe": -0.2281345806218534, "benchmarkSharpe": -0.22182175736916387 }, "count": 5, "solutions": [ "Try adjusting the trading rules and/or the universe to get a strategy that outperforms the benchmark." ] } ] }` |

| `ResearchGuide` Model - A power gauge for backtests, time and parameters to estimate the overfitting risk. |  |
| --- | --- |
| minutes | `integer` Number of minutes used in developing the current backtest. |
| backtestCount | `integer` The quantity of backtests run in the project. |
| parameters | `integer` Number of parameters detected. |
| Example | `{ "minutes": 0, "backtestCount": 0, "parameters": 0 }` |

| `ChartSummary` Model - Contains the names of all charts |  |
| --- | --- |
| name | `string` Name of the Chart. |
| Example | `{ "name": "string" }` |

| `RuntimeStatistics` Model |  |
| --- | --- |
| Equity | `string example: $100.00` Total portfolio value. |
| Fees | `string example: -$100.00` Transaction fee. |
| Holdings | `string example: $100.00` Equity value of security holdings. |
| Net Profit | `string example: $100.00` Net profit. |
| Probabilistic Sharpe Ratio | `string example: 50.00%` Probabilistic Sharpe Ratio. |
| Return | `string example: 50.00%` Return. |
| Unrealized | `string example: $100.00` Unrealized profit/loss. |
| Volume | `string example: $100.00` Total transaction volume. |
| Example | `{ "Equity": "$100.00", "Fees": "-$100.00", "Holdings": "$100.00", "Net Profit": "$100.00", "Probabilistic Sharpe Ratio": "50.00%", "Return": "50.00%", "Unrealized": "$100.00", "Volume": "$100.00" }` |

| `ServerStatistics` Model |  |
| --- | --- |
| CPU Usage | `string example: 0.0%` Percentage of the node CPU in use. |
| Used RAM (MB) | `string example: 241` RAM the algorithm uses, in megabytes. |
| Total RAM (MB) | `string example: 16384` RAM the node provides, in megabytes. |
| Hostname | `string example: BACKTESTING-48-b663526eb061eda8efa07d9bde55c24f` Name of the machine that runs the algorithm, which starts with the type of deployment. |
| LEAN Version | `string example: v2.5.0.0.18009` Version of LEAN that runs the algorithm. |
| Up Time | `string example: 0d 00:00:03` Time the node has been running, in days, hours, minutes, and seconds. |
| Example | `{ "CPU Usage": "0.0%", "Used RAM (MB)": "241", "Total RAM (MB)": "16384", "Hostname": "BACKTESTING-48-b663526eb061eda8efa07d9bde55c24f", "LEAN Version": "v2.5.0.0.18009", "Up Time": "0d 00:00:03" }` |

| `StatisticsResult` Model - Statistics information sent during the algorithm operations. |  |
| --- | --- |
| Total Orders | `string` Total nuber of orders. |
| Average Win | `string` The average rate of return for winning trades. |
| Average Loss | `string` The average rate of return for losing trades. |
| Compounding Annual Return | `string` Annual compounded returns statistic based on the final-starting capital and years. |
| Drawdown | `string` Drawdown maximum percentage. |
| Expectancy | `string` The expected value of the rate of return. |
| Start Equity | `string` Initial Equity Total Value. |
| End Equity | `string` Final Equity Total Value. |
| Net Profit | `string` The total net profit percentage. |
| Sharpe Ratio | `string` Sharpe ratio with respect to risk free rate; measures excess of return per unit of risk. |
| Sortino Ratio | `string` Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk. |
| Probabilistic Sharpe Ratio | `string` Is a probability measure associated with the Sharpe ratio. It informs us of the probability that the estimated Sharpe ratio is greater than a chosen benchmark. |
| Loss Rate | `string` The ratio of the number of losing trades to the total number of trades. |
| Win Rate | `string` The ratio of the number of winning trades to the total number of trades. |
| Profit-Loss Ratio | `string` The ratio of the average win rate to the average loss rate. |
| Alpha | `string` Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns. |
| Beta | `string` Algorithm "beta" statistic - the covariance between the algorithm and benchmark performance, divided by benchmark's variance. |
| Annual Standard Deviation | `string` Annualized standard deviation. |
| Annual Variance | `string` Annualized variance statistic calculation using the daily performance variance and trading days per year. |
| Information Ratio | `string` Information ratio - risk adjusted return. |
| Tracking Error | `string` Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked. |
| Treynor Ratio | `string` Treynor ratio statistic is a measurement of the returns earned in excess of that which could have been earned on an investment that has no diversifiable risk. |
| Total Fees | `string` Total amount of fees. |
| Estimated Strategy Capacity | `string` The estimated total capacity of the strategy at a point in time. |
| Lowest Capacity Asset | `string` Provide a reference to the lowest capacity symbol used in scaling down the capacity for debugging. |
| Portfolio Turnover | `string` The average Portfolio Turnover. |
| Drawdown Recovery | `string` /. |
| Example | `{ "Total Orders": "string", "Average Win": "string", "Average Loss": "string", "Compounding Annual Return": "string", "Drawdown": "string", "Expectancy": "string", "Start Equity": "string", "End Equity": "string", "Net Profit": "string", "Sharpe Ratio": "string", "Sortino Ratio": "string", "Probabilistic Sharpe Ratio": "string", "Loss Rate": "string", "Win Rate": "string", "Profit-Loss Ratio": "string", "Alpha": "string", "Beta": "string", "Annual Standard Deviation": "string", "Annual Variance": "string", "Information Ratio": "string", "Tracking Error": "string", "Treynor Ratio": "string", "Total Fees": "string", "Estimated Strategy Capacity": "string", "Lowest Capacity Asset": "string", "Portfolio Turnover": "string", "Drawdown Recovery": "string" }` |

| `AlgorithmPerformance` Model - The AlgorithmPerformance class is a wrapper for TradeStatistics and PortfolioStatistics. |  |
| --- | --- |
| tradeStatistics | `TradeStatistics object` A set of statistics calculated from a list of closed trades. |
| portfolioStatistics | `PortfolioStatistics object` Represents a set of statistics calculated from equity and benchmark samples. |
| closedTrades | `ClosedTrade Array` The algorithm statistics on portfolio. |
| Example | `{ "tradeStatistics": { "startDateTime": "2021-11-26T15:18:27.693Z", "endDateTime": "2021-11-26T15:18:27.693Z", "totalNumberOfTrades": 0, "numberOfWinningTrades": 0, "numberOfLosingTrades": 0, "totalProfitLoss": "string", "totalProfit": "string", "totalLoss": "string", "largestProfit": "string", "largestLoss": "string", "averageProfitLoss": "string", "averageProfit": "string", "averageLoss": "string", "averageTradeDuration": "string", "averageWinningTradeDuration": "string", "averageLosingTradeDuration": "string", "medianTradeDuration": "string", "medianWinningTradeDuration": "string", "medianLosingTradeDuration": "string", "maxConsecutiveWinningTrades": 0, "maxConsecutiveLosingTrades": 0, "profitLossRatio": "string", "winLossRatio": "string", "winRate": "string", "lossRate": "string", "averageMAE": "string", "averageMFE": "string", "largestMAE": "string", "largestMFE": "string", "maximumClosedTradeDrawdown": "string", "maximumIntraTradeDrawdown": "string", "profitLossStandardDeviation": "string", "profitLossDownsideDeviation": "string", "profitFactor": "string", "sharpeRatio": "string", "sortinoRatio": "string", "profitToMaxDrawdownRatio": "string", "maximumEndTradeDrawdown": "string", "averageEndTradeDrawdown": "string", "maximumDrawdownDuration": "string", "totalFees": "string" }, "portfolioStatistics": { "averageWinRate": "string", "averageLossRate": "string", "profitLossRatio": "string", "winRate": "string", "lossRate": "string", "expectancy": "string", "startEquity": "string", "endEquity": "string", "compoundingAnnualReturn": "string", "drawdown": "string", "totalNetProfit": "string", "sharpeRatio": "string", "probabilisticSharpeRatio": "string", "sortinoRatio": "string", "alpha": "string", "beta": "string", "annualStandardDeviation": "string", "annualVariance": "string", "informationRatio": "string", "trackingError": "string", "treynorRatio": "string", "portfolioTurnover": "string", "valueAtRisk99": "string", "valueAtRisk95": "string", "drawdownRecovery": "string" }, "closedTrades": [ { "id": "e1936b18-446b-4d57-95a6-6fd1a420e261", "symbols": [ { "value": "string", "id": "string", "permtick": "string" } ], "entryTime": "2021-11-26T15:18:27.693Z", "entryPrice": 0, "direction": 0, "quantity": 0, "exitTime": "2021-11-26T15:18:27.693Z", "exitPrice": 0, "profitLoss": 0, "totalFees": 0, "mae": 0, "mfe": 0, "duration": "string", "endTradeDrawdown": 0, "isWin": true, "orderIds": [ "integer" ] } ] }` |

| `TradeStatistics` Model - A set of statistics calculated from a list of closed trades. |  |
| --- | --- |
| startDateTime | `string($date-time)` The entry date/time of the first trade. |
| endDateTime | `string($date-time)` The exit date/time of the first trade. |
| totalNumberOfTrades | `integer` The total number of trades. |
| numberOfWinningTrades | `integer` The total number of winning trades. |
| numberOfLosingTrades | `integer` The total number of losing trades. |
| totalProfitLoss | `string` The total profit/loss for all trades (as symbol currency). |
| totalProfit | `string` The total profit for all winning trades (as symbol currency). |
| totalLoss | `string` The total loss for all losing trades (as symbol currency). |
| largestProfit | `string` The largest profit in a single trade (as symbol currency). |
| largestLoss | `string` The largest loss in a single trade (as symbol currency). |
| averageProfitLoss | `string` The average profit/loss (a.k.a. Expectancy or Average Trade) for all trades (as symbol currency). |
| averageProfit | `string` The average profit for all winning trades (as symbol currency). |
| averageLoss | `string` The average loss for all winning trades (as symbol currency). |
| averageTradeDuration | `string` The average duration for all trades. |
| averageWinningTradeDuration | `string` The average duration for all winning trades. |
| averageLosingTradeDuration | `string` The average duration for all losing trades. |
| medianTradeDuration | `string` The median duration for all trades. |
| medianWinningTradeDuration | `string` The median duration for all winning trades. |
| medianLosingTradeDuration | `string` The median duration for all losing trades. |
| maxConsecutiveWinningTrades | `integer` The maximum number of consecutive winning trades. |
| maxConsecutiveLosingTrades | `integer` The maximum number of consecutive losing trades. |
| profitLossRatio | `string` The ratio of the average profit per trade to the average loss per trade. |
| winLossRatio | `string` The ratio of the number of winning trades to the number of losing trades. |
| winRate | `string` The ratio of the number of winning trades to the total number of trades. |
| lossRate | `string` The ratio of the number of losing trades to the total number of trades. |
| averageMAE | `string` The average Maximum Adverse Excursion for all trades. |
| averageMFE | `string` The average Maximum Adverse Excursion for all trades. |
| largestMAE | `string` The average Maximum Favorable Excursion for all trades. |
| largestMFE | `string` The largest Maximum Adverse Excursion in a single trade (as symbol currency). |
| maximumClosedTradeDrawdown | `string` The maximum closed-trade drawdown for all trades (as symbol currency). |
| maximumIntraTradeDrawdown | `string` The maximum intra-trade drawdown for all trades (as symbol currency). |
| profitLossStandardDeviation | `string` The standard deviation of the profits/losses for all trades (as symbol currency). |
| profitLossDownsideDeviation | `string` The downside deviation of the profits/losses for all trades (as symbol currency). |
| profitFactor | `string` The ratio of the total profit to the total loss. |
| sharpeRatio | `string` The ratio of the average profit/loss to the standard deviation. |
| sortinoRatio | `string` The ratio of the average profit/loss to the downside deviation. |
| profitToMaxDrawdownRatio | `string` The ratio of the total profit/loss to the maximum closed trade drawdown. |
| maximumEndTradeDrawdown | `string` The maximum amount of profit given back by a single trade before exit (as symbol currency). |
| averageEndTradeDrawdown | `string` The average amount of profit given back by all trades before exit (as symbol currency). |
| maximumDrawdownDuration | `string` The maximum amount of time to recover from a drawdown (longest time between new equity highs or peaks). |
| totalFees | `string` The sum of fees for all trades. |
| Example | `{ "startDateTime": "2021-11-26T15:18:27.693Z", "endDateTime": "2021-11-26T15:18:27.693Z", "totalNumberOfTrades": 0, "numberOfWinningTrades": 0, "numberOfLosingTrades": 0, "totalProfitLoss": "string", "totalProfit": "string", "totalLoss": "string", "largestProfit": "string", "largestLoss": "string", "averageProfitLoss": "string", "averageProfit": "string", "averageLoss": "string", "averageTradeDuration": "string", "averageWinningTradeDuration": "string", "averageLosingTradeDuration": "string", "medianTradeDuration": "string", "medianWinningTradeDuration": "string", "medianLosingTradeDuration": "string", "maxConsecutiveWinningTrades": 0, "maxConsecutiveLosingTrades": 0, "profitLossRatio": "string", "winLossRatio": "string", "winRate": "string", "lossRate": "string", "averageMAE": "string", "averageMFE": "string", "largestMAE": "string", "largestMFE": "string", "maximumClosedTradeDrawdown": "string", "maximumIntraTradeDrawdown": "string", "profitLossStandardDeviation": "string", "profitLossDownsideDeviation": "string", "profitFactor": "string", "sharpeRatio": "string", "sortinoRatio": "string", "profitToMaxDrawdownRatio": "string", "maximumEndTradeDrawdown": "string", "averageEndTradeDrawdown": "string", "maximumDrawdownDuration": "string", "totalFees": "string" }` |

| `PortfolioStatistics` Model - Represents a set of statistics calculated from equity and benchmark samples. |  |
| --- | --- |
| averageWinRate | `string` The average rate of return for winning trades. |
| averageLossRate | `string` The average rate of return for losing trades. |
| profitLossRatio | `string` The ratio of the average win rate to the average loss rate. |
| winRate | `string` The ratio of the number of winning trades to the total number of trades. |
| lossRate | `string` The ratio of the number of losing trades to the total number of trades. |
| expectancy | `string` The expected value of the rate of return. |
| startEquity | `string` Initial Equity Total Value. |
| endEquity | `string` Final Equity Total Value. |
| compoundingAnnualReturn | `string` Annual compounded returns statistic based on the final-starting capital and years. |
| drawdown | `string` Drawdown maximum percentage. |
| totalNetProfit | `string` The total net profit percentage. |
| sharpeRatio | `string` Sharpe ratio with respect to risk free rate: measures excess of return per unit of risk. |
| probabilisticSharpeRatio | `string` Probabilistic Sharpe Ratio is a probability measure associated with the Sharpe ratio. It informs us of the probability that the estimated Sharpe ratio is greater than a chosen benchmark. |
| sortinoRatio | `string` Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk. |
| alpha | `string` Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns. |
| beta | `string` Algorithm beta statistic - the covariance between the algorithm and benchmark performance, divided by benchmark variance. |
| annualStandardDeviation | `string` Annualized standard deviation. |
| annualVariance | `string` Annualized variance statistic calculation using the daily performance variance and trading days per year. |
| informationRatio | `string` Information ratio - risk adjusted return. |
| trackingError | `string` Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked. |
| treynorRatio | `string` Treynor ratio statistic is a measurement of the returns earned in excess of that which could have been earned on an investment that has no diversifiable risk. |
| portfolioTurnover | `string` The average Portfolio Turnover. |
| valueAtRisk99 | `string` The 1-day VaR for the portfolio, using the Variance-covariance approach. Assumes a 99% confidence level, 1 year lookback period, and that the returns are normally distributed. |
| valueAtRisk95 | `string` The 1-day VaR for the portfolio, using the Variance-covariance approach. Assumes a 95% confidence level, 1 year lookback period, and that the returns are normally distributed. |
| drawdownRecovery | `string` /. |
| Example | `{ "averageWinRate": "string", "averageLossRate": "string", "profitLossRatio": "string", "winRate": "string", "lossRate": "string", "expectancy": "string", "startEquity": "string", "endEquity": "string", "compoundingAnnualReturn": "string", "drawdown": "string", "totalNetProfit": "string", "sharpeRatio": "string", "probabilisticSharpeRatio": "string", "sortinoRatio": "string", "alpha": "string", "beta": "string", "annualStandardDeviation": "string", "annualVariance": "string", "informationRatio": "string", "trackingError": "string", "treynorRatio": "string", "portfolioTurnover": "string", "valueAtRisk99": "string", "valueAtRisk95": "string", "drawdownRecovery": "string" }` |

| `ClosedTrade` Model - Represents a closed trade of a backtest or a live algorithm. |  |
| --- | --- |
| id | `string example: e1936b18-446b-4d57-95a6-6fd1a420e261` Unique identifier of the closed trade. |
| symbols | `Symbol Array` The securities involved in the trade. |
| entryTime | `string($date-time)` The date and time the trade was opened. |
| entryPrice | `number` The price at which the trade was opened (or the average price if multiple entries). |
| direction | `integer Enum` Direction of a trade. 0=Long, 1=Short. Options : [0, 1] |
| quantity | `number` The total unsigned quantity of the trade. |
| exitTime | `string($date-time)` The date and time the trade was closed. |
| exitPrice | `number` The price at which the trade was closed (or the average price if multiple exits). |
| profitLoss | `number` The gross profit/loss of the trade (as account currency). |
| totalFees | `number` The total fees associated with the trade (always positive value) (as account currency). |
| mae | `number` The Maximum Adverse Excursion (as account currency). |
| mfe | `number` The Maximum Favorable Excursion (as account currency). |
| duration | `string` The duration of the trade. |
| endTradeDrawdown | `number` The amount of profit given back before the trade was closed. |
| isWin | `boolean` Whether the trade closed at a profit. |
| orderIds | `integer Array` Ids of the orders that opened and closed the trade. |
| Example | `{ "id": "e1936b18-446b-4d57-95a6-6fd1a420e261", "symbols": [ { "value": "string", "id": "string", "permtick": "string" } ], "entryTime": "2021-11-26T15:18:27.693Z", "entryPrice": 0, "direction": 0, "quantity": 0, "exitTime": "2021-11-26T15:18:27.693Z", "exitPrice": 0, "profitLoss": 0, "totalFees": 0, "mae": 0, "mfe": 0, "duration": "string", "endTradeDrawdown": 0, "isWin": true, "orderIds": [ "integer" ] }` |

| `Symbol` Model - Represents a unique security identifier. This is made of two components, the unique SID and the Value. The value is the current ticker symbol while the SID is constant over the life of a security. |  |
| --- | --- |
| value | `string` The current symbol for this ticker. |
| id | `string` The security identifier for this symbol. |
| permtick | `string` The ticker at IPO for this security. |
| Example | `{ "value": "string", "id": "string", "permtick": "string" }` |

| `AnalysisResult` Model - The result of an analysis performed on a result. |  |
| --- | --- |
| name | `string required example: PerformanceRelativeToBenchmarkAnalysis` The name of the analysis that produced this result. |
| issue | `string required example: The strategy has a lower Sharpe ratio than the benchmark.` A short description of why the analysis was triggered. |
| sample | `object required example: {'backtestSharpe': -0.2281345806218534, 'benchmarkSharpe': -0.22182175736916387}` A representative sample value of the issue detected by the analysis. |
| count | `integer example: 5` The total number of matching occurrences found by the analysis. If not present, it should be assumed that there is only one occurrence. |
| solutions | `string Array required` Human-readable suggestions for resolving the detected issue. |
| Example | `{ "name": "PerformanceRelativeToBenchmarkAnalysis", "issue": "The strategy has a lower Sharpe ratio than the benchmark.", "sample": { "backtestSharpe": -0.2281345806218534, "benchmarkSharpe": -0.22182175736916387 }, "count": 5, "solutions": [ "Try adjusting the trading rules and/or the universe to get a strategy that outperforms the benchmark." ] }` |

### 401 Authentication Error

| `UnauthorizedError` Model - Unauthorized response from the API. Key is missing, invalid, or timestamp is too old for hash. |  |
| --- | --- |
| www_authenticate | `string` Header |

## Examples

The following example demonstates creating, reading, updating, deleting, and listing backtests of a project through the cloud API.

```
from base64 import b64encode
from hashlib import sha256
from time import time
from requests import get, post
BASE_URL = 'https://www.quantconnect.com/api/v2/'

# You need to replace these with your actual credentials.
# You can request your credentials at https://www.quantconnect.com/settings/
# You can find our organization ID at https://www.quantconnect.com/organization/
USER_ID = 0
API_TOKEN = '____'
ORGANIZATION_ID = '____'

def get_headers():
    # Get timestamp
    timestamp = f'{int(time())}'
    time_stamped_token = f'{API_TOKEN}:{timestamp}'.encode('utf-8')

    # Get hased API token
    hashed_token = sha256(time_stamped_token).hexdigest()
    authentication = f'{USER_ID}:{hashed_token}'.encode('utf-8')
    authentication = b64encode(authentication).decode('ascii')

    # Create headers dictionary.
    return {
        'Authorization': f'Basic {authentication}',
        'Timestamp': timestamp
    }

# Authenticate to verify credentials
response = post(f'{BASE_URL}/authenticate', headers = get_headers())
print(response.json())

# --------------------

### Create Backtest
# Define placeholder compilation ID (replace with actual value)
compile_id = "compile_id..."
# Send a POST request to the /backtests/create endpoint to create a backtest
response = post(f'{BASE_URL}/backtests/create', headers=get_headers(), json={
    "projectId": project_id,  # ID of the project to backtest
    "compileId": compile_id,  # Compilation ID for the backtest
    "backtestName": f"Backtest {int(time())}"  # Unique name for the backtest using current timestamp
})
# Parse the JSON response into python managable dict
result = response.json()
# Extract the backtest ID from the response
backtest_id = result['backtest']['backtestId']
# Check if the request was successful and print the result
if result['success']:
    print("Backtest Created Successfully:")
    print(result)

### Read Backtest Statistics
# Prepare data payload to read backtest statistics
payload = {
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id  # ID of the backtest to read
}
# Send a POST request to the /backtests/read endpoint to get statistics
response = post(f'{BASE_URL}/backtests/read', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the statistics
if result['success']:
    print("Backtest Statistics:")
    print(result)

### Read Backtest Logs
# Prepare data payload to read the first 200 log lines
payload = {
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id,  # ID of the backtest to read
    "start": 0,  # Start line (inclusive)
    "end": 200,  # End line (exclusive), at most 200 lines per request
    "query": None  # Keyword to filter the lines, or None to read all of them
}
# Send a POST request to the /backtests/read/log endpoint to get the logs
response = post(f'{BASE_URL}/backtests/read/log', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the logs
if result['success']:
    print("Backtest Logs:")
    print(result)

### Update Backtest
# Send a POST request to the /backtests/update endpoint to update backtest details
response = post(f'{BASE_URL}/backtests/update', headers=get_headers(), json={
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id,  # ID of the backtest to update
    "name": f"Backtest_{backtest_id}",  # New name for the backtest
    "note": "The new backtest name is awesome!"  # Additional note
})
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("Backtest Updated Successfully:")
    print(result)

### Delete Backtest
# Prepare data payload to delete the backtest
payload = {
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id  # ID of the backtest to delete
}
# Send a POST request to the /backtests/delete endpoint to delete the backtest
response = post(f'{BASE_URL}/backtests/delete', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("Backtest Deleted Successfully:")
    print(result)

### List Backtests
# Prepare data payload to list backtests with statistics
payload = {
    "projectId": project_id,  # ID of the project
    "includeStatistics": True  # Include statistics in the response
}
# Send a POST request to the /backtests/list endpoint to list backtests
response = post(f'{BASE_URL}/backtests/list', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the list
if result['success']:
    print("List of Backtests:")
    print(result)

### Export Orders
# Download the orders of the backtest as a CSV file
payload = {
    "backtestId": backtest_id  # ID of the backtest
}
response = post(f'{BASE_URL}/backtests/export/orders', headers=get_headers(), json=payload)
with open(f'orders-{backtest_id}.csv', 'w', newline='') as file:
    file.write(response.text)

### Export Trades
# Download the closed trades of the backtest as a CSV file
payload = {
    "backtestId": backtest_id  # ID of the backtest
}
response = post(f'{BASE_URL}/backtests/export/trades', headers=get_headers(), json=payload)
with open(f'trades-{backtest_id}.csv', 'w', newline='') as file:
    file.write(response.text)

### Export Insights
# Download the insights of the backtest as a JSON file
payload = {
    "backtestId": backtest_id  # ID of the backtest
}
response = post(f'{BASE_URL}/backtests/export/insights', headers=get_headers(), json=payload)
with open(f'insights-{backtest_id}.json', 'w', newline='') as file:
    file.write(response.text)

### Export Logs
# Download the logs of the backtest as a text file
payload = {
    "projectId": project_id,  # ID of the project
    "backtestId": backtest_id  # ID of the backtest
}
response = post(f'{BASE_URL}/backtests/export/logs', headers=get_headers(), json=payload)
with open(f'logs-{backtest_id}.txt', 'w', newline='') as file:
    file.write(response.text)
```
