API Reference

Authentication

Introduction

You can make authenticated REST requests to the QuantConnect API with your User Id and API Token. You can use the authentication endpoint described in this page to verify it is working correctly.

The base URL of QuantConnect API is https://www.quantconnect.com/api/v2.

Follow these steps to request an API token:

  1. Log in to your account.
  2. In the top navigation bar, click yourUsername > My Account.
  3. On your Account page, in the Security section, click Request Email With Token and Your User-Id for API Requests.
  4. Click OK.

We email you your user Id and API token.

To get the organization Id, open Organization > Home and check the URL. For example, the organization Id of https://www.quantconnect.com/organization/5cad178b20a1d52567b534553413b691 is 5cad178b20a1d52567b534553413b691.

Authenticating Requests

Requests to QuantConnect API v2 require a hashed combination of time, and the API token. The unixtime stamp combination serves as a nonce token as each request is sent with a different signature but never requires sending the API token itself.

Hashing

Follow the below example to create a hashed token for authentication.

// Generate a timestamped SHA-256 hashed API token for secure authentication
using System.Security.Cryptography;
using System.Text;

// 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") ?? "_____";

Dictionary<string, string> GetHeaders()
{
    // 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 }
    };
}
# 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

# 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 hashed 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
    }

Make API Request

Follow the below example to set the authentication headers and make an API request.

// 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 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/'

response = post(f'{BASE_URL}/<request_url>',
                headers = get_headers(),
                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.

# 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)"

Authenticated State Request

Authentication status check endpoint to verify the hashing function is working successfully. The /authenticate API does not require any information, but just an authenticated hash in the header.

Authenticated State Responses

The /authenticate API provides a response in the following format:

200 Success

RestResponse Model - Base API response class for the QuantConnect API.
success boolean
Indicate if the API request was successful.
Example
{
  "success": true
}

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

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: