Read Live Algorithm

Trades

Introduction

Read out the closed trades of a live algorithm. The snapshot updates about every 10 minutes.

Request

Fetch the closed trades of a live algorithm for the project Id and steps provided. The /live/trades/read API accepts requests in the following format:

ReadLiveTradesRequest Model - Request to read closed trades from a live algorithm.
projectId integer
required
example: 23456789

Id of the project from which to read the live algorithm.
deployId string
example: L-6e9d8a78f5af89d401f630585be90e43

Deploy Id of the live algorithm. When you provide it, the response contains the closed trades of that deployment. When you omit it, the response contains the closed trades of every deployment of the project. If you provide it, it must be a string. The API rejects a null value.
start integer
required
example: 0

Starting index of the closed trades to be fetched.
end integer
required
example: 100

Last index of the closed trades to be fetched. Note that end - start must be <= 1,000.
Example
{
  "projectId": 23456789,
  "deployId": "L-6e9d8a78f5af89d401f630585be90e43",
  "start": 0,
  "end": 100
}

Responses

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

200 Success

LoadingResponse Model - Response when the requested chart or orders are being generated.
progress number
Loading percentage of the data generation process.
status string Enum
Status of the data generation process. Options : ['loading']
success boolean
Indicate if the API request was successful.
Example
{
  "progress": 0,
  "status": "loading",
  "success": true
}
LiveTradesResponse Model - Contains the closed trades and the number of closed trades of the live algorithm in the request criteria.
trades ClosedTradeWithOrders Array
Collection of closed trades.
length integer
Total number of closed trades matching the request criteria.
success boolean
Indicate if the API request was successful.
errors string Array
List of errors with the API call.
Example
{
  "trades": [
    {
      "id": "e1936b18-446b-4d57-95a6-6fd1a420e261",
      "symbols": [
        {
          "value": "string",
          "id": "string",
          "permtick": "string"
        }
      ],
      "entryTime": "2021-11-26T15:18:27.693Z",
      "entryPrice": 0,
      "direction": 0,
      "quantity": 0,
      "exitTime": "2021-11-26T15:18:27.693Z",
      "exitPrice": 0,
      "profitLoss": 0,
      "totalFees": 0,
      "mae": 0,
      "mfe": 0,
      "duration": "string",
      "endTradeDrawdown": 0,
      "isWin": true,
      "orderIds": [
        "integer"
      ],
      "orders": [
        {
          "id": 0,
          "contingentId": 0,
          "brokerId": [
            "string"
          ],
          "symbol": {
            "value": "string",
            "id": "string",
            "permtick": "string"
          },
          "limitPrice": 0,
          "stopPrice": 0,
          "stopTriggered": true,
          "price": 0,
          "priceCurrency": "string",
          "time": "2021-11-26T15:18:27.693Z",
          "createdTime": "2021-11-26T15:18:27.693Z",
          "lastFillTime": "2021-11-26T15:18:27.693Z",
          "lastUpdateTime": "2021-11-26T15:18:27.693Z",
          "canceledTime": "2021-11-26T15:18:27.693Z",
          "quantity": 0,
          "type": 0,
          "status": 0,
          "tag": "string",
          "securityType": 0,
          "direction": 0,
          "value": 0,
          "orderSubmissionData": {
            "bidPrice": 0,
            "askPrice": 0,
            "lastPrice": 0
          },
          "isMarketable": true,
          "properties": {
            "timeInForce": 
          },
          "events": [
            {
              "algorithmId": "string",
              "symbol": "string",
              "symbolValue": "string",
              "symbolPermtick": "string",
              "orderId": 0,
              "orderEventId": 0,
              "id": "string",
              "status": "new",
              "orderFeeAmount": 0,
              "orderFeeCurrency": "string",
              "fillPrice": 0,
              "fillPriceCurrency": "string",
              "fillQuantity": 0,
              "direction": "buy",
              "message": "string",
              "isAssignment": true,
              "stopPrice": 0,
              "limitPrice": 0,
              "quantity": 0,
              "time": 0,
              "isInTheMoney": true
            }
          ],
          "trailingAmount": 0,
          "trailingPercentage": true,
          "groupOrderManager": {
            "id": 0,
            "quantity": 0,
            "count": 0,
            "limitPrice": 0,
            "orderIds": [
              "integer"
            ],
            "direction": 0
          },
          "triggerPrice": 0,
          "triggerTouched": true
        }
      ]
    }
  ],
  "length": 0,
  "success": true,
  "errors": [
    "string"
  ]
}
ClosedTradeWithOrders Model - Represents a closed trade of a backtest or a live algorithm, with the orders that opened and closed it.
id string
example: e1936b18-446b-4d57-95a6-6fd1a420e261

Unique identifier of the closed trade.
symbols Symbol Array
The securities involved in the trade.
entryTime string($date-time)
The date and time the trade was opened.
entryPrice number
The price at which the trade was opened (or the average price if multiple entries).
direction integer Enum
Direction of a trade. 0=Long, 1=Short. Options : [0, 1]
quantity number
The total unsigned quantity of the trade.
exitTime string($date-time)
The date and time the trade was closed.
exitPrice number
The price at which the trade was closed (or the average price if multiple exits).
profitLoss number
The gross profit/loss of the trade (as account currency).
totalFees number
The total fees associated with the trade (always positive value) (as account currency).
mae number
The Maximum Adverse Excursion (as account currency).
mfe number
The Maximum Favorable Excursion (as account currency).
duration string
The duration of the trade.
endTradeDrawdown number
The amount of profit given back before the trade was closed.
isWin boolean
Whether the trade closed at a profit.
orderIds integer Array
Ids of the orders that opened and closed the trade.
orders Order Array
The orders that opened and closed the trade.
Example
{
  "id": "e1936b18-446b-4d57-95a6-6fd1a420e261",
  "symbols": [
    {
      "value": "string",
      "id": "string",
      "permtick": "string"
    }
  ],
  "entryTime": "2021-11-26T15:18:27.693Z",
  "entryPrice": 0,
  "direction": 0,
  "quantity": 0,
  "exitTime": "2021-11-26T15:18:27.693Z",
  "exitPrice": 0,
  "profitLoss": 0,
  "totalFees": 0,
  "mae": 0,
  "mfe": 0,
  "duration": "string",
  "endTradeDrawdown": 0,
  "isWin": true,
  "orderIds": [
    "integer"
  ],
  "orders": [
    {
      "id": 0,
      "contingentId": 0,
      "brokerId": [
        "string"
      ],
      "symbol": {
        "value": "string",
        "id": "string",
        "permtick": "string"
      },
      "limitPrice": 0,
      "stopPrice": 0,
      "stopTriggered": true,
      "price": 0,
      "priceCurrency": "string",
      "time": "2021-11-26T15:18:27.693Z",
      "createdTime": "2021-11-26T15:18:27.693Z",
      "lastFillTime": "2021-11-26T15:18:27.693Z",
      "lastUpdateTime": "2021-11-26T15:18:27.693Z",
      "canceledTime": "2021-11-26T15:18:27.693Z",
      "quantity": 0,
      "type": 0,
      "status": 0,
      "tag": "string",
      "securityType": 0,
      "direction": 0,
      "value": 0,
      "orderSubmissionData": {
        "bidPrice": 0,
        "askPrice": 0,
        "lastPrice": 0
      },
      "isMarketable": true,
      "properties": {
        "timeInForce": 
      },
      "events": [
        {
          "algorithmId": "string",
          "symbol": "string",
          "symbolValue": "string",
          "symbolPermtick": "string",
          "orderId": 0,
          "orderEventId": 0,
          "id": "string",
          "status": "new",
          "orderFeeAmount": 0,
          "orderFeeCurrency": "string",
          "fillPrice": 0,
          "fillPriceCurrency": "string",
          "fillQuantity": 0,
          "direction": "buy",
          "message": "string",
          "isAssignment": true,
          "stopPrice": 0,
          "limitPrice": 0,
          "quantity": 0,
          "time": 0,
          "isInTheMoney": true
        }
      ],
      "trailingAmount": 0,
      "trailingPercentage": true,
      "groupOrderManager": {
        "id": 0,
        "quantity": 0,
        "count": 0,
        "limitPrice": 0,
        "orderIds": [
          "integer"
        ],
        "direction": 0
      },
      "triggerPrice": 0,
      "triggerTouched": true
    }
  ]
}
Symbol Model - Represents a unique security identifier. This is made of two components, the unique SID and the Value. The value is the current ticker symbol while the SID is constant over the life of a security.
value string
The current symbol for this ticker.
id string
The security identifier for this symbol.
permtick string
The ticker at IPO for this security.
Example
{
  "value": "string",
  "id": "string",
  "permtick": "string"
}
Order Model - Order struct for placing new trade.
id integer
Order ID.
contingentId integer
Order Id to process before processing this order.
brokerId string Array
Brokerage Id for this order for when the brokerage splits orders into multiple pieces.
symbol Symbol object
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.
limitPrice number
Limit price of the Order.
stopPrice number
Stop price of the Order.
stopTriggered boolean
Indicates if the stop price has been reached, so the limit order has been triggered.
price number
Price of the Order.
priceCurrency string
Currency for the order price.
time string($date-time)
Gets the UTC time the order was created.
createdTime string($date-time)
Gets the UTC time this order was created. Alias for Time.
lastFillTime string($date-time)
Gets the UTC time the last fill was received, or null if no fills have been received.
lastUpdateTime string($date-time)
Gets the UTC time this order was last updated, or null if the order has not been updated.
canceledTime string($date-time)
Gets the UTC time this order was canceled, or null if the order was not canceled.
quantity number
Number of shares to execute.
type integer Enum
Order type. 0=Market, 1=Limit, 2=StopMarket, 3=StopLimit, 4=MarketOnOpen, 5=MarketOnClose, 6=OptionExercise, 7=LimitIfTouched, 8=ComboMarket, 9=ComboLimit, 10=ComboLegLimit, 11=TrailingStop. Options : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
status integer Enum
Status of the Order. 0=New, 1=Submitted, 2=PartiallyFilled, 3=Filled, 5=Canceled, 6=None, 7=Invalid, 8=CancelPending, 9=UpdateSubmitted. Options : [0, 1, 2, 3, 5, 6, 7, 8, 9]
tag string
Tag the order with some custom data.
securityType integer Enum
Type of tradable security / underlying asset. 0=Base, 1=Equity, 2=Option, 3=Commodity, 4=Forex, 5=Future, 6=Cfd, 7=Crypto, 8=FutureOption, 9=Index, 10=IndexOption, 11=CryptoFuture. Options : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
direction integer Enum
Order Direction Property based off Quantity. 0=Buy, 1=Sell, 2=Hold. Options : [0, 1, 2]
value number
Gets the executed value of this order. If the order has not yet filled, then this will return zero.
orderSubmissionData OrderSubmissionData object
Stores time and price information available at the time an order was submitted.
isMarketable boolean
Returns true if the order is a marketable order.
properties OrderProperties object
Additional properties of the order.
events OrderEvent Array
The order events.
trailingAmount number
Trailing amount for a trailing stop order.
trailingPercentage boolean
Determines whether the trailingAmount is a percentage or an absolute currency value.
groupOrderManager GroupOrderManager object
Manager of a group of orders.
triggerPrice number
The price which, when touched, will trigger the setting of a limit order at limitPrice.
triggerTouched boolean
Whether or not the triggerPrice has been touched.
Example
{
  "id": 0,
  "contingentId": 0,
  "brokerId": [
    "string"
  ],
  "symbol": {
    "value": "string",
    "id": "string",
    "permtick": "string"
  },
  "limitPrice": 0,
  "stopPrice": 0,
  "stopTriggered": true,
  "price": 0,
  "priceCurrency": "string",
  "time": "2021-11-26T15:18:27.693Z",
  "createdTime": "2021-11-26T15:18:27.693Z",
  "lastFillTime": "2021-11-26T15:18:27.693Z",
  "lastUpdateTime": "2021-11-26T15:18:27.693Z",
  "canceledTime": "2021-11-26T15:18:27.693Z",
  "quantity": 0,
  "type": 0,
  "status": 0,
  "tag": "string",
  "securityType": 0,
  "direction": 0,
  "value": 0,
  "orderSubmissionData": {
    "bidPrice": 0,
    "askPrice": 0,
    "lastPrice": 0
  },
  "isMarketable": true,
  "properties": {
    "timeInForce": 
  },
  "events": [
    {
      "algorithmId": "string",
      "symbol": "string",
      "symbolValue": "string",
      "symbolPermtick": "string",
      "orderId": 0,
      "orderEventId": 0,
      "id": "string",
      "status": "new",
      "orderFeeAmount": 0,
      "orderFeeCurrency": "string",
      "fillPrice": 0,
      "fillPriceCurrency": "string",
      "fillQuantity": 0,
      "direction": "buy",
      "message": "string",
      "isAssignment": true,
      "stopPrice": 0,
      "limitPrice": 0,
      "quantity": 0,
      "time": 0,
      "isInTheMoney": true
    }
  ],
  "trailingAmount": 0,
  "trailingPercentage": true,
  "groupOrderManager": {
    "id": 0,
    "quantity": 0,
    "count": 0,
    "limitPrice": 0,
    "orderIds": [
      "integer"
    ],
    "direction": 0
  },
  "triggerPrice": 0,
  "triggerTouched": true
}
OrderSubmissionData Model - Stores time and price information available at the time an order was submitted.
bidPrice number
The bid price at order submission time.
askPrice number
The ask price at order submission time.
lastPrice number
The current price at order submission time.
Example
{
  "bidPrice": 0,
  "askPrice": 0,
  "lastPrice": 0
}
OrderProperties Model - Additional properties of the order
timeInForce object
Defines the length of time over which an order will continue working before it is cancelled.
Example
{
  "timeInForce": 
}
OrderEvent Model - Change in an order state applied to user algorithm portfolio
algorithmId string
Algorithm Id, BacktestId or DeployId.
symbol string
Easy access to the order symbol associated with this event.
symbolValue string
The current symbol for this ticker; It is a user friendly symbol representation.
symbolPermtick string
The original symbol used to generate this symbol.
orderId integer
Id of the order this event comes from.
orderEventId integer
The unique order event id for each order.
id string
The unique order event Id for each order.
status string Enum
Status of the Order. Options : ['new', 'submitted', 'partiallyFilled', 'filled', 'canceled', 'none', 'invalid', 'cancelPending', 'updateSubmitted']
orderFeeAmount number
The fee amount associated with the order.
orderFeeCurrency string
The fee currency associated with the order.
fillPrice number
Fill price information about the order.
fillPriceCurrency string
Currency for the fill price.
fillQuantity number
Number of shares of the order that was filled in this event.
direction string Enum
Direction of the order. Options : ['buy', 'sell', 'hold']
message string
Any message from the exchange.
isAssignment boolean
True if the order event is an assignment.
stopPrice number
The current stop price.
limitPrice number
The current limit price.
quantity number
The current order quantity.
time number
The time of this event in unix timestamp.
isInTheMoney boolean
True if the order event's option is In-The-Money (ITM).
Example
{
  "algorithmId": "string",
  "symbol": "string",
  "symbolValue": "string",
  "symbolPermtick": "string",
  "orderId": 0,
  "orderEventId": 0,
  "id": "string",
  "status": "new",
  "orderFeeAmount": 0,
  "orderFeeCurrency": "string",
  "fillPrice": 0,
  "fillPriceCurrency": "string",
  "fillQuantity": 0,
  "direction": "buy",
  "message": "string",
  "isAssignment": true,
  "stopPrice": 0,
  "limitPrice": 0,
  "quantity": 0,
  "time": 0,
  "isInTheMoney": true
}
OrderDirection Model - Direction of the order.
GroupOrderManager string Enum
Direction of the order. Options : ['buy', 'sell', 'hold']
Example
{
  "GroupOrderManager": "buy"
}
GroupOrderManager Model - Manager of a group of orders.
id integer
The unique order group Id.
quantity number
The group order quantity.
count integer
The total order count associated with this order group.
limitPrice number
The limit price associated with this order group if any.
orderIds integer Array
The order Ids in this group.
direction integer
Order Direction Property based off Quantity.
Example
{
  "id": 0,
  "quantity": 0,
  "count": 0,
  "limitPrice": 0,
  "orderIds": [
    "integer"
  ],
  "direction": 0
}

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: