book
Checkout our new book! Hands on AI Trading with Python, QuantConnect, and AWS Learn More arrow

Read Live Algorithm

Live Algorithm Statistics

Introduction

If a ReadLiveAlgorithmRequest is provided details on a live algorithm are returned. If a ListLiveAlgorithmsRequest is passed get a list of live running algorithms.

Request

Dynamic arguement to specify whether seeking single project or list response. The /live/read API accepts requests in the following format:

ReadLiveAlgorithmRequest Model - Request to read out a single algorithm.
projectId integer
required
example: 23456789

Id of the project to read.
deployId string
example: L-sdf86b7045bb83203e79d2aa6150b321

Specific instance Id to read.
Example
{
  "projectId": 23456789,
  "deployId": "L-sdf86b7045bb83203e79d2aa6150b321"
}

Responses

The /live/read API provides a response in the following format:

200 Success

LiveAlgorithmResults Model - Details a live algorithm from the live/read API endpoint.
message string
example: message

Error message.
status string
example: Running

Indicates the status of the algorihtm, i.e. 'Running', 'Stopped'.
deployId string
example: L-sdf86b7045bb83203e79d2aa6150b321

Algorithm deployment ID.
cloneId integer
The snapshot project ID for cloning the live development's source code.
launched string
Date the live algorithm was launched.
stopped string
Date the live algorithm was stopped.
brokerage string
Brokerage used in the live algorithm.
securityTypes string
Security types present in the live algorithm.
projectName string
Name of the project the live algorithm is in.
dataCenter string
Name of the data center where the algorithm is physically located.
public boolean
Indicates if the algorithm is being live shared.
files ProjectFile Array
Files present in the project in which the algorithm is.
runtimeStatistics RuntimeStatistics object
Runtime banner/updating statistics in the title banner of the live algorithm GUI. It can be empty if the algorithm is not running.
charts ChartSummary object
Chart updates for the live algorithm since the last result packet.
success boolean
Indicate if the API request was successful.
errors string Array
List of errors with the API call.
Example
{
  "message": "message",
  "status": "Running",
  "deployId": "L-sdf86b7045bb83203e79d2aa6150b321",
  "cloneId": 0,
  "launched": "string",
  "stopped": "string",
  "brokerage": "string",
  "securityTypes": "string",
  "projectName": "string",
  "dataCenter": "string",
  "public": true,
  "files": [
    {
      "id": 0,
      "projectId": 23456789,
      "name": "string",
      "content": "string",
      "modified": "2021-11-26T15:18:27.693Z",
      "open": true,
      "isLibrary": true
    }
  ],
  "runtimeStatistics": {
    "Equity": "$100.00",
    "Fees": "-$100.00",
    "Holdings": "$100.00",
    "Net Profit": "$100.00",
    "Probabilistic Sharpe Ratio": "50.00%",
    "Return": "50.00%",
    "Unrealized": "$100.00",
    "Volume": "$100.00"
  },
  "charts": {
    "name": "string"
  },
  "success": true,
  "errors": [
    "string"
  ]
}
ProjectFile Model - File for a project.
id integer
ID of the project file. This can also be null.
projectId integer
required
example: 23456789

ID of the project.
name string
Name of a project file.
content string
Contents of the project file.
modified string($date-time)
DateTime project file was modified.
open boolean
Indicates if the project file is open or not.
isLibrary boolean
Indicates if the project file is a library or not. It's always false in live/read and backtest/read.
Example
{
  "id": 0,
  "projectId": 23456789,
  "name": "string",
  "content": "string",
  "modified": "2021-11-26T15:18:27.693Z",
  "open": true,
  "isLibrary": true
}
RuntimeStatistics Model
Equity string
example: $100.00

Total portfolio value.
Fees string
example: -$100.00

Transaction fee.
Holdings string
example: $100.00

Equity value of security holdings.
Net Profit string
example: $100.00

Net profit.
Probabilistic Sharpe Ratio string
example: 50.00%

Probabilistic Sharpe Ratio.
Return string
example: 50.00%

Return.
Unrealized string
example: $100.00

Unrealized profit/loss.
Volume string
example: $100.00

Total transaction volume.
Example
{
  "Equity": "$100.00",
  "Fees": "-$100.00",
  "Holdings": "$100.00",
  "Net Profit": "$100.00",
  "Probabilistic Sharpe Ratio": "50.00%",
  "Return": "50.00%",
  "Unrealized": "$100.00",
  "Volume": "$100.00"
}
ChartSummary Model - Contains the names of all charts
name string
Name of the Chart.
Example
{
  "name": "string"
}

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, and listing live algorithms of a project through the cloud API.

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

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

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

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

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

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

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


### Create Live Algorithm
# Define placeholder IDs for compilation and node (replace with actual values)
project_id = 12345678
compile_id = "compile_id..."
node_id = "node_id..."
# Prepare the data payload for creating a live algorithm with necessary details
payload = {
    "versionId": "-1",  # Use the latest version of the algorithm
    "projectId": project_id,  # ID of the project to deploy as a live algorithm
    "compileId": compile_id,  # Compilation ID for the algorithm code
    "nodeId": node_id,  # Node ID where the algorithm will run
    "brokerage": {  # Brokerage configuration for live trading
        "id": "QuantConnectBrokerage",  # Brokerage identifier
        "user": "",  # Brokerage username (replace with actual value)
        "password": "",  # Brokerage password (replace with actual value)
        "environment": "live-paper",  # Trading environment (live or paper)
        "account": ""  # Brokerage account ID (replace with actual value)
    },
    "dataProviders": {  # Data provider configuration
        "QuantConnectBrokerage": {
            "id": "QuantConnectBrokerage"  # Data provider identifier
        }
    },
    "parameters": {},  # Optional algorithm parameters (empty in this example)
    "notification": {}  # Optional notification settings (empty in this example)
}
# Send a POST request to the /live/create endpoint to deploy the algorithm
response = post(f'{BASE_URL}/live/create', headers=get_headers(), json=data)
# Parse the JSON response into python managable dict from the API
result = response.json()
# Extract the deploy ID from the response for future operations
deploy_id = result['deployId']
# Check if the request was successful and print the result
if result['success']:
    print("Live Algorithm Created Successfully:")
    print(result)

### Read Live Algorithm Statistics
# Prepare data payload with project and deploy IDs to fetch statistics
payload = {
    "projectId": project_id,  # ID of the project
    "deployId": deploy_id  # ID of the deployed live algorithm
}
# Send a POST request to the /live/read endpoint to get algorithm statistics
response = post(f'{BASE_URL}/live/read', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the statistics
if result['success']:
    print("Live Algorithm Statistics:")
    print(result)

### Liquidate Live Algorithm
# Prepare data payload with project ID to liquidate the algorithm
payload = {
    "projectId": project_id  # ID of the project to liquidate
}
# Send a POST request to the /live/update/liquidate endpoint to liquidate
response = post(f'{BASE_URL}/live/update/liquidate', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("Live Algorithm Liquidated Successfully:")
    print(result)

### Stop Live Algorithm
# Prepare data payload with project ID to stop the algorithm
payload = {
    "projectId": project_id  # ID of the project to stop
}
# Send a POST request to the /live/update/stop endpoint to stop the algorithm
response = post(f'{BASE_URL}/live/update/stop', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the result
if result['success']:
    print("Live Algorithm Stopped Successfully:")
    print(result)

### List Live Algorithms
# Prepare data payload with filters for listing live algorithms
payload = {
    "status": "Running",  # Filter to show only running algorithms
    "start": 1717801200,  # Start time (Unix timestamp) for the list range
    "end": 1743462000  # End time (Unix timestamp) for the list range
}
# Send a POST request to the /live/list endpoint to list algorithms
response = post(f'{BASE_URL}/live/list', headers=get_headers(), json=payload)
# Parse the JSON response into python managable dict
result = response.json()
# Check if the request was successful and print the list
if result['success']:
    print("List of Live Algorithms:")
    print(result)

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

Did you find this page helpful?

Contribute to the documentation: