diff --git a/single-page/Quantconnect-Cloud-Platform.html b/single-page/Quantconnect-Cloud-Platform.html index c771a78b22..a3f3bc20c2 100644 --- a/single-page/Quantconnect-Cloud-Platform.html +++ b/single-page/Quantconnect-Cloud-Platform.html @@ -565,7 +565,11 @@
Physical access to our servers is limited to a few dedicated team members whom QuantConnect has vetted. Only those credentialed team members can access the physical servers, and we schedule all work in advance. - Work on the servers is always done in pairs to prevent single rogue actors from accessing the servers. We host our servers in a world-class security facility (Equinix) with security staff 24/7. + Work on the servers is always done in pairs to prevent single rogue actors from accessing the servers. We host our servers in a world-class security facility, on co-located servers racked in + + Equinix + + , with security staff 24/7.
- Live trading nodes enable you to deploy live algorithms to our professionally-managed, co-located servers. + Live trading nodes enable you to deploy live algorithms to our professionally-managed, co-located servers racked in + + Equinix + + . You need a live trading node for each algorithm that you deploy to our co-located servers. Several models of live trading nodes are available. More powerful live trading nodes allow you to run algorithms with larger universes and give you @@ -9333,6 +9341,87 @@
+ You can add + + tags + + to your orders to track why each trade was placed. This is useful for debugging your algorithm's trading logic because you can include the indicator values or conditions that triggered the order. +
+public class OrderTaggingAlgorithm : QCAlgorithm
+{
+ private ExponentialMovingAverage _emaShort;
+ private ExponentialMovingAverage _emaLong;
+ private Symbol _symbol;
+
+ public override void Initialize()
+ {
+ SetStartDate(2024, 9, 1);
+ SetEndDate(2024, 12, 31);
+ SetCash(100000);
+
+ _symbol = AddEquity("SPY", Resolution.Daily).Symbol;
+ _emaShort = EMA(_symbol, 10);
+ _emaLong = EMA(_symbol, 30);
+ }
+
+ public override void OnData(Slice data)
+ {
+ if (!_emaShort.IsReady || !_emaLong.IsReady) return;
+
+ if (_emaShort > _emaLong && !Portfolio[_symbol].IsLong)
+ {
+ MarketOrder(_symbol, 100, tag: $"BUY: ema-short: {_emaShort:F4} > ema-long: {_emaLong:F4}");
+ }
+ else if (_emaShort < _emaLong && !Portfolio[_symbol].IsShort)
+ {
+ MarketOrder(_symbol, -100, tag: $"SELL: ema-short: {_emaShort:F4} < ema-long: {_emaLong:F4}");
+ }
+ }
+}
+ class OrderTaggingAlgorithm(QCAlgorithm):
+ def initialize(self) -> None:
+ self.set_start_date(2024, 9, 1)
+ self.set_end_date(2024, 12, 31)
+ self.set_cash(100000)
+
+ self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
+ self._ema_short = self.ema(self._symbol, 10)
+ self._ema_long = self.ema(self._symbol, 30)
+
+ def on_data(self, data: Slice) -> None:
+ if not self._ema_short.is_ready or not self._ema_long.is_ready:
+ return
+
+ ema_short = self._ema_short.current.value
+ ema_long = self._ema_long.current.value
+ if ema_short > ema_long and not self.portfolio[self._symbol].is_long:
+ self.market_order(self._symbol, 100, tag=f'BUY: ema-short: {ema_short:.4f} > ema-long: {ema_long:.4f}')
+ elif ema_short < ema_long and not self.portfolio[self._symbol].is_short:
+ self.market_order(self._symbol, -100, tag=f'SELL: ema-short: {ema_short:.4f} < ema-long: {ema_long:.4f}')
+ + The tag is saved to the + + result files + + that you can download for local analysis. Unlike + + logging statements + + , order tags are attached directly to each order, so you don't need to search through logs to match a message to a specific trade, and they don't consume your + + log quota + + . +
+ + +The Object Store is a key-value data store for low-latency information storage and retrieval. - During a backtest, you can build large objects you’d like to analyze and write them for later analysis. + During a backtest, you can build large objects you'd like to analyze and write them for later analysis. This workflow can be helpful when the objects are large and plotting is impossible or when you want to perform analysis across many backtests.
#load "../QuantConnect.csx" -using QuantConnect; +#load "../QuantConnect.csx"+
using QuantConnect; using QuantConnect.Data; using QuantConnect.Algorithm; using QuantConnect.Research; @@ -18483,7 +18574,11 @@Delivery
- Most live trading algorithms run on co-located servers racked in Equinix. Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters. + Most live trading algorithms run on co-located servers racked in + + Equinix + + . Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters.
Live data takes time to travel from the source to your algorithm. @@ -18665,7 +18760,11 @@
Delivery
- Most live trading algorithms run on co-located servers racked in Equinix. Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters. + Most live trading algorithms run on co-located servers racked in + + Equinix + + . Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters.
Live data takes time to travel from the source to your algorithm. @@ -18813,7 +18912,11 @@
Delivery
- Most live trading algorithms run on co-located servers racked in Equinix. Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters. + Most live trading algorithms run on co-located servers racked in + + Equinix + + . Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters.
Live data takes time to travel from the source to your algorithm. @@ -18948,7 +19051,11 @@
Delivery
- Most live trading algorithms run on co-located servers racked in Equinix. Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters. + Most live trading algorithms run on co-located servers racked in + + Equinix + + . Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters.
Live data takes time to travel from the source to your algorithm. @@ -19083,7 +19190,11 @@
Delivery
- Most live trading algorithms run on co-located servers racked in Equinix. Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters. + Most live trading algorithms run on co-located servers racked in + + Equinix + + . Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters.
Live data takes time to travel from the source to your algorithm. @@ -19249,7 +19360,11 @@
Delivery
- Most live trading algorithms run on co-located servers racked in Equinix. Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters. + Most live trading algorithms run on co-located servers racked in + + Equinix + + . Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters.
Live data takes time to travel from the source to your algorithm. @@ -19389,7 +19504,11 @@
Delivery
, include a live stream. In these cases, we deliver the data as a live stream to your algorithm.- Most live trading algorithms run on co-located servers racked in Equinix. Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters. + Most live trading algorithms run on co-located servers racked in + + Equinix + + . Co-location reduces several factors that can interfere with your algorithm, including downtime from internet outages, equipment repairs, and natural disasters.
Live data takes time to travel from the source to your algorithm. The latency of the alternative data depends on the specific dataset you're using. @@ -21666,7 +21785,11 @@
Introduction
- A live algorithm is an algorithm that trades in real-time with real market data. QuantConnect enables you to run your algorithms in live mode with real-time market data. Deploy your algorithms using QuantConnect because our infrastructure is battle-tested. The algorithms that our members create are run on co-located servers and the trading infrastructure is maintained at all times by our team of engineers. It's common for members to achieve 6-months of uptime with no interruptions. + A live algorithm is an algorithm that trades in real-time with real market data. QuantConnect enables you to run your algorithms in live mode with real-time market data. Deploy your algorithms using QuantConnect because our infrastructure is battle-tested. The algorithms that our members create are run on co-located servers racked in + + Equinix + + and the trading infrastructure is maintained at all times by our team of engineers. It's common for members to achieve 6-months of uptime with no interruptions.
@@ -23531,6 +23654,110 @@+
FIX Integration
+ + ++ FIX (Financial Information eXchange) integration lets existing Interactive Brokers (IB) clients route orders from QuantConnect through their IB account. If you already hold an IB account, you can subscribe to QuantConnect directly from the IB Client Portal to enable FIX order routing. +
++ Before you start, make sure you have an active IB account and access to the IB Client Portal. +
++ Follow these steps to add FIX support to your IB account: +
++
+ + +- + Log in to the + + IB Client Portal + + , open + + Settings + + , click + + Research Subscriptions + + , open + + News & Research Subscriptions + + , and then click + + . +
+- + Select + + from the list of subscriptions to create the FIX session, and then click + + . +
+- + On the + + Review Your Research Subscriptions + + screen, review the market-data agreements and disclosures, and then confirm to proceed. +
+- + On the + + Service Account Configuration + + screen, click the + + gear next to QuantConnect. +
+- + In the + + Service Account Configuration for QuantConnect + + dialog, select the IB account(s) you want to link, enter your QuantConnect user name in the + + Quantconnect Username + + field, and then click + + . +
++ The user name you enter is the default subscriber for the QuantConnect service. You can select multiple accounts here. When you later connect from QuantConnect to IB, you enter this same user name to authenticate. +
+- + Back on the + + Service Account Configuration + + screen, click + + . +
+- + Acknowledge and confirm the OMS Riders and Addendum. +
++ After you confirm, your subscription is complete and the selected information is added to the FIX connection for order validation. +
+Asset Classes
@@ -24801,6 +25028,141 @@Deploy Live Algorithms
+Deploy Live Algorithms FIX
+ + ++ You must have an available + + live trading node + + for each live trading algorithm you deploy. +
++ Follow these steps to deploy a live algorithm: +
++
+- + + Open the project + + you want to deploy. +
+- + Click the +
++ + Deploy Live + + icon. +
- + On the Deploy Live page, click the + + Brokerage + + field and then click + + from the drop-down menu. +
+- + Enter your + + IB + + user name (see + + FIX Integration + + ). +
+- + Click the + + Node + + field and then click the live trading node that you want to use from the drop-down menu. +
+- + + (Optional) + + In the + + Data Provider + + section, click + + and change the data provider or add additional providers. +
++ In most cases, we suggest using + + both the QC and IB data providers + + . +
++ If you use + + IB + + data provider and trade with a paper trading account, you need to share the market data subscription with your paper trading account. For instructions on sharing market data subscription, see + + Account Types + + . +
+- + + (Optional) + + + Set up notifications + + . +
+- + Configure the + + Automatically restart algorithm + + setting. +
++ By enabling + + automatic restarts + + , the algorithm will use best efforts to restart the algorithm if it fails due to a runtime error. This can help improve the algorithm's resilience to temporary outages such as a brokerage API disconnection. +
+- + Click + + . +
+- + If your IB account has 2FA enabled, tap the notification on your IB Key device and then enter your pin. +
++ The deployment process can take up to 5 minutes. When the algorithm deploys, the + + live results page + + displays. If you know your brokerage positions before you deployed, you can verify they have been loaded properly by checking your equity value in the runtime statistics, your cashbook holdings, and your position holdings. +
+ + +Troubleshooting
@@ -38460,7 +38822,11 @@Introduction
- Deploy your trading algorithms live to receive real-time market data and submit orders on our co-located servers. As your algorithms run, you can view their performance in the Algorithm Lab. Since the algorithms run in QuantConnect Cloud, you can close the IDE without interrupting the execution of your algorithms. Deploying your algorithms to live trading through QuantConnect is cheaper than purchasing server space, setting up data feeds, and maintaining the software on your own. To deploy your algorithms on QuantConnect, you just need to follow the + Deploy your trading algorithms live to receive real-time market data and submit orders on our co-located servers racked in + + Equinix + + . As your algorithms run, you can view their performance in the Algorithm Lab. Since the algorithms run in QuantConnect Cloud, you can close the IDE without interrupting the execution of your algorithms. Deploying your algorithms to live trading through QuantConnect is cheaper than purchasing server space, setting up data feeds, and maintaining the software on your own. To deploy your algorithms on QuantConnect, you just need to follow the Deploy Live Algorithms @@ -38477,7 +38843,11 @@
Resources
- Live trading nodes enable you to deploy live algorithms to our professionally-managed, co-located servers. + Live trading nodes enable you to deploy live algorithms to our professionally-managed, co-located servers racked in + + Equinix + + . You need a live trading node for each algorithm that you deploy to our co-located servers. Several models of live trading nodes are available. More powerful live trading nodes allow you to run algorithms with larger universes and give you @@ -40577,9 +40947,9 @@
To programmatically analyze orders, call the - + - ReadBacktestOrders + ReadLiveOrders read_live_orders @@ -41195,6 +41565,13 @@
Introduction
If your algorithm is perfectly reconciled, it has an exact overlap between its live and OOS backtest equity curves. Deviations mean that the performance of your algorithm has differed between the two execution modes. Several factors can contribute to the deviations.
++ To generate the OOS reconciliation curve for a live deployment and overlay live vs. backtest equity and order fills from the Research Environment, see + + Live Reconciliation + + . +
@@ -47460,44 +47837,48 @@
// Generate a timestamped SHA-256 hashed API token for secure authentication -#r "nuget:RestSharp" -using System; using System.Security.Cryptography; -using RestSharp; +using System.Text; -// Request your API token on https://www.quantconnect.com/settings/ and replace the below values. -var yourUserId = 0; -var yourApiToken = "_____"; +// Set the QC_USER_ID and QC_API_TOKEN environment variables with values from https://www.quantconnect.com/settings/. +var yourUserId = Environment.GetEnvironmentVariable("QC_USER_ID") ?? "0"; +var yourApiToken = Environment.GetEnvironmentVariable("QC_API_TOKEN") ?? "_____"; -// Get timestamp -var stamp = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds(); -var timeStampedToken = $"{<yourApiToken>}:{stamp}"; - -// Get hashed API token -var crypt = new SHA256Managed(); -var hashToken = crypt.ComputeHash(Encoding.UTF8.GetBytes(timeStampedToken), 0, Encoding.UTF8.GetByteCount(timeStampedToken)); -var hash = new StringBuilder(); -foreach (var theByte in hashToken) +Dictionary<string, string> GetHeaders() { - hash.Append(theByte.ToString("x2")); + // Get timestamp + var timestamp = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds().ToString(); + var timeStampedToken = $"{yourApiToken}:{timestamp}"; + + // Get hashed API token + var hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(timeStampedToken)); + var hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); + var authentication = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{yourUserId}:{hash}")); + + // Create headers dictionary. + return new Dictionary<string, string> + { + { "Authorization", $"Basic {authentication}" }, + { "Timestamp", timestamp } + }; } -var apiToken = hash.ToString();# Generate a timestamped SHA-256 hashed API token for secure authentication +from os import environ from base64 import b64encode from hashlib import sha256 from time import time -# Request your API token on https://www.quantconnect.com/settings/ and replace the below values. -USER_ID = 0 -API_TOKEN = '_____' +# Set the QC_USER_ID and QC_API_TOKEN environment variables with values from https://www.quantconnect.com/settings/. +USER_ID = environ.get('QC_USER_ID', 0) +API_TOKEN = environ.get('QC_API_TOKEN', '_____') def get_headers(): # Get timestamp timestamp = f'{int(time())}' time_stamped_token = f'{API_TOKEN}:{timestamp}'.encode('utf-8') - # Get hased API token + # Get hashed API token hashed_token = sha256(time_stamped_token).hexdigest() authentication = f'{USER_ID}:{hashed_token}'.encode('utf-8') authentication = b64encode(authentication).decode('ascii') @@ -47512,27 +47893,22 @@
Make API Request
-- Follow the below example to install the hashing into the authenticator and make an API request. -
-- Follow the below example to install the hashing into the headings and make an API request. +
+ Follow the below example to set the authentication headers and make an API request.
-+// Create REST client and install authenticator. -var client = new RestClient("<requestUrl>"); -client.Authenticator = new HttpBasicAuthenticator( - "<yourUserId>", - hash.ToString() -); - -// Create Request and add timestamp header (optional: Json Content). -var request = new RestRequest(); -request.AddHeader("Timestamp", stamp.ToString()); +// Create HTTP client with authentication headers. +var client = new HttpClient(); +client.BaseAddress = new Uri("https://www.quantconnect.com/api/v2/"); +foreach (var header in GetHeaders()) +{ + client.DefaultRequestHeaders.Add(header.Key, header.Value); +} // Make POST request. -var response = await client.PostAsync(request); -var content = response.Content+var request = new StringContent("{}", Encoding.UTF8, "application/json"); +var response = await client.PostAsync("<requestUrl>", request); +var content = await response.Content.ReadAsStringAsync();# Create POST Request with headers from requests import post BASE_URL = 'https://www.quantconnect.com/api/v2/' @@ -47542,6 +47918,61 @@json = {}) # Use json keyword to send the payload content = response.text
+ Using cURL +
++ Follow the below example to make an API request with authentication using cURL. +
+++# Set the QC_USER_ID and QC_API_TOKEN environment variables with values from https://www.quantconnect.com/settings/. +YOUR_USER_ID=${QC_USER_ID:-0} +YOUR_API_TOKEN=${QC_API_TOKEN:-_____} + +# Get timestamp +TIMESTAMP=$(date +%s) +TIME_STAMPED_TOKEN="${YOUR_API_TOKEN}:${TIMESTAMP}" + +# Get hashed API token +HASHED_TOKEN=$(echo -n "$TIME_STAMPED_TOKEN" | sha256sum | cut -d ' ' -f 1) +AUTHENTICATION=$(echo -n "${YOUR_USER_ID}:${HASHED_TOKEN}" | base64 -w 0) + +# Make POST request with authentication headers +curl -X POST "https://www.quantconnect.com/api/v2/<request_url>" \ + -H "Authorization: Basic ${AUTHENTICATION}" \ + -H "Timestamp: ${TIMESTAMP}" \ + -H "Content-Type: application/json" \ + -d '{}'++ Using PowerShell +
++ Follow the below example to make an API request with authentication using PowerShell. +
++@@ -48115,7 +48546,7 @@# Set the QC_USER_ID and QC_API_TOKEN environment variables with values from https://www.quantconnect.com/settings/. +$yourUserId = if ($env:QC_USER_ID) { $env:QC_USER_ID } else { "0" } +$yourApiToken = if ($env:QC_API_TOKEN) { $env:QC_API_TOKEN } else { "_____" } + +# Get timestamp +$timestamp = [Math]::Floor((([DateTimeOffset]::UtcNow).ToUnixTimeSeconds())) +$timeStampedToken = "${yourApiToken}:${timestamp}" + +# Get hashed API token +$hasher = [System.Security.Cryptography.SHA256]::Create() +$hashBytes = $hasher.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($timeStampedToken)) +$hash = -join ($hashBytes | ForEach-Object { $_.ToString("x2") }) +$authentication = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("${yourUserId}:${hash}")) + +# Make POST request with authentication headers +$headers = @{ + "Authorization" = "Basic $authentication" + "Timestamp" = "$timestamp" +} +$response = Invoke-RestMethod -Uri "https://www.quantconnect.com/api/v2/<requestUrl>" -Method Post -Headers $headers -ContentType "application/json" -Body "{}" +Write-Host "Response: $($response | ConvertTo-Json)"+"name": "string" }, "isPinned": true, - "maxFileSize": "string", + "maxFileSize": 0, "sharingTokenBacktest": "q" } ], @@ -48439,7 +48870,7 @@
- object + Grid object
@@ -48448,7 +48879,7 @@
- Configuration of the backtest view grid. + The grid arrangement of charts.@@ -48457,7 +48888,7 @@
- object + Grid object
@@ -48466,7 +48897,7 @@
- Configuration of the live view grid. + The grid arrangement of charts.@@ -48511,7 +48942,7 @@
- object + LiveForm object
@@ -48520,7 +48951,7 @@
- The last live wizard content used. + The live wizard content used.@@ -48583,7 +49014,7 @@
- object + EncryptionKey object
@@ -48592,7 +49023,7 @@
- Text file with at least 32 characters to be used to encrypt the project. + Encryption key details.@@ -48619,7 +49050,7 @@
- int + integer
@@ -48850,7 +49281,7 @@"name": "string" }, "isPinned": true, - "maxFileSize": "string", + "maxFileSize": 0, "sharingTokenBacktest": "q" } @@ -49495,7 +49926,7 @@
- object + BrokerageData object
@@ -49504,7 +49935,7 @@
- /. + Brokerage data saved on live deployment.@@ -51615,7 +52046,7 @@ "name": "string" }, "isPinned": true, - "maxFileSize": "string", + "maxFileSize": 0, "sharingTokenBacktest": "q" } ], @@ -51939,7 +52370,7 @@
- object + Grid object
@@ -51948,7 +52379,7 @@
- Configuration of the backtest view grid. + The grid arrangement of charts.@@ -51957,7 +52388,7 @@
- object + Grid object
@@ -51966,7 +52397,7 @@
- Configuration of the live view grid. + The grid arrangement of charts.@@ -52011,7 +52442,7 @@
- object + LiveForm object
@@ -52020,7 +52451,7 @@
- The last live wizard content used. + The live wizard content used.@@ -52083,7 +52514,7 @@
- object + EncryptionKey object
@@ -52092,7 +52523,7 @@
- Text file with at least 32 characters to be used to encrypt the project. + Encryption key details.@@ -52119,7 +52550,7 @@
- int + integer
@@ -52350,7 +52781,7 @@"name": "string" }, "isPinned": true, - "maxFileSize": "string", + "maxFileSize": 0, "sharingTokenBacktest": "q" } @@ -52995,7 +53426,7 @@
- object + BrokerageData object
@@ -53004,7 +53435,7 @@
- /. + Brokerage data saved on live deployment.@@ -55000,9 +55431,79 @@ Examples
# 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(f"Project Collaborator Deleted Successfully: {result}") + if result['success']: print(f"Project Collaborator Deleted Successfully: {result}") ++ The following example demonstrates how to add a collaborator to all projects that start with a given folder name. +
++@@ -55521,9 +56022,79 @@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()) + +# -------------------- + + +# Define the folder prefix to match (e.g., "SubFolder/") +folder_prefix = "SubFolder/" +# Define collaborator ID (replace with actual user ID) +collaborator_id = 'johnny_walker' +# Send a POST request to the /projects/read endpoint to get all projects +response = post(f'{BASE_URL}/projects/read', headers=get_headers()) +result = response.json() +if result['success']: + # Filter projects that start with the given folder prefix + matching_projects = [ + project for project in result['projects'] + if project['name'].startswith(folder_prefix) + ] + # Add the collaborator to each matching project + for project in matching_projects: + response = post(f'{BASE_URL}/projects/collaboration/create', headers=get_headers(), json={ + "projectId": project['projectId'], + "collaboratorUserId": collaborator_id, + "collaborationLiveControl": True, + "collaborationWrite": True + }) + add_result = response.json() + if add_result['success']: + print(f"Added collaborator to project '{project['name']}' (ID: {project['projectId']})") + else: + print(f"Failed to add collaborator to project '{project['name']}': {add_result}")+Examples
# 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(f"Project Collaborator Deleted Successfully: {result}") + if result['success']: print(f"Project Collaborator Deleted Successfully: {result}") ++ The following example demonstrates how to add a collaborator to all projects that start with a given folder name. +
++@@ -56091,9 +56662,79 @@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()) + +# -------------------- + + +# Define the folder prefix to match (e.g., "SubFolder/") +folder_prefix = "SubFolder/" +# Define collaborator ID (replace with actual user ID) +collaborator_id = 'johnny_walker' +# Send a POST request to the /projects/read endpoint to get all projects +response = post(f'{BASE_URL}/projects/read', headers=get_headers()) +result = response.json() +if result['success']: + # Filter projects that start with the given folder prefix + matching_projects = [ + project for project in result['projects'] + if project['name'].startswith(folder_prefix) + ] + # Add the collaborator to each matching project + for project in matching_projects: + response = post(f'{BASE_URL}/projects/collaboration/create', headers=get_headers(), json={ + "projectId": project['projectId'], + "collaboratorUserId": collaborator_id, + "collaborationLiveControl": True, + "collaborationWrite": True + }) + add_result = response.json() + if add_result['success']: + print(f"Added collaborator to project '{project['name']}' (ID: {project['projectId']})") + else: + print(f"Failed to add collaborator to project '{project['name']}': {add_result}")+Examples
# 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(f"Project Collaborator Deleted Successfully: {result}") + if result['success']: print(f"Project Collaborator Deleted Successfully: {result}") ++ The following example demonstrates how to add a collaborator to all projects that start with a given folder name. +
++@@ -56611,9 +57252,79 @@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()) + +# -------------------- + + +# Define the folder prefix to match (e.g., "SubFolder/") +folder_prefix = "SubFolder/" +# Define collaborator ID (replace with actual user ID) +collaborator_id = 'johnny_walker' +# Send a POST request to the /projects/read endpoint to get all projects +response = post(f'{BASE_URL}/projects/read', headers=get_headers()) +result = response.json() +if result['success']: + # Filter projects that start with the given folder prefix + matching_projects = [ + project for project in result['projects'] + if project['name'].startswith(folder_prefix) + ] + # Add the collaborator to each matching project + for project in matching_projects: + response = post(f'{BASE_URL}/projects/collaboration/create', headers=get_headers(), json={ + "projectId": project['projectId'], + "collaboratorUserId": collaborator_id, + "collaborationLiveControl": True, + "collaborationWrite": True + }) + add_result = response.json() + if add_result['success']: + print(f"Added collaborator to project '{project['name']}' (ID: {project['projectId']})") + else: + print(f"Failed to add collaborator to project '{project['name']}': {add_result}")+Examples
# 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(f"Project Collaborator Deleted Successfully: {result}") + if result['success']: print(f"Project Collaborator Deleted Successfully: {result}") ++ The following example demonstrates how to add a collaborator to all projects that start with a given folder name. +
++@@ -56914,9 +57625,79 @@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()) + +# -------------------- + + +# Define the folder prefix to match (e.g., "SubFolder/") +folder_prefix = "SubFolder/" +# Define collaborator ID (replace with actual user ID) +collaborator_id = 'johnny_walker' +# Send a POST request to the /projects/read endpoint to get all projects +response = post(f'{BASE_URL}/projects/read', headers=get_headers()) +result = response.json() +if result['success']: + # Filter projects that start with the given folder prefix + matching_projects = [ + project for project in result['projects'] + if project['name'].startswith(folder_prefix) + ] + # Add the collaborator to each matching project + for project in matching_projects: + response = post(f'{BASE_URL}/projects/collaboration/create', headers=get_headers(), json={ + "projectId": project['projectId'], + "collaboratorUserId": collaborator_id, + "collaborationLiveControl": True, + "collaborationWrite": True + }) + add_result = response.json() + if add_result['success']: + print(f"Added collaborator to project '{project['name']}' (ID: {project['projectId']})") + else: + print(f"Failed to add collaborator to project '{project['name']}': {add_result}")+Examples
# 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(f"Project Collaborator Deleted Successfully: {result}") + if result['success']: print(f"Project Collaborator Deleted Successfully: {result}") ++ The following example demonstrates how to add a collaborator to all projects that start with a given folder name. +
++@@ -62086,98 +62867,7 @@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()) + +# -------------------- + + +# Define the folder prefix to match (e.g., "SubFolder/") +folder_prefix = "SubFolder/" +# Define collaborator ID (replace with actual user ID) +collaborator_id = 'johnny_walker' +# Send a POST request to the /projects/read endpoint to get all projects +response = post(f'{BASE_URL}/projects/read', headers=get_headers()) +result = response.json() +if result['success']: + # Filter projects that start with the given folder prefix + matching_projects = [ + project for project in result['projects'] + if project['name'].startswith(folder_prefix) + ] + # Add the collaborator to each matching project + for project in matching_projects: + response = post(f'{BASE_URL}/projects/collaboration/create', headers=get_headers(), json={ + "projectId": project['projectId'], + "collaboratorUserId": collaborator_id, + "collaborationLiveControl": True, + "collaborationWrite": True + }) + add_result = response.json() + if add_result['success']: + print(f"Added collaborator to project '{project['name']}' (ID: {project['projectId']})") + else: + print(f"Failed to add collaborator to project '{project['name']}': {add_result}")+}, "parameterSet": , "rollingWindow": { - "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": [ - { - "symbol": { - "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 - } - ] - }, + }, "runtimeStatistics": { "Equity": "$100.00", "Fees": "-$100.00", @@ -62312,7 +63002,21 @@
}, "nodeName": "string", "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z", - "outOfSampleDays": 0 + "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, @@ -62701,7 +63405,7 @@
- AlgorithmPerformance object + object
Rolling window detailed statistics. @@ -62749,7 +63453,7 @@
- object + AlgorithmPerformance object
@@ -62758,7 +63462,7 @@
- The algorithm performance statistics. + The AlgorithmPerformance class is a wrapper for TradeStatistics and PortfolioStatistics.@@ -62803,6 +63507,18 @@ +Number of days of out of sample days.
+ + analysis + ++ ++ AnalysisResult Array ++
+ /. +Example @@ -62838,98 +63554,7 @@ @@ -63175,1223 +63814,1204 @@}, "parameterSet": , "rollingWindow": { - "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": [ - { - "symbol": { - "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 - } - ] - }, +}, "runtimeStatistics": { "Equity": "$100.00", "Fees": "-$100.00", @@ -63064,7 +63689,21 @@
}, "nodeName": "string", "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z", - "outOfSampleDays": 0 + "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." + ] + } + ] }
- AlgorithmPerformance + RuntimeStatistics- Model - The AlgorithmPerformance class is a wrapper for TradeStatistics and PortfolioStatistics. + Model- tradeStatistics + Equity - TradeStatistics object + string +
+ + + example: $100.00 + +
- A set of statistics calculated from a list of closed trades. + Total portfolio value.- portfolioStatistics + Fees - PortfolioStatistics object + string +
+ + + example: -$100.00 + +
- Represents a set of statistics calculated from equity and benchmark samples. + Transaction fee.- closedTrades + Holdings - Trade Array + string +
+ + + example: $100.00 + +
- The algorithm statistics on portfolio. + Equity value of security holdings.- - - Example + Net Profit - -+-{ - "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": [ - { - "symbol": { - "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 - } - ] -}-+ string ++
+ + + example: $100.00 + + +
+ Net profit.- -
+- -- -- TradeStatistics -- Model - A set of statistics calculated from a list of closed trades. -- startDateTime + Probabilistic Sharpe Ratio - string($date-time) + string +
+ + + example: 50.00% + +
- The entry date/time of the first trade. + Probabilistic Sharpe Ratio.- endDateTime + Return - string($date-time) + string +
+ + + example: 50.00% + +
- The exit date/time of the first trade. + Return.- totalNumberOfTrades + Unrealized - integer + string +
+ + + example: $100.00 + +
- The total number of trades. + Unrealized profit/loss.- numberOfWinningTrades + Volume - integer + string +
+ + + example: $100.00 + +
- The total number of winning trades. + Total transaction volume.+ - numberOfLosingTrades + Example - - integer --
- The total number of losing trades. +++{ + "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" +}++ +
++ ++ ++ StatisticsResult ++ Model - Statistics information sent during the algorithm operations. +- totalProfitLoss + Total Orders string
- The total profit/loss for all trades (as symbol currency). + Total nuber of orders.- totalProfit + Average Win string
- The total profit for all winning trades (as symbol currency). + The average rate of return for winning trades.- totalLoss + Average Loss string
- The total loss for all losing trades (as symbol currency). + The average rate of return for losing trades.- largestProfit + Compounding Annual Return string
- The largest profit in a single trade (as symbol currency). + Annual compounded returns statistic based on the final-starting capital and years.- largestLoss + Drawdown string
- The largest loss in a single trade (as symbol currency). + Drawdown maximum percentage.- averageProfitLoss + Expectancy string
- The average profit/loss (a.k.a. Expectancy or Average Trade) for all trades (as symbol currency). + The expected value of the rate of return.- averageProfit + Start Equity string
- The average profit for all winning trades (as symbol currency). + Initial Equity Total Value.- averageLoss + End Equity string
- The average loss for all winning trades (as symbol currency). + Final Equity Total Value.- averageTradeDuration + Net Profit string
- The average duration for all trades. + The total net profit percentage.- averageWinningTradeDuration + Sharpe Ratio string
- The average duration for all winning trades. + Sharpe ratio with respect to risk free rate; measures excess of return per unit of risk.- averageLosingTradeDuration + Sortino Ratio string
- The average duration for all losing trades. + Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk.- medianTradeDuration + Probabilistic Sharpe Ratio string
- The median duration for all trades. + 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.- medianWinningTradeDuration + Loss Rate string
- The median duration for all winning trades. + The ratio of the number of losing trades to the total number of trades.- medianLosingTradeDuration + Win Rate string
- The median duration for all losing trades. + The ratio of the number of winning trades to the total number of trades.- maxConsecutiveWinningTrades + Profit-Loss Ratio - integer + string
- The maximum number of consecutive winning trades. + The ratio of the average win rate to the average loss rate.- maxConsecutiveLosingTrades + Alpha - integer + string
- The maximum number of consecutive losing trades. + Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns.- profitLossRatio + Beta string
- The ratio of the average profit per trade to the average loss per trade. + Algorithm "beta" statistic - the covariance between the algorithm and benchmark performance, divided by benchmark's variance.- winLossRatio + Annual Standard Deviation string
- The ratio of the number of winning trades to the number of losing trades. + Annualized standard deviation.- winRate + Annual Variance string
- The ratio of the number of winning trades to the total number of trades. + Annualized variance statistic calculation using the daily performance variance and trading days per year.- lossRate + Information Ratio string
- The ratio of the number of losing trades to the total number of trades. + Information ratio - risk adjusted return.- averageMAE + Tracking Error string
- The average Maximum Adverse Excursion for all trades. + Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked.- averageMFE + Treynor Ratio string
- The average Maximum Adverse Excursion for all trades. + 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.- largestMAE + Total Fees string
- The average Maximum Favorable Excursion for all trades. + Total amount of fees.- largestMFE + Estimated Strategy Capacity string
- The largest Maximum Adverse Excursion in a single trade (as symbol currency). + The estimated total capacity of the strategy at a point in time.- maximumClosedTradeDrawdown + Lowest Capacity Asset string
- The maximum closed-trade drawdown for all trades (as symbol currency). + Provide a reference to the lowest capacity symbol used in scaling down the capacity for debugging.- maximumIntraTradeDrawdown + Portfolio Turnover string
- The maximum intra-trade drawdown for all trades (as symbol currency). + The average Portfolio Turnover.- profitLossStandardDeviation + Drawdown Recovery string
- The standard deviation of the profits/losses for all trades (as symbol currency). + /.+ - profitLossDownsideDeviation + Example - - string --
- The downside deviation of the profits/losses for all trades (as symbol currency). +++{ + "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. +- profitFactor + tradeStatistics - string + TradeStatistics object
- The ratio of the total profit to the total loss. + A set of statistics calculated from a list of closed trades.- sharpeRatio + portfolioStatistics - string + PortfolioStatistics object
- The ratio of the average profit/loss to the standard deviation. + Represents a set of statistics calculated from equity and benchmark samples.- sortinoRatio + closedTrades - string + Trade Array
- The ratio of the average profit/loss to the downside deviation. + The algorithm statistics on portfolio.+ - profitToMaxDrawdownRatio + Example - - string --
- The ratio of the total profit/loss to the maximum closed trade drawdown. +++{ + "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": [ + { + "symbol": { + "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 + } + ] +}++ +
-+ ++ ++ TradeStatistics ++ Model - A set of statistics calculated from a list of closed trades. +- maximumEndTradeDrawdown + startDateTime - string + string($date-time)
- The maximum amount of profit given back by a single trade before exit (as symbol currency). + The entry date/time of the first trade.- averageEndTradeDrawdown + endDateTime - string + string($date-time)
- The average amount of profit given back by all trades before exit (as symbol currency). + The exit date/time of the first trade.- maximumDrawdownDuration + totalNumberOfTrades - string + integer
- The maximum amount of time to recover from a drawdown (longest time between new equity highs or peaks). + The total number of trades.- totalFees + numberOfWinningTrades - string + integer
- The sum of fees for all trades. + The total number of winning trades.- - Example + numberOfLosingTrades - -+-{ - "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" -}-+ integer ++
+ The total number of losing trades.- -
-- -- -- PortfolioStatistics -- Model - Represents a set of statistics calculated from equity and benchmark samples. -- averageWinRate + totalProfitLoss string
- The average rate of return for winning trades. + The total profit/loss for all trades (as symbol currency).- averageLossRate + totalProfit string
- The average rate of return for losing trades. + The total profit for all winning trades (as symbol currency).- profitLossRatio + totalLoss string
- The ratio of the average win rate to the average loss rate. + The total loss for all losing trades (as symbol currency).- winRate + largestProfit string
- The ratio of the number of winning trades to the total number of trades. + The largest profit in a single trade (as symbol currency).- lossRate + largestLoss string
- The ratio of the number of losing trades to the total number of trades. + The largest loss in a single trade (as symbol currency).- expectancy + averageProfitLoss string
- The expected value of the rate of return. + The average profit/loss (a.k.a. Expectancy or Average Trade) for all trades (as symbol currency).- startEquity + averageProfit string
- Initial Equity Total Value. + The average profit for all winning trades (as symbol currency).- endEquity + averageLoss string
- Final Equity Total Value. + The average loss for all winning trades (as symbol currency).- compoundingAnnualReturn + averageTradeDuration string
- Annual compounded returns statistic based on the final-starting capital and years. + The average duration for all trades.- drawdown + averageWinningTradeDuration string
- Drawdown maximum percentage. + The average duration for all winning trades.- totalNetProfit + averageLosingTradeDuration string
- The total net profit percentage. + The average duration for all losing trades.- sharpeRatio + medianTradeDuration string
- Sharpe ratio with respect to risk free rate: measures excess of return per unit of risk. + The median duration for all trades.- probabilisticSharpeRatio + medianWinningTradeDuration 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. + The median duration for all winning trades.- sortinoRatio + medianLosingTradeDuration string
- Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk. + The median duration for all losing trades.- alpha + maxConsecutiveWinningTrades - string + integer
- Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns. + The maximum number of consecutive winning trades.- beta + maxConsecutiveLosingTrades - string + integer
- Algorithm beta statistic - the covariance between the algorithm and benchmark performance, divided by benchmark variance. + The maximum number of consecutive losing trades.- annualStandardDeviation + profitLossRatio string
- Annualized standard deviation. + The ratio of the average profit per trade to the average loss per trade.- annualVariance + winLossRatio string
- Annualized variance statistic calculation using the daily performance variance and trading days per year. + The ratio of the number of winning trades to the number of losing trades.- informationRatio + winRate string
- Information ratio - risk adjusted return. + The ratio of the number of winning trades to the total number of trades.- trackingError + lossRate string
- Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked. + The ratio of the number of losing trades to the total number of trades.- treynorRatio + averageMAE 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. + The average Maximum Adverse Excursion for all trades.- portfolioTurnover + averageMFE string
- The average Portfolio Turnover. + The average Maximum Adverse Excursion for all trades.- valueAtRisk99 + largestMAE 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. + The average Maximum Favorable Excursion for all trades.- valueAtRisk95 + largestMFE 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. + The largest Maximum Adverse Excursion in a single trade (as symbol currency).- drawdownRecovery + maximumClosedTradeDrawdown string
- /. + The maximum closed-trade drawdown for all trades (as symbol currency).- - Example + maximumIntraTradeDrawdown - -+-{ - "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" -}-+ string ++
+ The maximum intra-trade drawdown for all trades (as symbol currency).- -
-- -- -- Trade -- Model - Represents a closed trade. -- symbol + profitLossStandardDeviation - Symbol object + string
- 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. + The standard deviation of the profits/losses for all trades (as symbol currency).- entryTime + profitLossDownsideDeviation - string($date-time) + string
- The date and time the trade was opened. + The downside deviation of the profits/losses for all trades (as symbol currency).- entryPrice + profitFactor - number + string
- The price at which the trade was opened (or the average price if multiple entries). + The ratio of the total profit to the total loss.- direction + sharpeRatio - integer Enum + string
- Direction of a trade. 0=Long, 1=Short. Options : [0, 1] + The ratio of the average profit/loss to the standard deviation.- quantity + sortinoRatio - number + string
- The total unsigned quantity of the trade. + The ratio of the average profit/loss to the downside deviation.- - exitTime + profitToMaxDrawdownRatio - - 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 + string
- The total fees associated with the trade (always positive value) (as account currency). + The ratio of the total profit/loss to the maximum closed trade drawdown.- mae + maximumEndTradeDrawdown - number + string
- The Maximum Adverse Excursion (as account currency). + The maximum amount of profit given back by a single trade before exit (as symbol currency).- mfe + averageEndTradeDrawdown - number + string
- The Maximum Favorable Excursion (as account currency). + The average amount of profit given back by all trades before exit (as symbol currency).- duration + maximumDrawdownDuration string
- The duration of the trade. + The maximum amount of time to recover from a drawdown (longest time between new equity highs or peaks).- endTradeDrawdown + totalFees - number + string
- The amount of profit given back before the trade was closed. + The sum of fees for all trades.@@ -64402,23 +65022,47 @@
@@ -64429,573 +65073,515 @@{ - "symbol": { - "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 + "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" }
- Symbol + PortfolioStatistics- 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. + Model - Represents a set of statistics calculated from equity and benchmark samples.- value + averageWinRate string
- The current symbol for this ticker. + The average rate of return for winning trades.- id + averageLossRate string
- The security identifier for this symbol. + The average rate of return for losing trades.- - permtick + profitLossRatio - string
- The ticker at IPO for this security. -- -- Example - -- -+ The ratio of the average win rate to the average loss rate.-{ - "value": "string", - "id": "string", - "permtick": "string" -}-- -
-- -- -- RuntimeStatistics -- Model -- Equity + winRate string -
- - - example: $100.00 - -
- Total portfolio value. + The ratio of the number of winning trades to the total number of trades.- Fees + lossRate string -
- - - example: -$100.00 - -
- Transaction fee. + The ratio of the number of losing trades to the total number of trades.- Holdings + expectancy string -
- - - example: $100.00 - -
- Equity value of security holdings. + The expected value of the rate of return.- Net Profit + startEquity string -
- - - example: $100.00 - -
- Net profit. + Initial Equity Total Value.- Probabilistic Sharpe Ratio + endEquity string -
- - - example: 50.00% - -
- Probabilistic Sharpe Ratio. + Final Equity Total Value.- Return + compoundingAnnualReturn string -
- - - example: 50.00% - -
- Return. + Annual compounded returns statistic based on the final-starting capital and years.- Unrealized + drawdown string -
- - - example: $100.00 - -
- Unrealized profit/loss. + Drawdown maximum percentage.- Volume + totalNetProfit string -
- - - example: $100.00 - -
- Total transaction volume. + The total net profit percentage.- - Example + sharpeRatio - -+-{ - "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" -}-+ string ++
+ Sharpe ratio with respect to risk free rate: measures excess of return per unit of risk.- -
+- -- -- StatisticsResult -- Model - Statistics information sent during the algorithm operations. -- Total Orders + probabilisticSharpeRatio string
- Total nuber of orders. + 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.- Average Win + sortinoRatio string
- The average rate of return for winning trades. + Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk.- Average Loss + alpha string
- The average rate of return for losing trades. + Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns.- Compounding Annual Return + beta string
- Annual compounded returns statistic based on the final-starting capital and years. + Algorithm beta statistic - the covariance between the algorithm and benchmark performance, divided by benchmark variance.- Drawdown + annualStandardDeviation string
- Drawdown maximum percentage. + Annualized standard deviation.- Expectancy + annualVariance string
- The expected value of the rate of return. + Annualized variance statistic calculation using the daily performance variance and trading days per year.- Start Equity + informationRatio string
- Initial Equity Total Value. + Information ratio - risk adjusted return.- End Equity + trackingError string
- Final Equity Total Value. + Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked.- Net Profit + treynorRatio string
- The total net profit percentage. + 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.- Sharpe Ratio + portfolioTurnover string
- Sharpe ratio with respect to risk free rate; measures excess of return per unit of risk. + The average Portfolio Turnover.- Sortino Ratio + valueAtRisk99 string
- Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk. + 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.- Probabilistic Sharpe Ratio + valueAtRisk95 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. + 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.- Loss Rate + drawdownRecovery string
- The ratio of the number of losing trades to the total number of trades. + /.+ - Win Rate + Example - - string --
- The ratio of the number of winning trades to the total number of trades. +++{ + "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" +}++ +
-+ ++ ++ Trade ++ Model - Represents a closed trade. +- Profit-Loss Ratio + symbol - string + Symbol object
- The ratio of the average win rate to the average loss rate. + 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.- Alpha + entryTime - string + string($date-time)
- Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns. + The date and time the trade was opened.- Beta + entryPrice - string + number
- Algorithm "beta" statistic - the covariance between the algorithm and benchmark performance, divided by benchmark's variance. + The price at which the trade was opened (or the average price if multiple entries).- Annual Standard Deviation + direction - string + integer Enum
- Annualized standard deviation. + Direction of a trade. 0=Long, 1=Short. Options : [0, 1]- Annual Variance + quantity - string + number
- Annualized variance statistic calculation using the daily performance variance and trading days per year. + The total unsigned quantity of the trade.- Information Ratio + exitTime - string + string($date-time)
- Information ratio - risk adjusted return. + The date and time the trade was closed.- Tracking Error + exitPrice - string + number
- Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked. + The price at which the trade was closed (or the average price if multiple exits).- Treynor Ratio + profitLoss - string + number
- 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. + The gross profit/loss of the trade (as account currency).- Total Fees + totalFees - string + number
- Total amount of fees. + The total fees associated with the trade (always positive value) (as account currency).- Estimated Strategy Capacity + mae - string + number
- The estimated total capacity of the strategy at a point in time. + The Maximum Adverse Excursion (as account currency).- Lowest Capacity Asset + mfe - string + number
- Provide a reference to the lowest capacity symbol used in scaling down the capacity for debugging. + The Maximum Favorable Excursion (as account currency).- Portfolio Turnover + duration string
- The average Portfolio Turnover. + The duration of the trade.- Drawdown Recovery + endTradeDrawdown - string + number
- /. + The amount of profit given back before the trade was closed.@@ -65006,70 +65592,265 @@
{ - "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" + "symbol": { + "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 }- 401 Authentication Error -
- - - -
- UnauthorizedError + Symbol- Model - Unauthorized response from the API. Key is missing, invalid, or timestamp is too old for hash. + 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.- - www_authenticate + value string
- Header + The current symbol for this ticker.Examples
- ++ ++ 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. @@ -65473,98 +66254,7 @@
}, "parameterSet": , "rollingWindow": { - "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": [ - { - "symbol": { - "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 - } - ] - }, + }, "runtimeStatistics": { "Equity": "$100.00", "Fees": "-$100.00", @@ -65699,7 +66389,21 @@
}, "nodeName": "string", "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z", - "outOfSampleDays": 0 + "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, @@ -66088,7 +66792,7 @@
- AlgorithmPerformance object + object
Rolling window detailed statistics. @@ -66136,7 +66840,7 @@
- object + AlgorithmPerformance object
@@ -66145,7 +66849,7 @@
- The algorithm performance statistics. + The AlgorithmPerformance class is a wrapper for TradeStatistics and PortfolioStatistics.@@ -66190,6 +66894,18 @@ +Number of days of out of sample days.
+ + analysis + ++ ++ AnalysisResult Array ++
+ /. +Example @@ -66225,98 +66941,7 @@ @@ -66562,1163 +67201,1192 @@}, "parameterSet": , "rollingWindow": { - "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": [ - { - "symbol": { - "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 - } - ] - }, +}, "runtimeStatistics": { "Equity": "$100.00", "Fees": "-$100.00", @@ -66451,7 +67076,21 @@
}, "nodeName": "string", "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z", - "outOfSampleDays": 0 + "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." + ] + } + ] }
- AlgorithmPerformance + RuntimeStatistics- Model - The AlgorithmPerformance class is a wrapper for TradeStatistics and PortfolioStatistics. + Model- tradeStatistics + Equity - TradeStatistics object + string +
+ + + example: $100.00 + +
- A set of statistics calculated from a list of closed trades. + Total portfolio value.- portfolioStatistics + Fees - PortfolioStatistics object + string +
+ + + example: -$100.00 + +
- Represents a set of statistics calculated from equity and benchmark samples. + Transaction fee.- closedTrades + Holdings - Trade Array + string +
+ + + example: $100.00 + +
- The algorithm statistics on portfolio. + Equity value of security holdings.- - - Example + Net Profit - -+-{ - "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": [ - { - "symbol": { - "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 - } - ] -}-+ string ++
+ + + example: $100.00 + + +
+ Net profit.- -
+- -- -- TradeStatistics -- Model - A set of statistics calculated from a list of closed trades. -- startDateTime + Probabilistic Sharpe Ratio - string($date-time) + string +
+ + + example: 50.00% + +
- The entry date/time of the first trade. + Probabilistic Sharpe Ratio.- endDateTime + Return - string($date-time) + string +
+ + + example: 50.00% + +
- The exit date/time of the first trade. + Return.- totalNumberOfTrades + Unrealized - integer + string +
+ + + example: $100.00 + +
- The total number of trades. + Unrealized profit/loss.- numberOfWinningTrades + Volume - integer + string +
+ + + example: $100.00 + +
- The total number of winning trades. + Total transaction volume.+ - numberOfLosingTrades + Example - - integer --
- The total number of losing trades. +++{ + "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" +}++ +
++ ++ ++ StatisticsResult ++ Model - Statistics information sent during the algorithm operations. +- totalProfitLoss + Total Orders string
- The total profit/loss for all trades (as symbol currency). + Total nuber of orders.- totalProfit + Average Win string
- The total profit for all winning trades (as symbol currency). + The average rate of return for winning trades.- totalLoss + Average Loss string
- The total loss for all losing trades (as symbol currency). + The average rate of return for losing trades.- largestProfit + Compounding Annual Return string
- The largest profit in a single trade (as symbol currency). + Annual compounded returns statistic based on the final-starting capital and years.- largestLoss + Drawdown string
- The largest loss in a single trade (as symbol currency). + Drawdown maximum percentage.- averageProfitLoss + Expectancy string
- The average profit/loss (a.k.a. Expectancy or Average Trade) for all trades (as symbol currency). + The expected value of the rate of return.- averageProfit + Start Equity string
- The average profit for all winning trades (as symbol currency). + Initial Equity Total Value.- averageLoss + End Equity string
- The average loss for all winning trades (as symbol currency). + Final Equity Total Value.- averageTradeDuration + Net Profit string
- The average duration for all trades. + The total net profit percentage.- averageWinningTradeDuration + Sharpe Ratio string
- The average duration for all winning trades. + Sharpe ratio with respect to risk free rate; measures excess of return per unit of risk.- averageLosingTradeDuration + Sortino Ratio string
- The average duration for all losing trades. + Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk.- medianTradeDuration + Probabilistic Sharpe Ratio string
- The median duration for all trades. + 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.- medianWinningTradeDuration + Loss Rate string
- The median duration for all winning trades. + The ratio of the number of losing trades to the total number of trades.- medianLosingTradeDuration + Win Rate string
- The median duration for all losing trades. + The ratio of the number of winning trades to the total number of trades.- maxConsecutiveWinningTrades + Profit-Loss Ratio - integer + string
- The maximum number of consecutive winning trades. + The ratio of the average win rate to the average loss rate.- maxConsecutiveLosingTrades + Alpha - integer + string
- The maximum number of consecutive losing trades. + Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns.- profitLossRatio + Beta string
- The ratio of the average profit per trade to the average loss per trade. + Algorithm "beta" statistic - the covariance between the algorithm and benchmark performance, divided by benchmark's variance.- winLossRatio + Annual Standard Deviation string
- The ratio of the number of winning trades to the number of losing trades. + Annualized standard deviation.- winRate + Annual Variance string
- The ratio of the number of winning trades to the total number of trades. + Annualized variance statistic calculation using the daily performance variance and trading days per year.- lossRate + Information Ratio string
- The ratio of the number of losing trades to the total number of trades. + Information ratio - risk adjusted return.- averageMAE + Tracking Error string
- The average Maximum Adverse Excursion for all trades. + Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked.- averageMFE + Treynor Ratio string
- The average Maximum Adverse Excursion for all trades. + 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.- largestMAE + Total Fees string
- The average Maximum Favorable Excursion for all trades. + Total amount of fees.- largestMFE + Estimated Strategy Capacity string
- The largest Maximum Adverse Excursion in a single trade (as symbol currency). + The estimated total capacity of the strategy at a point in time.- maximumClosedTradeDrawdown + Lowest Capacity Asset string
- The maximum closed-trade drawdown for all trades (as symbol currency). + Provide a reference to the lowest capacity symbol used in scaling down the capacity for debugging.- maximumIntraTradeDrawdown + Portfolio Turnover string
- The maximum intra-trade drawdown for all trades (as symbol currency). + The average Portfolio Turnover.- profitLossStandardDeviation + Drawdown Recovery string
- The standard deviation of the profits/losses for all trades (as symbol currency). + /.+ - profitLossDownsideDeviation + Example - - string --
- The downside deviation of the profits/losses for all trades (as symbol currency). +++{ + "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. +- profitFactor + tradeStatistics - string + TradeStatistics object
- The ratio of the total profit to the total loss. + A set of statistics calculated from a list of closed trades.- sharpeRatio + portfolioStatistics - string + PortfolioStatistics object
- The ratio of the average profit/loss to the standard deviation. + Represents a set of statistics calculated from equity and benchmark samples.- sortinoRatio + closedTrades - string + Trade Array
- The ratio of the average profit/loss to the downside deviation. + The algorithm statistics on portfolio.+ - profitToMaxDrawdownRatio + 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": [ + { + "symbol": { + "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 + } + ] +}++ +
-+ + ++ ++ TradeStatistics ++ Model - A set of statistics calculated from a list of closed trades. ++ + startDateTime - string + string($date-time)
- The ratio of the total profit/loss to the maximum closed trade drawdown. + The entry date/time of the first trade.- maximumEndTradeDrawdown + endDateTime - string + string($date-time)
- The maximum amount of profit given back by a single trade before exit (as symbol currency). + The exit date/time of the first trade.- averageEndTradeDrawdown + totalNumberOfTrades - string + integer
- The average amount of profit given back by all trades before exit (as symbol currency). + The total number of trades.- maximumDrawdownDuration + numberOfWinningTrades - string + integer
- The maximum amount of time to recover from a drawdown (longest time between new equity highs or peaks). + The total number of winning trades.- totalFees + numberOfLosingTrades - string + integer
- The sum of fees for all trades. + The total number of losing trades.- - Example + totalProfitLoss - -+-{ - "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" -}-+ string ++
+ The total profit/loss for all trades (as symbol currency).- -
-- -- -- PortfolioStatistics -- Model - Represents a set of statistics calculated from equity and benchmark samples. -- averageWinRate + totalProfit string
- The average rate of return for winning trades. + The total profit for all winning trades (as symbol currency).- averageLossRate + totalLoss string
- The average rate of return for losing trades. + The total loss for all losing trades (as symbol currency).- profitLossRatio + largestProfit string
- The ratio of the average win rate to the average loss rate. + The largest profit in a single trade (as symbol currency).- winRate + largestLoss string
- The ratio of the number of winning trades to the total number of trades. + The largest loss in a single trade (as symbol currency).- lossRate + averageProfitLoss string
- The ratio of the number of losing trades to the total number of trades. + The average profit/loss (a.k.a. Expectancy or Average Trade) for all trades (as symbol currency).- expectancy + averageProfit string
- The expected value of the rate of return. + The average profit for all winning trades (as symbol currency).- startEquity + averageLoss string
- Initial Equity Total Value. + The average loss for all winning trades (as symbol currency).- endEquity + averageTradeDuration string
- Final Equity Total Value. + The average duration for all trades.- compoundingAnnualReturn + averageWinningTradeDuration string
- Annual compounded returns statistic based on the final-starting capital and years. + The average duration for all winning trades.- drawdown + averageLosingTradeDuration string
- Drawdown maximum percentage. + The average duration for all losing trades.- totalNetProfit + medianTradeDuration string
- The total net profit percentage. + The median duration for all trades.- sharpeRatio + medianWinningTradeDuration string
- Sharpe ratio with respect to risk free rate: measures excess of return per unit of risk. + The median duration for all winning trades.- probabilisticSharpeRatio + medianLosingTradeDuration 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. + The median duration for all losing trades.- sortinoRatio + maxConsecutiveWinningTrades - string + integer
- Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk. + The maximum number of consecutive winning trades.- alpha + maxConsecutiveLosingTrades - string + integer
- Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns. + The maximum number of consecutive losing trades.- beta + profitLossRatio string
- Algorithm beta statistic - the covariance between the algorithm and benchmark performance, divided by benchmark variance. + The ratio of the average profit per trade to the average loss per trade.- annualStandardDeviation + winLossRatio string
- Annualized standard deviation. + The ratio of the number of winning trades to the number of losing trades.- annualVariance + winRate string
- Annualized variance statistic calculation using the daily performance variance and trading days per year. + The ratio of the number of winning trades to the total number of trades.- informationRatio + lossRate string
- Information ratio - risk adjusted return. + The ratio of the number of losing trades to the total number of trades.- trackingError + averageMAE string
- Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked. + The average Maximum Adverse Excursion for all trades.- treynorRatio + averageMFE 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. + The average Maximum Adverse Excursion for all trades.- portfolioTurnover + largestMAE string
- The average Portfolio Turnover. + The average Maximum Favorable Excursion for all trades.- valueAtRisk99 + largestMFE 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. + The largest Maximum Adverse Excursion in a single trade (as symbol currency).- valueAtRisk95 + maximumClosedTradeDrawdown 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. + The maximum closed-trade drawdown for all trades (as symbol currency).- drawdownRecovery + maximumIntraTradeDrawdown string
- /. + The maximum intra-trade drawdown for all trades (as symbol currency).- - Example + profitLossStandardDeviation - -+-{ - "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" -}-+ string ++
+ The standard deviation of the profits/losses for all trades (as symbol currency).- -
+- -- -- Trade -- Model - Represents a closed trade. -- symbol + profitLossDownsideDeviation - Symbol object + string
- 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. + The downside deviation of the profits/losses for all trades (as symbol currency).- entryTime + profitFactor - string($date-time) + string
- The date and time the trade was opened. + The ratio of the total profit to the total loss.- entryPrice + sharpeRatio - number + string
- The price at which the trade was opened (or the average price if multiple entries). + The ratio of the average profit/loss to the standard deviation.- direction + sortinoRatio - integer Enum + string
- Direction of a trade. 0=Long, 1=Short. Options : [0, 1] + The ratio of the average profit/loss to the downside deviation.- quantity + profitToMaxDrawdownRatio - number + string
- The total unsigned quantity of the trade. + The ratio of the total profit/loss to the maximum closed trade drawdown.- exitTime + maximumEndTradeDrawdown - string($date-time) + string
- The date and time the trade was closed. + The maximum amount of profit given back by a single trade before exit (as symbol currency).- exitPrice + averageEndTradeDrawdown - number + string
- The price at which the trade was closed (or the average price if multiple exits). + The average amount of profit given back by all trades before exit (as symbol currency).- profitLoss + maximumDrawdownDuration - number + string
- The gross profit/loss of the trade (as account currency). + The maximum amount of time to recover from a drawdown (longest time between new equity highs or peaks).@@ -67727,662 +68395,792 @@
- number + string
- The total fees associated with the trade (always positive value) (as account currency). + The sum of fees for all trades.+ - mae + 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 - number + string
- The Maximum Adverse Excursion (as account currency). + The average rate of return for winning trades.- mfe + averageLossRate - number + string
- The Maximum Favorable Excursion (as account currency). + The average rate of return for losing trades.- duration + profitLossRatio string
- The duration of the trade. + The ratio of the average win rate to the average loss rate.- endTradeDrawdown + winRate - number + string
- The amount of profit given back before the trade was closed. + The ratio of the number of winning trades to the total number of trades.- - Example + lossRate - -+-{ - "symbol": { - "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 -}-+ string ++
+ The ratio of the number of losing trades to the total number of trades.- -
-- -- -- 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 + expectancy string
- The current symbol for this ticker. + The expected value of the rate of return.- id + startEquity string
- The security identifier for this symbol. + Initial Equity Total Value.- permtick + endEquity string
- The ticker at IPO for this security. + Final Equity Total Value.- - Example + compoundingAnnualReturn - -+-{ - "value": "string", - "id": "string", - "permtick": "string" -}-+ string ++
+ Annual compounded returns statistic based on the final-starting capital and years.- -
-- -- -- RuntimeStatistics -- Model -- Equity + drawdown string -
- - - example: $100.00 - -
- Total portfolio value. + Drawdown maximum percentage.- Fees + totalNetProfit string -
- - - example: -$100.00 - -
- Transaction fee. + The total net profit percentage.- Holdings + sharpeRatio string -
- - - example: $100.00 - -
- Equity value of security holdings. + Sharpe ratio with respect to risk free rate: measures excess of return per unit of risk.- Net Profit + probabilisticSharpeRatio string -
- - - example: $100.00 - -
- Net profit. + 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.- Probabilistic Sharpe Ratio + sortinoRatio string -
- - - example: 50.00% - -
- Probabilistic Sharpe Ratio. + Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk.- Return + alpha string -
- - - example: 50.00% - -
- Return. + Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns.- Unrealized + beta string -
- - - example: $100.00 - -
- Unrealized profit/loss. + Algorithm beta statistic - the covariance between the algorithm and benchmark performance, divided by benchmark variance.- Volume + annualStandardDeviation string -
- - - example: $100.00 - -
- Total transaction volume. + Annualized standard deviation.- - Example + annualVariance - -+-{ - "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" -}-+ string ++
+ Annualized variance statistic calculation using the daily performance variance and trading days per year.- -
+- -- -- StatisticsResult -- Model - Statistics information sent during the algorithm operations. -+ - Total Orders + informationRatio + ++ ++ string ++
+ Information ratio - risk adjusted return. ++ + trackingError string
- Total nuber of orders. + Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked.- Average Win + treynorRatio string
- The average rate of return for winning trades. + 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.- Average Loss + portfolioTurnover string
- The average rate of return for losing trades. + The average Portfolio Turnover.- Compounding Annual Return + valueAtRisk99 string
- Annual compounded returns statistic based on the final-starting capital and years. + 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.- Drawdown + valueAtRisk95 string
- Drawdown maximum percentage. + 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.- Expectancy + drawdownRecovery string
- The expected value of the rate of return. + /.+ - Start Equity + 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" +}++ +
++ + ++ ++ Trade ++ Model - Represents a closed trade. ++ + symbol - string + Symbol object
- Initial Equity Total Value. + 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.- End Equity + entryTime - string + string($date-time)
- Final Equity Total Value. + The date and time the trade was opened.- Net Profit + entryPrice - string + number
- The total net profit percentage. + The price at which the trade was opened (or the average price if multiple entries).- Sharpe Ratio + direction - string + integer Enum
- Sharpe ratio with respect to risk free rate; measures excess of return per unit of risk. + Direction of a trade. 0=Long, 1=Short. Options : [0, 1]- Sortino Ratio + quantity - string + number
- Sortino ratio with respect to risk free rate; measures excess of return per unit of downside risk. + The total unsigned quantity of the trade.- Probabilistic Sharpe Ratio + exitTime - string + string($date-time)
- 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. + The date and time the trade was closed.- Loss Rate + exitPrice - string + number
- The ratio of the number of losing trades to the total number of trades. + The price at which the trade was closed (or the average price if multiple exits).- Win Rate + profitLoss - string + number
- The ratio of the number of winning trades to the total number of trades. + The gross profit/loss of the trade (as account currency).- Profit-Loss Ratio + totalFees - string + number
- The ratio of the average win rate to the average loss rate. + The total fees associated with the trade (always positive value) (as account currency).- Alpha + mae - string + number
- Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns. + The Maximum Adverse Excursion (as account currency).- Beta + mfe - string + number
- Algorithm "beta" statistic - the covariance between the algorithm and benchmark performance, divided by benchmark's variance. + The Maximum Favorable Excursion (as account currency).- Annual Standard Deviation + duration string
- Annualized standard deviation. + The duration of the trade.- Annual Variance + endTradeDrawdown - string + number
- Annualized variance statistic calculation using the daily performance variance and trading days per year. + The amount of profit given back before the trade was closed.+ - Information Ratio + Example + ++ ++++{ + "symbol": { + "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 +}++ +
++ + ++ ++ 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
- Information ratio - risk adjusted return. + The current symbol for this ticker.- Tracking Error + id string
- Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked. + The security identifier for this symbol.- Treynor Ratio + permtick 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. + The ticker at IPO for this security.+ - Total Fees + Example + ++ ++++{ + "value": "string", + "id": "string", + "permtick": "string" +}++ +
+ + ++ ++ AnalysisResult ++ Model - The result of an analysis performed on a result. ++ + name string +
+ + + required + + +
+ + + example: PerformanceRelativeToBenchmarkAnalysis + +
- Total amount of fees. + The name of the analysis that produced this result.- Estimated Strategy Capacity + issue string +
+ + + required + + +
+ + + example: The strategy has a lower Sharpe ratio than the benchmark. + +
- The estimated total capacity of the strategy at a point in time. + A short description of why the analysis was triggered.- Lowest Capacity Asset + sample - string + object +
+ + + required + + +
+ + + example: {'backtestSharpe': -0.2281345806218534, 'benchmarkSharpe': -0.22182175736916387} + +
- Provide a reference to the lowest capacity symbol used in scaling down the capacity for debugging. + A representative sample value of the issue detected by the analysis.- Portfolio Turnover + count - string + integer +
+ + + example: 5 + +
- The average Portfolio Turnover. + The total number of matching occurrences found by the analysis. If not present, it should be assumed that there is only one occurrence.- Drawdown Recovery + solutions - string + string Array +
+ + + required + +
- /. + Human-readable suggestions for resolving the detected issue.@@ -68393,33 +69191,16 @@ +
@@ -69279,130 +70060,6 @@{ - "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" + "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." + ] }Examples
print("List of Backtests:") print(result) -- The following example demonstrates how to read and plot chart data from a backtest through the cloud API. -
--@@ -78476,128 +79133,6 @@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()) - -# -------------------- - -from time import sleep -import matplotlib.pyplot as plt -import matplotlib.dates as mdates -from datetime import datetime, timedelta - -# The project and backtest ID of the backtest -project_id = 12345678 -backtest_id = "..." - -### Read Backtest Chart -# Define the chart name to retrieve -chart_name = "Strategy Equity" -# Prepare data payload to fetch chart data -payload = { - "projectId": project_id, # ID of the project - "backtestId": backtest_id, # ID of the backtest - "name": chart_name, # Name of the chart to retrieve - "count": 500, # Number of data points to fetch - "start": 1717801200, # Start time in Unix timestamp - "end": 1743462000 # End time in Unix timestamp -} -# Retry up to 10 times if the chart data is still loading -for attempt in range(10): - # Send a POST request to the /backtests/chart/read endpoint - response = post(f'{BASE_URL}/backtests/chart/read', headers=get_headers(), json=payload) - # Parse the JSON response - result = response.json() - # Check if the data is still loading - if result.get('status') == 'loading': - print(f"Chart data is loading... Progress: {result['progress']}% (attempt {attempt + 1}/10)") - sleep(10) - continue - break - -# If the request was successful, extract and plot the chart data -if result['success']: - chart = result['chart'] - # Filter to series with plottable list data points - series_items = [(name, data) for name, data in chart['series'].items() - if data['values'] and isinstance(data['values'][0], list)] - if not series_items: - print("No series data available in the chart.") - else: - # Create a subplot for each series - fig, axes = plt.subplots(len(series_items), 1, figsize=(12, 4 * len(series_items)), sharex=True) - if len(series_items) == 1: - axes = [axes] - for ax, (series_name, series_data) in zip(axes, series_items): - values = series_data['values'] - # Check if the data is OHLC (5 elements: timestamp, open, high, low, close) - is_ohlc = len(values[0]) == 5 - if is_ohlc: - # Filter out data points with None values - valid = [p for p in values if None not in p[1:]] - if not valid: - ax.set_title(f"{series_name} (no valid data)") - continue - timestamps = [datetime.utcfromtimestamp(p[0]) for p in valid] - dates = mdates.date2num(timestamps) - # Calculate bar width as 60% of the average interval between points - bar_width = (dates[-1] - dates[0]) / len(dates) * 0.6 - for i, point in enumerate(valid): - _, o, h, l, c = point - color = 'green' if c >= o else 'red' - # Draw the high-low wick - ax.vlines(dates[i], l, h, color=color, linewidth=0.8) - # Draw the open-close body - ax.bar(dates[i], abs(c - o) or 0.01, bottom=min(o, c), - width=bar_width, color=color, edgecolor=color) - ax.xaxis_date() - ax.set_ylabel("Price") - else: - # Filter out data points with None values - valid = [p for p in values if p[1] is not None] - timestamps = [datetime.utcfromtimestamp(p[0]) for p in valid] - y_values = [p[1] for p in valid] - ax.plot(timestamps, y_values) - ax.set_ylabel("Value") - ax.set_title(series_name) - ax.tick_params(axis='x', rotation=45) - fig.suptitle(chart_name, fontsize=14) - plt.tight_layout() - plt.savefig(f"{project_id}-{backtest_id}-{chart_name.replace(' ', '_')}.png") - plt.show()-Examples
print("List of Live Algorithms:") print(result) -- The following example demonstrates how to read and plot chart data from a live algorithm through the cloud API. -
--@@ -82136,15 +82671,15 @@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()) - -# -------------------- - -from time import sleep -import matplotlib.pyplot as plt -import matplotlib.dates as mdates -from datetime import datetime, timedelta - -# The project ID of the live algorithm -project_id = 23456789 - -### Read Live Algorithm Chart -# Define the chart name to retrieve -chart_name = "Strategy Equity" -# Prepare data payload to fetch chart data -payload = { - "projectId": project_id, # ID of the project that's live trading - "name": chart_name, # Name of the chart to retrieve - "count": 500, # Number of data points to fetch - "start": 1717801200, # Start time in Unix timestamp - "end": 1743462000 # End time in Unix timestamp -} -# Retry up to 10 times if the chart data is still loading -for attempt in range(10): - # Send a POST request to the /live/chart/read endpoint - response = post(f'{BASE_URL}/live/chart/read', headers=get_headers(), json=payload) - # Parse the JSON response - result = response.json() - # Check if the data is still loading - if result.get('status') == 'loading': - print(f"Chart data is loading... Progress: {result['progress']}% (attempt {attempt + 1}/10)") - sleep(10) - continue - break - -# If the request was successful, extract and plot the chart data -if result['success']: - chart = result['chart'] - # Filter to series with plottable list data points - series_items = [(name, data) for name, data in chart['series'].items() - if data['values'] and isinstance(data['values'][0], list)] - if not series_items: - print("No series data available in the chart.") - else: - # Create a subplot for each series - fig, axes = plt.subplots(len(series_items), 1, figsize=(12, 4 * len(series_items)), sharex=True) - if len(series_items) == 1: - axes = [axes] - for ax, (series_name, series_data) in zip(axes, series_items): - values = series_data['values'] - # Check if the data is OHLC (5 elements: timestamp, open, high, low, close) - is_ohlc = len(values[0]) == 5 - if is_ohlc: - # Filter out data points with None values - valid = [p for p in values if None not in p[1:]] - if not valid: - ax.set_title(f"{series_name} (no valid data)") - continue - timestamps = [datetime.utcfromtimestamp(p[0]) for p in valid] - dates = mdates.date2num(timestamps) - # Calculate bar width as 60% of the average interval between points - bar_width = (dates[-1] - dates[0]) / len(dates) * 0.6 - for i, point in enumerate(valid): - _, o, h, l, c = point - color = 'green' if c >= o else 'red' - # Draw the high-low wick - ax.vlines(dates[i], l, h, color=color, linewidth=0.8) - # Draw the open-close body - ax.bar(dates[i], abs(c - o) or 0.01, bottom=min(o, c), - width=bar_width, color=color, edgecolor=color) - ax.xaxis_date() - ax.set_ylabel("Price") - else: - # Filter out data points with None values - valid = [p for p in values if p[1] is not None] - timestamps = [datetime.utcfromtimestamp(p[0]) for p in valid] - y_values = [p[1] for p in valid] - ax.plot(timestamps, y_values) - ax.set_ylabel("Value") - ax.set_title(series_name) - ax.tick_params(axis='x', rotation=45) - fig.suptitle(chart_name, fontsize=14) - plt.tight_layout() - plt.savefig(f"{project_id}-{chart_name.replace(' ', '_')}.png") - plt.show()-Request
"command": { "$type": "OrderCommand", "symbol": { - "id": "BTCUSD 2XR", - "value": "BTCUSD" + "id": "BTCUSD 2XR", + "value": "BTCUSD" }, "order_type": "market", "quantity": "0.1", "limit_price": 0, "stop_price": 0, "tag": "" -} + } } @@ -82510,15 +83045,15 @@Request
"command": { "$type": "OrderCommand", "symbol": { - "id": "BTCUSD 2XR", - "value": "BTCUSD" + "id": "BTCUSD 2XR", + "value": "BTCUSD" }, "order_type": "market", "quantity": "0.1", "limit_price": 0, "stop_price": 0, "tag": "" -} + } } @@ -84565,7 +85100,12 @@} ], "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z", - "outOfSampleDays": 0 + "outOfSampleDays": 0, + "created": "2021-11-26T15:18:27.693Z", + "psr": 0, + "sharpeRatio": 0, + "trades": 0, + "cloneId": 0 }, "success": true, "errors": [ @@ -84911,6 +85451,96 @@
Number of days of out of sample days.
+ ++ created + ++ ++ string($date-time) ++
+ + + required + + +
+ Date and time of when this optimization was created. ++ ++ psr + ++ ++ number ++
+ + + required + + +
+ Probabilistic Sharpe ratio statistic. ++ ++ sharpeRatio + ++ ++ number ++
+ + + required + + +
+ Sharpe ratio statistic. ++ ++ trades + ++ ++ integer ++
+ + + required + + +
+ Number of trades in the best backtest (based on the criterion) of the optimziation. ++ + cloneId + ++ ++ integer ++
+ + + required + + +
+ Id of project where this current project was originally cloned. +Example @@ -84993,7 +85623,12 @@ @@ -92418,7 +93053,7 @@} ], "outOfSampleMaxEndDate": "2021-11-26T15:18:27.693Z", - "outOfSampleDays": 0 + "outOfSampleDays": 0, + "created": "2021-11-26T15:18:27.693Z", + "psr": 0, + "sharpeRatio": 0, + "trades": 0, + "cloneId": 0 }
"version": 2.0, "payload": { "utils.py": "def add(a,b):\n return a+b\n" -}, + }, "payloadType": "StringDict" } diff --git a/single-page/Quantconnect-Lean-Cli.html b/single-page/Quantconnect-Lean-Cli.html index 3e55ed5fc9..112782bacd 100644 --- a/single-page/Quantconnect-Lean-Cli.html +++ b/single-page/Quantconnect-Lean-Cli.html @@ -3006,17 +3006,17 @@
Data that will be purchased and downloaded: -┌───────────────────────────┬─────────┬────────────────────────┬────────────┬─────────┐ -│ Dataset │ Vendor │ Details │ File count │ Price │ -├───────────────────────────┼─────────┼────────────────────────┼────────────┼─────────┤ -│ Binance Crypto Price Data │ CoinAPI │ Data type: Trade │ 32 │ 800 QCC │ -│ │ │ Ticker: BTCBUSD │ │ │ -│ │ │ Resolution: Second │ │ │ -│ │ │ Start date: 2022-05-05 │ │ │ -│ │ │ End date: 2022-06-05 │ │ │ -└───────────────────────────┴─────────┴────────────────────────┴────────────┴─────────┘ -Total price: 800 QCC -Organization balance: 1,000 QCC +┌─────────────┬──────────┬────────────────────────┬────────────┬────────┐ +│ Dataset │ Vendor │ Details │ File count │ Price │ +├─────────────┼──────────┼────────────────────────┼────────────┼────────┤ +│ US Equities │ AlgoSeek │ Data type: Trade │ 3 │ 15 QCC │ +│ │ │ Ticker: SPY │ │ │ +│ │ │ Resolution: Minute │ │ │ +│ │ │ Start date: 2023-01-01 │ │ │ +│ │ │ End date: 2023-01-05 │ │ │ +└─────────────┴──────────┴────────────────────────┴────────────┴────────┘ +Total price: 15 QCC +Organization balance: 10,000 QCC Data Terms of Use has been signed previously. Find full agreement at: https://www.quantconnect.com/terms/data/?organization=<organizationId> @@ -3124,7 +3124,46 @@
lean data download- to start an interactive downloading wizard and then enter the dataset category number. + to start an interactive downloading wizard and then select + + to list the categories in the + + Dataset Market + + . +++ +$ lean data download +Select a historical data provider: +1) Interactive Brokers +2) Oanda +3) Bitfinex +4) Coinbase Advanced Trade +5) Binance +6) Kraken +7) CharlesSchwab +8) IQFeed +9) Polygon +10) FactSet +11) AlphaVantage +12) CoinApi +13) ThetaData +14) QuantConnect +15) Local +16) Terminal Link +17) Bybit +18) TradeStation +19) Alpaca +20) Tastytrade +21) Eze +22) dYdX +23) Databento +Enter an option: 14++ Enter the dataset category number. $ lean data download Select a category: @@ -3147,38 +3186,37 @@
$ lean data download Select a dataset: -1) Binance Crypto Future Margin Rate Data -2) Binance Crypto Future Price Data -3) Binance Crypto Price Data -4) Binance US Crypto Price Data -5) Bitcoin Metadata -6) Bitfinex Crypto Price Data -7) Brain Language Metrics on Company Filings -8) Brain ML Stock Ranking -9) CFD Data -10) Coinbase Crypto Price Data -11) Composite Factor Bundle -12) Cross Asset Model -13) FOREX Data -14) Insider Trading -15) Kraken Crypto Price Data -16) NFT Sales -17) Tactical -18) US Congress Trading -19) US ETF Constituents -20) US Equities -21) US Equity Coarse Universe -22) US Equity Options -23) US Equity Security Master -24) US Federal Reserve (FRED) -25) US Futures -26) US Futures Security Master -27) US Index Options -28) US SEC Filings -29) US Treasury Yield Curve -30) VIX Central Contango -31) VIX Daily Price -Enter an option: 20+1) Bitcoin Metadata +2) Brain Language Metrics on Company Filings +3) Brain ML Stock Ranking +4) CFD Data +5) Composite Factor Bundle +6) Cross Asset Model +7) FOREX Data +8) Insider Trading +9) International Future Universe +10) NFT Sales +11) Tactical +12) US Congress Trading +13) US ETF Constituents +14) US Equities +15) US Equity Coarse Universe +16) US Equity Option Universe +17) US Equity Options +18) US Equity Security Master +19) US Future Option Universe +20) US Future Options +21) US Future Universe +22) US Futures +23) US Futures Security Master +24) US Index Option Universe +25) US Index Options +26) US Interest Rate +27) US SEC Filings +28) US Treasury Yield Curve +29) VIX Central Contango +30) VIX Daily Price +Enter an option: 13If you don't have an active subscription to the US Equity Security Master, you'll get the following error message: @@ -4035,444 +4073,6 @@
Equity Options