Live Management

Create Live Algorithm

Introduction

Create a live algorithm.

Request

Project, compile, and brokerage login information for deploying a live algorithm. The /live/create API accepts requests in the following format:

CreateLiveAlgorithmRequest Model
versionId integer
required
example: -1

The version of the Lean used to run the algorithm. -1 is master, however, sometimes this can create problems with live deployments. If you experience problems using, try specifying the version of Lean you would like to use.
projectId integer
required
example: 23456789

Project Id.
compileId string
required
example: 5d1f2cba3a0ec7407c566614300502b5-173e0419674daf4144ce7c9931155ca8

Compile Id.
nodeId string
required
example: LN-c54129e1b4f667613d3f34542b787771

Id of the node that will run the algorithm.
parameters string object
Algorithm parameters to set for the deployment, as name-value pairs.
automaticRedeploy boolean
If true, the algorithm uses best efforts to restart after a runtime error, up to five attempts. The default value is false.
signature string
Signature of the project code you expect to deploy. If the project code changed since you read the signature, the request fails. The check doesn't apply to encrypted projects.
notification LiveNotificationSettings object
Notifications to send when the live algorithm emits insights or order events.
dataHandler string
Legacy alternative to dataProviders. Name of the data queue handler to use. You can't send both dataHandler and dataProviders.
brokerage object
required

Brokerage configuration for the live algorithm.
dataProviders object
Dictionary of data provider configurations to be used in the live algorithm. Provide at least one. The order in which you define the providers defines their order of precedence.
Example
{
  "versionId": -1,
  "projectId": 23456789,
  "compileId": "5d1f2cba3a0ec7407c566614300502b5-173e0419674daf4144ce7c9931155ca8",
  "nodeId": "LN-c54129e1b4f667613d3f34542b787771",
  "parameters": {
    "key": "string"
  },
  "automaticRedeploy": true,
  "signature": "string",
  "notification": {
    "events": [
      "string"
    ],
    "targets": [
      {
        "address": "https://www.example.com/webhook",
        "headers": {
          "Authorization": "Bearer token"
        }
      }
    ]
  },
  "dataHandler": "string",
  "brokerage": {
  "QuantConnectBrokerageSettings": object,
  "InteractiveBrokersBrokerageSettings": object,
  "TradierBrokerageSettings": object,
  "BitfinexSettings": object,
  "CoinbaseBrokerageSettings": {
{
      "id": "CoinbaseBrokerage",
      "coinbase-api-name": "string",
      "coinbase-api-private-key": "string"
    },
  },
  "BinanceBrokerageSettings": {
{
      "id": "BinanceBrokerage",
      "binance-exchange-name": "Binance",
      "binance-api-key": "string",
      "binance-api-secret": "string",
      "binance-use-testnet": "live"
    },
  },
  "BinanceUSBrokerageSettings": {
{
      "id": "BinanceBrokerage",
      "binance-exchange-name": "BinanceUS",
      "binanceus-api-key": "string",
      "binanceus-api-secret": "string"
    },
  },
  "BinanceUSDMFuturesBrokerageSettings": {
{
      "id": "BinanceBrokerage",
      "binance-exchange-name": "Binance-USDM-Futures",
      "binance-api-key": "string",
      "binance-api-secret": "string"
    },
  },
  "BinanceCOINFuturesBrokerageSettings": {
{
      "id": "BinanceBrokerage",
      "binance-exchange-name": "Binance-COIN-Futures",
      "binance-api-key": "string",
      "binance-api-secret": "string"
    },
  },
  "TradingTechnologiesBrokerageSettings": object,
  "KrakenSettings": object,
  "BybitBrokerageSettings": {
{
      "id": "BybitBrokerage",
      "bybit-api-key": "string",
      "bybit-api-secret": "string",
      "bybit-vip-level": "VIP0"
    },
  },
  "OandaSettings": object,
  "WolverineSettings": object,
  "CharlesSchwabSettings": object,
  "RBIBrokerageSettings": object,
  "QuantBridgeSettings": object,
  "TradeStationSettings": object,
  "TastytradeSettings": object,
  "AlpacaBrokerageSettings": object,
  "WebullBrokerageSettings": object,
  "PublicBrokerageSettings": object,
  "ClearStreetBrokerageSettings": object,
  "BloombergFixSettings": object,
},
  "dataProviders": 
}
LiveNotificationSettings Model - Notifications to send when the live algorithm emits insights or order events.
events string Array
required

Events that send a notification. If the list is empty, the algorithm sends no notifications.
targets object Array
required
example: [{'address': 'https://www.example.com/webhook', 'headers': {'Authorization': 'Bearer token'}}]

Notification targets. An email target has address and subject, with optional message, data, and headers. A webhook target has address, with optional data and headers. An SMS target has phoneNumber, with optional message. A Telegram target has id, with optional token and message.
Example
{
  "events": [
    "string"
  ],
  "targets": [
    {
      "address": "https://www.example.com/webhook",
      "headers": {
        "Authorization": "Bearer token"
      }
    }
  ]
}
QuantConnectBrokerageSettings Model - Settings for using Paper Trading as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['QuantConnectBrokerage']
holdings BrokerageHolding Array
List of holdings for the brokerage.
cash CashAmount Array
List of cash amount.
Example
{
  "id": "QuantConnectBrokerage",
  "holdings": [
    {
      "symbolId": "BTCUSD 2XR",
      "symbol": "BTCUSD",
      "quantity": 0,
      "averagePrice": 0
    }
  ],
  "cash": [
    {
      "amount": 0,
      "currency": "string"
    }
  ]
}
InteractiveBrokersBrokerageSettings Model - Settings for using Interactive Brokers as the brokerage or a data provider for a live algorithm.
id string Enum
required

Id of the module. Options : ['InteractiveBrokersBrokerage']
ib-user-name string
required

Your Interactive Brokers username.
ib-account string
required

Your Interactive Brokers account id.
ib-password string
required

Your Interactive Brokers password.
ib-weekly-restart-utc-time string
required

Weekly restart UTC time (hh:mm:ss). Each week on Sunday your algorithm restarts at this time and requires 2FA verification. This is required by Interactive Brokers.
ib-financial-advisors-group-filter string
Use this field to filter data by a specific financial advisor group within your Interactive Brokers account. Leave blank to include all groups.
Example
{
  "id": "InteractiveBrokersBrokerage",
  "ib-user-name": "string",
  "ib-account": "string",
  "ib-password": "string",
  "ib-weekly-restart-utc-time": "string",
  "ib-financial-advisors-group-filter": "string"
}
TradierBrokerageSettings Model - Settings for using Tradier as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['TradierBrokerage']
tradier-account-id string
required

Your Tradier account id.
tradier-access-token string
required

Your Tradier access token.
tradier-environment string Enum
required

Whether the developer sandbox should be used. Options : ['live', 'paper']
Example
{
  "id": "TradierBrokerage",
  "tradier-account-id": "string",
  "tradier-access-token": "string",
  "tradier-environment": "live"
}
BitfinexSettings Model - Settings for using Bitfinex as the brokerage or a data provider for a live algorithm.
id string Enum
required

Id of the module. Options : ['BitfinexBrokerage']
bitfinex-api-key string
required

Your Bitfinex API key.
bitfinex-api-secret string
required

Your Bitfinex API secret.
Example
{
  "id": "BitfinexBrokerage",
  "bitfinex-api-key": "string",
  "bitfinex-api-secret": "string"
}
CoinbaseBrokerageAndDataProviderSettings Model
id string Enum
required

Id of the module. Options : ['CoinbaseBrokerage']
coinbase-api-name string
required

Your Coinbase Advanced Trade API name.
coinbase-api-private-key string
required

Your Coinbase Advanced Trade API private key.
Example
{
  "id": "CoinbaseBrokerage",
  "coinbase-api-name": "string",
  "coinbase-api-private-key": "string"
}
BinanceBrokerageAndDataProviderSettings Model
id string Enum
required

Id of the module. Options : ['BinanceBrokerage']
binance-exchange-name string Enum
required

Binance exchange name. Options : ['Binance']
binance-api-key string
required

Your Binance API key.
binance-api-secret string
required

Your Binance API secret.
binance-use-testnet string Enum
required

Whether the testnet should be used. Options : ['live', 'paper']
Example
{
  "id": "BinanceBrokerage",
  "binance-exchange-name": "Binance",
  "binance-api-key": "string",
  "binance-api-secret": "string",
  "binance-use-testnet": "live"
}
BinanceUSBrokerageAndDataProviderSettings Model
id string Enum
required

Id of the module. Options : ['BinanceBrokerage']
binance-exchange-name string Enum
required

Binance exchange name. Options : ['BinanceUS']
binanceus-api-key string
required

Your Binance API key.
binanceus-api-secret string
required

Your Binance API secret.
Example
{
  "id": "BinanceBrokerage",
  "binance-exchange-name": "BinanceUS",
  "binanceus-api-key": "string",
  "binanceus-api-secret": "string"
}
BinanceUSDMFuturesBrokerageAndDataProviderSettings Model
id string Enum
required

Id of the module. Options : ['BinanceBrokerage']
binance-exchange-name string Enum
required

Binance exchange name. Options : ['Binance-USDM-Futures']
binance-api-key string
required

Your Binance API key.
binance-api-secret string
required

Your Binance API secret.
Example
{
  "id": "BinanceBrokerage",
  "binance-exchange-name": "Binance-USDM-Futures",
  "binance-api-key": "string",
  "binance-api-secret": "string"
}
BinanceCOINFuturesBrokerageAndDataProviderSettings Model
id string Enum
required

Id of the module. Options : ['BinanceBrokerage']
binance-exchange-name string Enum
required

Binance exchange name. Options : ['Binance-COIN-Futures']
binance-api-key string
required

Your Binance API key.
binance-api-secret string
required

Your Binance API secret.
Example
{
  "id": "BinanceBrokerage",
  "binance-exchange-name": "Binance-COIN-Futures",
  "binance-api-key": "string",
  "binance-api-secret": "string"
}
TradingTechnologiesBrokerageSettings Model - Settings for using Trading Technologies as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['TradingTechnologiesBrokerage']
tt-user-name string
required

Your Trading Technologies username.
tt-session-password string
required

Your Trading Technologies session password.
tt-account-name string
required

Your Trading Technologies account name.
tt-rest-app-key string
required

Your Trading Technologies REST app key.
tt-rest-app-secret string
required

Your Trading Technologies REST app secret.
tt-rest-environment string Enum
required

The REST environment to run in. Options : ['live', 'uat']
tt-order-routing-sender-comp-id string
required

The order routing sender comp id to use.
cash CashAmount Array
required

List of cash amount.
Example
{
  "id": "TradingTechnologiesBrokerage",
  "tt-user-name": "string",
  "tt-session-password": "string",
  "tt-account-name": "string",
  "tt-rest-app-key": "string",
  "tt-rest-app-secret": "string",
  "tt-rest-environment": "live",
  "tt-order-routing-sender-comp-id": "string",
  "cash": [
    {
      "amount": 0,
      "currency": "string"
    }
  ]
}
KrakenSettings Model - Settings for using Kraken as the brokerage or a data provider for a live algorithm.
id string Enum
required

Id of the module. Options : ['KrakenBrokerage']
kraken-api-key string
required

Your Kraken API key.
kraken-api-secret string
required

Your Kraken API secret.
kraken-verification-tier string Enum
required

Your Kraken Verification Tier. Options : ['Starter', 'Intermediate', 'Pro']
Example
{
  "id": "KrakenBrokerage",
  "kraken-api-key": "string",
  "kraken-api-secret": "string",
  "kraken-verification-tier": "Starter"
}
BybitBrokerageAndDataProviderSettings Model
id string Enum
required

Id of the module. Options : ['BybitBrokerage']
bybit-api-key string
required

Your Bybit API key.
bybit-api-secret string
required

Your Bybit API secret.
bybit-vip-level string Enum
required

Your Bybit VIP Level. Options : ['VIP0', 'VIP1', 'VIP2', 'VIP3', 'VIP4', 'VIP5', 'SupremeVIP', 'Pro1', 'Pro2', 'Pro3', 'Pro4', 'Pro5']
Example
{
  "id": "BybitBrokerage",
  "bybit-api-key": "string",
  "bybit-api-secret": "string",
  "bybit-vip-level": "VIP0"
}
OandaSettings Model - Settings for using Oanda as the brokerage or a data provider for a live algorithm.
id string Enum
required

Id of the module. Options : ['OandaBrokerage']
oanda-account-id string
required

Your OANDA account id can be found on your OANDA Account Statement page (https://www.oanda.com/account/statement/). It follows the following format '###-###-######-###'.
oanda-access-token string
required

Your OANDA API token. You can generate an API token from the Manage API Access page (https://www.oanda.com/account/tpa/personal_token).
oanda-environment string Enum
required

The environment to run in. Practice for fxTrade Practice, Trade for fxTrade. Options : ['Practice', 'Trade']
Example
{
  "id": "OandaBrokerage",
  "oanda-account-id": "string",
  "oanda-access-token": "string",
  "oanda-environment": "Practice"
}
WolverineSettings Model - Settings for using Wolverine Execution Services as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['WolverineBrokerage']
wolverine-on-behalf-of-comp-id string
required

Value used to identify the trading firm.
wolverine-account string
required

Wolverine Execution Services account name.
cash CashAmount Array
List of cash amount.
holdings BrokerageHolding Array
List of holdings for the brokerage.
Example
{
  "id": "WolverineBrokerage",
  "wolverine-on-behalf-of-comp-id": "string",
  "wolverine-account": "string",
  "cash": [
    {
      "amount": 0,
      "currency": "string"
    }
  ],
  "holdings": [
    {
      "symbolId": "BTCUSD 2XR",
      "symbol": "BTCUSD",
      "quantity": 0,
      "averagePrice": 0
    }
  ]
}
CharlesSchwabSettings Model - Settings for using Charles Schwab as a data provider or the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['CharlesSchwabBrokerage']
charles-schwab-account-number string
required

Your Charles Schwab account number.
Example
{
  "id": "CharlesSchwabBrokerage",
  "charles-schwab-account-number": "string"
}
RBIBrokerageSettings Model - Settings for using RBI as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['RBIBrokerage']
rbi-on-behalf-of-comp-id string
required

Value used to identify the trading firm.
rbi-account string
required

RBI account name.
cash CashAmount Array
List of cash amount.
holdings BrokerageHolding Array
List of holdings for the brokerage.
Example
{
  "id": "RBIBrokerage",
  "rbi-on-behalf-of-comp-id": "string",
  "rbi-account": "string",
  "cash": [
    {
      "amount": 0,
      "currency": "string"
    }
  ],
  "holdings": [
    {
      "symbolId": "BTCUSD 2XR",
      "symbol": "BTCUSD",
      "quantity": 0,
      "averagePrice": 0
    }
  ]
}
QuantBridgeSettings Model - Settings for using QuantBridge as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['QuantBridgeBrokerage']
quant-bridge-connection-type string Enum
required

Quant Bridge Connection Type. Options : ['SAPI']
quant-bridge-server-auth-id string
required

Your unique user identifier (UUID). The UUID is a unique integer identifier that's assigned to each Bloomberg Anywhere user. If you don't know your UUID, contact Bloomberg.
quant-bridge-environment string Enum
required

The environment to run in. Options : ['Production', 'Beta']
quant-bridge-server-host string
required

The public IP address of the AWS instance that runs the EMSX API Server.
quant-bridge-server-port integer
required

The port where the EMSX API Server is listening. The default port is 8194.
quant-bridge-emsx-broker string
required

The EMSX broker to use.
quant-bridge-emsx-account string
required

The account to which LEAN should route orders.
quant-bridge-openfigi-api-key string
required

The OpenFIGI API key to use for mapping options.
quant-bridge-emsx-team string
The EMSX team to use.
cash CashAmount Array
List of cash amount.
holdings BrokerageHolding Array
List of holdings for the brokerage.
Example
{
  "id": "QuantBridgeBrokerage",
  "quant-bridge-connection-type": "SAPI",
  "quant-bridge-server-auth-id": "string",
  "quant-bridge-environment": "Production",
  "quant-bridge-server-host": "string",
  "quant-bridge-server-port": 0,
  "quant-bridge-emsx-broker": "string",
  "quant-bridge-emsx-account": "string",
  "quant-bridge-openfigi-api-key": "string",
  "quant-bridge-emsx-team": "string",
  "cash": [
    {
      "amount": 0,
      "currency": "string"
    }
  ],
  "holdings": [
    {
      "symbolId": "BTCUSD 2XR",
      "symbol": "BTCUSD",
      "quantity": 0,
      "averagePrice": 0
    }
  ]
}
TradeStationSettings Model - Settings for using TradeStation as the brokerage or a data provider for a live algorithm.
id string Enum
required

Id of the module. Options : ['TradeStationBrokerage']
trade-station-client-id string
required

Your TradeStation client Id.
trade-station-account-id string
required

The TradeStation account Id.
trade-station-refresh-token string
required

The TradeStation refresh token.
trade-station-environment string Enum
required

The environment to run the algorithm in. Options : ['live', 'paper']
Example
{
  "id": "TradeStationBrokerage",
  "trade-station-client-id": "string",
  "trade-station-account-id": "string",
  "trade-station-refresh-token": "string",
  "trade-station-environment": "live"
}
TastytradeSettings Model - Settings for using Tastytrade as the brokerage or a data provider for a live algorithm.
id string Enum
required

Id of the module. Options : ['TastytradeBrokerage']
tastytrade-account-number integer
required

Your Tastytrade account number.
tastytrade-refresh-token string
required

The TradeStation refresh token.
Example
{
  "id": "TastytradeBrokerage",
  "tastytrade-account-number": 0,
  "tastytrade-refresh-token": "string"
}
AlpacaBrokerageSettings Model - Settings for using Alpaca as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['AlpacaBrokerage']
alpaca-access-token string
required

Your Alpaca access token for authentication.
alpaca-environment string Enum
required

The environment to run the algorithm in. Options : ['live', 'paper']
Example
{
  "id": "AlpacaBrokerage",
  "alpaca-access-token": "string",
  "alpaca-environment": "live"
}
WebullBrokerageSettings Model - Settings for using Webull as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['WebullBrokerage']
webull-app-key string
required

Your Webull App Key.
webull-app-secret string
required

Your Webull App Secret.
webull-account-id string
required

Your Webull account ID.
webull-use-2fa boolean
Whether your Webull application has two-factor authentication (2FA) enabled.
Example
{
  "id": "WebullBrokerage",
  "webull-app-key": "string",
  "webull-app-secret": "string",
  "webull-account-id": "string",
  "webull-use-2fa": true
}
PublicBrokerageSettings Model - Settings for using Public as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['PublicBrokerage']
public-secret-key string
required

Your Public secret key.
public-account-number string
required

The number of the Public account you want to trade.
Example
{
  "id": "PublicBrokerage",
  "public-secret-key": "string",
  "public-account-number": "string"
}
ClearStreetBrokerageSettings Model - Settings for using Clear Street as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['ClearStreetBrokerage']
clearstreet-access-token string
required

Your Clear Street API access token.
clearstreet-account-id string
required

Your Clear Street account ID, the numeric ID of the account the algorithm trades.
Example
{
  "id": "ClearStreetBrokerage",
  "clearstreet-access-token": "string",
  "clearstreet-account-id": "string"
}
BloombergFixSettings Model - Settings for using Bloomberg FIX as the brokerage for a live algorithm.
id string Enum
required

Id of the module. Options : ['BloombergFixBrokerage']
bloomberg-fix-sender-sub-id string
required

Your QuantConnect user Id. The connection sends it as FIX tag 50 so Bloomberg can map the orders to you.
bloomberg-fix-on-behalf-of-comp-id string
required

The CompID that identifies your trading firm, sent as FIX tag 115. Bloomberg assigns it when they provision your FIX session.
bloomberg-fix-deliver-to-comp-id string
required

The CompID of the prime brokerage that receives your orders, sent as FIX tag 128.
bloomberg-fix-environment string Enum
required

The environment to run in. Options : ['Live']
cash CashAmount Array
List of cash amount.
holdings BrokerageHolding Array
List of holdings for the brokerage.
Example
{
  "id": "BloombergFixBrokerage",
  "bloomberg-fix-sender-sub-id": "string",
  "bloomberg-fix-on-behalf-of-comp-id": "string",
  "bloomberg-fix-deliver-to-comp-id": "string",
  "bloomberg-fix-environment": "Live",
  "cash": [
    {
      "amount": 0,
      "currency": "string"
    }
  ],
  "holdings": [
    {
      "symbolId": "BTCUSD 2XR",
      "symbol": "BTCUSD",
      "quantity": 0,
      "averagePrice": 0
    }
  ]
}
BrokerageHolding Model - Holding object class for creating a live algorithm.
symbolId string
example: BTCUSD 2XR

Symbol Id of the holding.
symbol string
example: BTCUSD

Symbol ticker of the holding.
quantity number
Quantity of the Symbol you hold.
averagePrice number
Average price of your Holding in the currency the symbol is traded in.
Example
{
  "symbolId": "BTCUSD 2XR",
  "symbol": "BTCUSD",
  "quantity": 0,
  "averagePrice": 0
}
CashAmount Model - Represents a cash amount which can be converted to account currency using a currency converter.
amount number
required

The amount of cash.
currency string
required

The currency in which the cash amount is denominated.
Example
{
  "amount": 0,
  "currency": "string"
}

Responses

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

200 Success

CreateLiveAlgorithmResponse Model - Response received when deploying a live algorithm.
responseCode string
Response code of the request.
source string
Source of the API call.
deployId string
example: L-141106d80de1da9a9f85ea07c06bf7b6

Id of the live deployment.
versionId integer
example: 17202

Id of the LEAN version deployed.
projectId integer
example: 24058693

Id of the project deployed.
live LiveAlgorithm object
Live algorithm instance result from the QuantConnect Rest API.
success boolean
Indicate if the API request was successful.
errors string Array
List of errors with the API call.
Example
{
  "responseCode": "string",
  "source": "string",
  "deployId": "L-141106d80de1da9a9f85ea07c06bf7b6",
  "versionId": 17202,
  "projectId": 24058693,
  "live": {
    "message": "string",
    "deployId": "L-sdf86b7045bb83203e79d2aa6150b321",
    "status": "DeployError",
    "cloneId": 0,
    "launched": "2021-11-26T15:18:27.693Z",
    "stopped": "2021-11-26T15:18:27.693Z",
    "projectName": "string",
    "brokerage": "string",
    "securityTypes": "string",
    "datacenter": "NY7",
    "isPublicStreaming": true,
    "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"
  ]
}
LiveAlgorithm Model - Live algorithm instance result from the QuantConnect Rest API.
message string
Error message.
deployId string
example: L-sdf86b7045bb83203e79d2aa6150b321

Unique live algorithm deployment identifier (similar to a backtest id).
status string Enum
State of the live deployment. Options : ['DeployError', 'InQueue', 'Running', 'Stopped', 'Liquidated', 'Deleted', 'Completed', 'RuntimeError', 'Invalid', 'LoggingIn', 'Initializing', 'History']
cloneId integer
The snapshot project Id for cloning the live development's source code.
launched string($date-time)
Datetime the first live deployment of the project started in UTC. To get the start time of this deployment, call the /live/list endpoint.
stopped string($date-time)
Datetime the algorithm was stopped in UTC, null if its still running.
projectName string
Project name.
brokerage string
Brokerage.
securityTypes string
Security types detected in the algorithm.
datacenter string
example: NY7

Name of the datacenter where the algorithm is physically located.
isPublicStreaming boolean
Flag to indicate if public streaming is enabled.
public boolean
Flag to indicate if the algorithm is public.
files ProjectFile Array
Files of the deployed algorithm. If the deployment has no files, this is an empty object instead of an array.
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
Contains the names of all charts.
Example
{
  "message": "string",
  "deployId": "L-sdf86b7045bb83203e79d2aa6150b321",
  "status": "DeployError",
  "cloneId": 0,
  "launched": "2021-11-26T15:18:27.693Z",
  "stopped": "2021-11-26T15:18:27.693Z",
  "projectName": "string",
  "brokerage": "string",
  "securityTypes": "string",
  "datacenter": "NY7",
  "isPublicStreaming": true,
  "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"
  }
}
ProjectFile Model - File for a project.
id integer
ID of the project file. This can also be null.
projectId integer
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 demonstrates listing, creating, reading, and updating 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())

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


### List Live Algorithms
# Define placeholder IDs for project, compilation and node (replace with actual values)
project_id = 12345678
compile_id = "compile_id..."
node_id = "node_id..."
# Prepare data payload to list the past and current deployments of the project
payload = {
    "projectId": project_id  # ID of the project
}
# 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()
deployments = result['live'] if result['success'] else []
# The most recent deployment of the project, if any
latest = max(deployments, key=lambda x: x['launched'], default=None)
print(f"Live deployments: {len(deployments)}, latest: {latest['deployId'] if latest else None}")

### Create Live Algorithm
# Deploy only if the project has no running deployment
if latest is None or latest['status'] != 'Running':
    # Prepare the data payload for creating a live algorithm with necessary details
    payload = {
        "versionId": -1,  # Use the latest version of LEAN
        "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"  # Paper trading brokerage identifier
        },
        "dataProviders": {  # Data provider configuration
            "QuantConnectBrokerage": {
                "id": "QuantConnectBrokerage"  # Data provider identifier
            }
        },
        "parameters": {}  # Optional algorithm parameters (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=payload)
    # Parse the JSON response into python managable dict from the API
    result = response.json()
    # 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 the project ID to fetch the statistics of its latest deployment
payload = {
    "projectId": project_id  # ID of the project
}
# 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)

### Export Orders
from decimal import Decimal
from time import sleep

# Download the orders of the last 750 days as a CSV file
payload = {
    "projectId": project_id  # ID of the project
}
response = post(f'{BASE_URL}/live/export/orders', headers=get_headers(), json=payload)
rows = response.text.splitlines()
header, recent = rows[0], rows[1:]
# The export starts at its first row. Older orders come from the /live/orders/read endpoint.
cutoff = recent[0].split(',')[1][:19].replace('T', ' ') if recent else '9999'

# Map the order type and status enums to the names in the CSV file
order_types = ["Market", "Limit", "Stop Market", "Stop Limit", "Market On Open", "Market On Close",
    "Option Exercise", "Limit If Touched", "Combo Market", "Combo Limit", "Combo Leg Limit", "Trailing Stop"]
order_statuses = ["New", "Submitted", "Partially Filled", "Filled", "", "Canceled", "None", "Invalid",
    "Cancel Pending", "Update Submitted"]

def number(value):
    text = format(Decimal(str(value)), 'f')
    return text.rstrip('0').rstrip('.') if '.' in text else text

# Read the older orders of each deployment that started before the cutoff
older = []
response = post(f'{BASE_URL}/live/list', headers=get_headers(), json={"projectId": project_id})
deployments = sorted(response.json()['live'], key=lambda x: x['launched'])
for deployment in deployments:
    if deployment['launched'] >= cutoff:
        continue
    start = 0
    while True:
        payload = {
            "projectId": project_id,  # ID of the project
            "deployId": deployment['deployId'],  # ID of the deployment
            "start": start,  # Starting index for orders
            "end": start + 1000  # Ending index for orders
        }
        result = post(f'{BASE_URL}/live/orders/read', headers=get_headers(), json=payload).json()
        # The first request can return a loading status while the orders are prepared
        if result.get('status') == 'loading':
            sleep(1)
            continue
        for order in result['orders']:
            if order['time'][:19].replace('T', ' ') >= cutoff:
                continue
            older.append(','.join([
                deployment['deployId'], order['time'], order['symbol']['value'],
                number(order['price']), number(order['quantity']),
                f'"{order_types[order["type"]]}"', f'"{order_statuses[order["status"]]}"',
                number(order['value']), '"' + order['tag'].replace('"', '""') + '" '
            ]))
        start += 1000
        if start >= result['length']:
            break

# Save all the orders in one CSV file
with open(f'orders-{project_id}.csv', 'w', newline='') as file:
    file.write('\n'.join([header] + older + recent) + '\n')
print(f"Saved {len(older) + len(recent)} orders")

### Export Trades
# Download the closed trades that opened since the start time as a CSV file
payload = {
    "projectId": project_id,  # ID of the project
    "start": 1717801200,  # Start time (Unix timestamp) for the trade entry time
    "end": 1743462000  # End time (Unix timestamp) for the trade exit time
}
response = post(f'{BASE_URL}/live/export/trades', headers=get_headers(), json=payload)
with open(f'trades-{project_id}.csv', 'w', newline='') as file:
    file.write(response.text)

### Export Insights
# Download the insights of all the live deployments of the project as a JSON file
payload = {
    "deployId": latest['deployId']  # ID of a deployment of the project
}
response = post(f'{BASE_URL}/live/export/insights', headers=get_headers(), json=payload)
with open(f'insights-{project_id}.json', 'w', newline='') as file:
    file.write(response.text)

### Export Logs
# Download the logs of all the live deployments of the project as a text file
payload = {
    "projectId": project_id,  # ID of the project
    "deployId": latest['deployId']  # ID of a deployment of the project, used to name the file
}
response = post(f'{BASE_URL}/live/export/logs', headers=get_headers(), json=payload)
with open(f'logs-{project_id}.txt', 'w', newline='') as file:
    file.write(response.text)

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: