Skip to content

IAlgorithm

QuantConnect.Interfaces.IAlgorithm

Bases: ISecurityInitializerProvider, IAccountCurrencyProvider

Interface for QuantConnect algorithm implementations. All algorithms must implement these basic members to allow interaction with the Lean Backtesting Engine.

insights_generated

insights_generated: _EventContainer[
    Callable[
        [IAlgorithm, GeneratedInsightsCollection], Any
    ],
    Any,
]

Event fired when an algorithm generates a insight

time_keeper

time_keeper: ITimeKeeper

Gets the time keeper instance

subscription_manager

subscription_manager: SubscriptionManager

Data subscription manager controls the information and subscriptions the algorithms recieves. Subscription configurations can be added through the Subscription Manager.

project_id

project_id: int

The project id associated with this algorithm if any

securities

securities: SecurityManager

Security object collection class stores an array of objects representing representing each security/asset we have a subscription for.

universe_manager

universe_manager: UniverseManager

Gets the collection of universes for the algorithm

portfolio

Security portfolio management class provides wrapper and helper methods for the Security.Holdings class such as IsLong, IsShort, TotalProfit

transactions

Security transaction manager class controls the store and processing of orders.

brokerage_model

brokerage_model: IBrokerageModel

Gets the brokerage model used to emulate a real brokerage

brokerage_name

brokerage_name: BrokerageName

Gets the brokerage name.

risk_free_interest_rate_model

risk_free_interest_rate_model: IRiskFreeInterestRateModel

Gets the risk free interest rate model used to get the interest rates

brokerage_message_handler

brokerage_message_handler: IBrokerageMessageHandler

Gets the brokerage message handler used to decide what to do with each message sent from the brokerage

notify

Notification manager for storing and processing live event messages

schedule

schedule: ScheduleManager

Gets schedule manager for adding/removing scheduled events

history_provider

history_provider: IHistoryProvider

Gets or sets the history provider for the algorithm

status

Gets or sets the current status of the algorithm

is_warming_up

is_warming_up: bool

Gets whether or not this algorithm is still warming up

name

name: str

Public name for the algorithm.

tags

tags: HashSet[str]

A list of tags associated with the algorithm or the backtest, useful for categorization

name_updated

name_updated: _EventContainer[
    Callable[[IAlgorithm, str], Any], Any
]

Event fired algorithm's name is changed

tags_updated

tags_updated: _EventContainer[
    Callable[[IAlgorithm, HashSet[str]], Any], Any
]

Event fired when the tag collection is updated

time

time: datetime

Current date/time in the algorithm's local time zone

time_zone

time_zone: Any

Gets the time zone of the algorithm

utc_time

utc_time: datetime

Current date/time in UTC.

start_date

start_date: datetime

Algorithm start date for backtesting, set by the SetStartDate methods.

end_date

end_date: datetime

Get Requested Backtest End Date

algorithm_id

algorithm_id: str

AlgorithmId for the backtest

live_mode

live_mode: bool

Algorithm is running on a live server.

algorithm_mode

algorithm_mode: AlgorithmMode

Algorithm running mode.

deployment_target

deployment_target: DeploymentTarget

Deployment target, either local or cloud.

universe_settings

universe_settings: UniverseSettings

Gets the subscription settings to be used when adding securities via universe selection

debug_messages

debug_messages: ConcurrentQueue[str]

Debug messages from the strategy:

error_messages

error_messages: ConcurrentQueue[str]

Error messages from the strategy:

log_messages

log_messages: ConcurrentQueue[str]

Log messages from the strategy:

run_time_error

run_time_error: Exception

Gets the run time error from the algorithm, or null if none was encountered.

runtime_statistics

runtime_statistics: ConcurrentDictionary[str, str]

Customizable dynamic statistics displayed during live trading:

statistics

statistics: StatisticsResults

The current algorithm statistics for the running algorithm.

benchmark

benchmark: IBenchmark

Gets the function used to define the benchmark. This function will return the value of the benchmark at a requested date/time

trade_builder

trade_builder: ITradeBuilder

Gets the Trade Builder to generate trades from executions

settings

Gets the user settings for the algorithm

option_chain_provider

option_chain_provider: IOptionChainProvider

Gets the option chain provider, used to get the list of option contracts for an underlying symbol

future_chain_provider

future_chain_provider: IFutureChainProvider

Gets the future chain provider, used to get the list of future contracts for an underlying symbol

insights

insights: InsightManager

Gets the insight manager

object_store

object_store: ObjectStore

Gets the object store, used for persistence

current_slice

current_slice: Slice

Returns the current Slice object

account_currency

account_currency: str

Gets the account currency

security_initializer

security_initializer: ISecurityInitializer

Gets an instance that is to be used to initialize newly created securities.

add_security

add_security(
    security_type: SecurityType,
    symbol: str,
    resolution: Optional[Resolution],
    market: str,
    fill_forward: bool,
    leverage: float,
    extended_market_hours: bool,
    data_mapping_mode: Optional[DataMappingMode] = None,
    data_normalization_mode: Optional[
        DataNormalizationMode
    ] = None,
) -> Security
add_security(
    symbol: Union[Symbol, str, BaseContract],
    resolution: Optional[Resolution] = None,
    fill_forward: bool = True,
    leverage: float = ...,
    extended_market_hours: bool = False,
    data_mapping_mode: Optional[DataMappingMode] = None,
    data_normalization_mode: Optional[
        DataNormalizationMode
    ] = None,
    contract_depth_offset: int = 0,
) -> Security

Set a required SecurityType-symbol and resolution for algorithm

Parameters:

Name Type Description Default
security_type Optional[SecurityType]

SecurityType Enum: Equity, Commodity, FOREX or Future

None
symbol str | Union[Symbol, str, BaseContract]

Symbol Representation of the MarketType, e.g. AAPL

required
resolution Optional[Resolution]

Resolution of the MarketType required: MarketData, Second or Minute

None
market Optional[str]

The market the requested security belongs to, such as 'usa' or 'fxcm'

None
fill_forward bool

If true, returns the last available data even if none in that timeslice.

True
leverage float

leverage for this security

...
extended_market_hours bool

ExtendedMarketHours send in data from 4am - 8pm, not used for FOREX

False
data_mapping_mode Optional[DataMappingMode]

The contract mapping mode to use for the security

None
data_normalization_mode Optional[DataNormalizationMode]

The price scaling mode to use for the security

None
contract_depth_offset Optional[int]

The continuous contract desired offset from the current front month.

0

Returns:

Type Description
Security

The new Security that was added to the algorithm.

get_last_known_prices

get_last_known_prices(
    symbol: Union[Symbol, str, BaseContract],
) -> Iterable[BaseData]
get_last_known_prices(
    symbols: List[Symbol],
) -> DataDictionary[Iterable[BaseData]]

Signature descriptions:

  • Yields data to warmup a security for all it's subscribed data types

  • Yields data to warm up multiple securities for all their subscribed data types

Parameters:

Name Type Description Default
symbol Optional[Union[Symbol, str, BaseContract]]

The symbol for which to retrieve historical data

None
symbols Optional[List[Symbol]]

The symbols we want to get seed data for

None

Returns:

Type Description
Iterable[BaseData] | DataDictionary[Iterable[BaseData]]

Securities historical data.

get_parameter

get_parameter(name: str, default_value: str = None) -> str
get_parameter(name: str, default_value: int) -> int
get_parameter(name: str, default_value: float) -> float

Signature descriptions:

  • Gets the parameter with the specified name. If a parameter with the specified name does not exist, the given default value is returned if any, else null

  • Gets the parameter with the specified name parsed as an integer. If a parameter with the specified name does not exist, or the conversion is not possible, the given default value is returned

  • Gets the parameter with the specified name parsed as a double. If a parameter with the specified name does not exist, or the conversion is not possible, the given default value is returned

Parameters:

Name Type Description Default
name str

The name of the parameter to get

required
default_value str | int | float

The default value to return

None

Returns:

Type Description
str | int | float

The value of the specified parameter, or default_value if not found or null if there's no default value.

set_cash

set_cash(starting_cash: float) -> None
set_cash(
    symbol: str,
    starting_cash: float,
    conversion_rate: float = 0,
) -> None

Signature descriptions:

  • Set the starting capital for the strategy

  • Set the cash for the specified symbol

Parameters:

Name Type Description Default
starting_cash float

decimal starting capital, default $100,000

required
symbol Optional[str]

The cash symbol to set

None
conversion_rate Optional[float]

The current conversion rate for the

0

add_chart

add_chart(chart: Chart) -> None

Add a Chart object to algorithm collection

Parameters:

Name Type Description Default
chart Chart

Chart object to add to collection.

required

add_future_contract

add_future_contract(
    symbol: Union[Symbol, str, BaseContract],
    resolution: Optional[Resolution] = None,
    fill_forward: bool = True,
    leverage: float = 0,
    extended_market_hours: bool = False,
) -> Future

Creates and adds a new single Future contract to the algorithm

Parameters:

Name Type Description Default
symbol Union[Symbol, str, BaseContract]

The futures contract symbol

required
resolution Optional[Resolution]

The Resolution of market data, Tick, Second, Minute, Hour, or Daily. Default is Resolution.MINUTE

None
fill_forward bool

If true, returns the last available data even if none in that timeslice. Default is true

True
leverage float

The requested leverage for this equity. Default is set by SecurityInitializer

0
extended_market_hours bool

Show the after market data as well

False

Returns:

Type Description
Future

The new Future security.

add_option_contract

add_option_contract(
    symbol: Union[Symbol, str, BaseContract],
    resolution: Optional[Resolution] = None,
    fill_forward: bool = True,
    leverage: float = 0,
    extended_market_hours: bool = False,
) -> Option

Creates and adds a new single Option contract to the algorithm

Parameters:

Name Type Description Default
symbol Union[Symbol, str, BaseContract]

The option contract symbol

required
resolution Optional[Resolution]

The Resolution of market data, Tick, Second, Minute, Hour, or Daily. Default is Resolution.MINUTE

None
fill_forward bool

If true, returns the last available data even if none in that timeslice. Default is true

True
leverage float

The requested leverage for this equity. Default is set by SecurityInitializer

0
extended_market_hours bool

Show the after market data as well

False

Returns:

Type Description
Option

The new Option security.

add_tag

add_tag(tag: str) -> None

Adds a tag to the algorithm

Parameters:

Name Type Description Default
tag str

The tag to add

required

debug

debug(message: str) -> None

Send debug message

Parameters:

Name Type Description Default
message str
required

error

error(message: str) -> None

Send an error message for the algorithm

Parameters:

Name Type Description Default
message str

String message

required

get_chart_updates

get_chart_updates(
    clear_chart_data: bool = False,
) -> Iterable[Chart]

Get the chart updates since the last request:

Parameters:

Name Type Description Default
clear_chart_data bool
False

Returns:

Type Description
Iterable[Chart]

List of Chart Updates.

get_last_known_price

get_last_known_price(
    symbol: Union[Symbol, str, BaseContract],
) -> BaseData

Get the last known price using the history provider. Useful for seeding securities with the correct price

Parameters:

Name Type Description Default
symbol Union[Symbol, str, BaseContract]

The symbol for which to retrieve historical data

required

Returns:

Type Description
BaseData

A single BaseData object with the last known price.

get_locked

get_locked() -> bool

Gets whether or not this algorithm has been locked and fully initialized

get_parameters

get_parameters() -> IReadOnlyDictionary[str, str]

Gets a read-only dictionary with all current parameters

initialize

initialize() -> None

Initialise the Algorithm and Prepare Required Data:

liquidate

liquidate(
    symbol: Union[Symbol, str, BaseContract] = None,
    asynchronous: bool = False,
    tag: str = "Liquidated",
    order_properties: IOrderProperties = None,
) -> List[OrderTicket]

Liquidate your portfolio holdings

Parameters:

Name Type Description Default
symbol Union[Symbol, str, BaseContract]

Specific asset to liquidate, defaults to all.

None
asynchronous bool

Flag to indicate if the symbols should be liquidated asynchronously

False
tag str

Custom tag to know who is calling this

'Liquidated'
order_properties IOrderProperties

Order properties to use

None

log

log(message: str) -> None

Save entry to the Log

Parameters:

Name Type Description Default
message str

String message

required

on_assignment_order_event

on_assignment_order_event(
    assignment_event: OrderEvent,
) -> None

Option assignment event handler. On an option assignment event for short legs the resulting information is passed to this method.

Parameters:

Name Type Description Default
assignment_event OrderEvent

Option exercise event details containing details of the assignment

required

on_brokerage_disconnect

on_brokerage_disconnect() -> None

Brokerage disconnected event handler. This method is called when the brokerage connection is lost.

on_brokerage_message

on_brokerage_message(
    message_event: BrokerageMessageEvent,
) -> None

Brokerage message event handler. This method is called for all types of brokerage messages.

on_brokerage_reconnect

on_brokerage_reconnect() -> None

Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.

on_command

on_command(data: Any) -> Optional[bool]

Generic untyped command call handler

Parameters:

Name Type Description Default
data Any

The associated data

required

Returns:

Type Description
Optional[bool]

True if success, false otherwise. Returning null will disable command feedback.

on_data

on_data(slice: Slice) -> None

v3.0 Handler for all data types

Parameters:

Name Type Description Default
slice Slice

The current slice of data

required

on_delistings

on_delistings(delistings: Delistings) -> None

Event handler to be called when there's been a delistings event

Parameters:

Name Type Description Default
delistings Delistings

The current time slice delistings

required

on_dividends

on_dividends(dividends: Dividends) -> None

Event handler to be called when there's been a dividend event

Parameters:

Name Type Description Default
dividends Dividends

The current time slice dividends

required

on_end_of_algorithm

on_end_of_algorithm() -> None

Call this event at the end of the algorithm running.

on_end_of_day

on_end_of_day(symbol: Symbol) -> None

Call this method at the end of each day of data.

on_end_of_time_step

on_end_of_time_step() -> None

Invoked at the end of every time step. This allows the algorithm to process events before advancing to the next time step.

on_framework_data

on_framework_data(slice: Slice) -> None

Used to send data updates to algorithm framework models

Parameters:

Name Type Description Default
slice Slice

The current data slice

required

on_framework_securities_changed

on_framework_securities_changed(
    changes: SecurityChanges,
) -> None

Used to send security changes to algorithm framework models

Parameters:

Name Type Description Default
changes SecurityChanges

Security additions/removals for this time step

required

on_margin_call

on_margin_call(requests: List[SubmitOrderRequest]) -> None

Margin call event handler. This method is called right before the margin call orders are placed in the market.

Parameters:

Name Type Description Default
requests List[SubmitOrderRequest]

The orders to be executed to bring this algorithm within margin limits

required

on_margin_call_warning

on_margin_call_warning() -> None

Margin call warning event handler. This method is called when Portfolio.MarginRemaining is under 5% of your Portfolio.TotalPortfolioValue

on_order_event

on_order_event(new_event: OrderEvent) -> None

EXPERTS ONLY:: <-!-Async Code-!-> New order event handler: on order status changes (filled, partially filled, cancelled etc).

Parameters:

Name Type Description Default
new_event OrderEvent

Event information

required

on_securities_changed

on_securities_changed(changes: SecurityChanges) -> None

Event fired each time that we add/remove securities from the data feed

Parameters:

Name Type Description Default
changes SecurityChanges

Security additions/removals for this time step

required

on_splits

on_splits(splits: Splits) -> None

Event handler to be called when there's been a split event

Parameters:

Name Type Description Default
splits Splits

The current time slice splits

required

on_symbol_changed_events

on_symbol_changed_events(
    symbols_changed: SymbolChangedEvents,
) -> None

Event handler to be called when there's been a symbol changed event

Parameters:

Name Type Description Default
symbols_changed SymbolChangedEvents

The current time slice symbol changed events

required

on_warmup_finished

on_warmup_finished() -> None

Called when the algorithm has completed initialization and warm up.

post_initialize

post_initialize() -> None

Called by setup handlers after Initialize and allows the algorithm a chance to organize the data gather in the Initialize method

remove_security

remove_security(
    symbol: Union[Symbol, str, BaseContract],
    tag: str = None,
) -> bool

Removes the security with the specified symbol. This will cancel all open orders and then liquidate any existing holdings

Parameters:

Name Type Description Default
symbol Union[Symbol, str, BaseContract]

The symbol of the security to be removed

required
tag str

Optional tag to indicate the cause of removal

None

run_command

run_command(
    command: CallbackCommand,
) -> CommandResultPacket

Run a callback command instance

Parameters:

Name Type Description Default
command CallbackCommand

The callback command instance

required

Returns:

Type Description
CommandResultPacket

The command result.

set_account_currency

set_account_currency(
    account_currency: str,
    starting_cash: Optional[float] = None,
) -> None

Sets the account currency cash symbol this algorithm is to manage, as well as the starting cash in this currency if given

Parameters:

Name Type Description Default
account_currency str

The account currency cash symbol to set

required
starting_cash Optional[float]

The account currency starting cash to set

None

set_algorithm_id

set_algorithm_id(algorithm_id: str) -> None

Set the algorithm Id for this backtest or live run. This can be used to identify the order and equity records.

Parameters:

Name Type Description Default
algorithm_id str

unique 32 character identifier for backtest or live server

required

set_algorithm_mode

set_algorithm_mode(algorithm_mode: AlgorithmMode) -> None

Sets the algorithm running mode

Parameters:

Name Type Description Default
algorithm_mode AlgorithmMode

Algorithm mode

required

set_api

set_api(api: IApi) -> None

Provide the API for the algorithm.

Parameters:

Name Type Description Default
api IApi

Initiated API

required

set_available_data_types

set_available_data_types(
    available_data_types: Dictionary[
        SecurityType, List[TickType]
    ],
) -> None

Set the available TickType supported by each SecurityType in SecurityManager

Parameters:

Name Type Description Default
available_data_types Dictionary[SecurityType, List[TickType]]

The different TickType each Security supports

required

set_brokerage_message_handler

set_brokerage_message_handler(
    handler: IBrokerageMessageHandler,
) -> None

Sets the implementation used to handle messages from the brokerage. The default implementation will forward messages to debug or error and when a BrokerageMessageType.ERROR occurs, the algorithm is stopped.

Parameters:

Name Type Description Default
handler IBrokerageMessageHandler

The message handler to use

required

set_brokerage_model

set_brokerage_model(
    brokerage_model: IBrokerageModel,
) -> None

Sets the brokerage model used to resolve transaction models, settlement models, and brokerage specified ordering behaviors.

Parameters:

Name Type Description Default
brokerage_model IBrokerageModel

The brokerage model used to emulate the real brokerage

required

set_current_slice

set_current_slice(slice: Slice) -> None

Sets the current slice

Parameters:

Name Type Description Default
slice Slice

The Slice object

required

set_date_time

set_date_time(time: Union[datetime, date]) -> None

Set the DateTime Frontier: This is the master time and is

Parameters:

Name Type Description Default
time Union[datetime, date]
required

set_deployment_target

set_deployment_target(
    deployment_target: DeploymentTarget,
) -> None

Sets the algorithm deployment target

Parameters:

Name Type Description Default
deployment_target DeploymentTarget

Deployment target

required

set_end_date

set_end_date(end: Union[datetime, date]) -> None

Set the end date for a backtest.

Parameters:

Name Type Description Default
end Union[datetime, date]

Datetime value for end date

required

set_finished_warming_up

set_finished_warming_up() -> None

Sets is_warming_up to false to indicate this algorithm has finished its warm up

set_future_chain_provider

set_future_chain_provider(
    future_chain_provider: IFutureChainProvider,
) -> None

Sets the future chain provider, used to get the list of future contracts for an underlying symbol

Parameters:

Name Type Description Default
future_chain_provider IFutureChainProvider

The future chain provider

required

set_history_provider

set_history_provider(
    history_provider: IHistoryProvider,
) -> None

Set the historical data provider

Parameters:

Name Type Description Default
history_provider IHistoryProvider

Historical data provider

required

set_live_mode

set_live_mode(live: bool) -> None

Set live mode state of the algorithm run: Public setter for the algorithm property LiveMode.

Parameters:

Name Type Description Default
live bool

Bool live mode flag

required

set_locked

set_locked() -> None

Set the algorithm as initialized and locked. No more cash or security changes.

set_maximum_orders

set_maximum_orders(max: int) -> None

Set the maximum number of orders the algorithm is allowed to process.

Parameters:

Name Type Description Default
max int

Maximum order count int

required

set_name

set_name(name: str) -> None

Sets name to the currently running backtest

Parameters:

Name Type Description Default
name str

The name for the backtest

required

set_object_store

set_object_store(object_store: IObjectStore) -> None

Sets the object store

Parameters:

Name Type Description Default
object_store IObjectStore

The object store

required

set_option_chain_provider

set_option_chain_provider(
    option_chain_provider: IOptionChainProvider,
) -> None

Sets the option chain provider, used to get the list of option contracts for an underlying symbol

Parameters:

Name Type Description Default
option_chain_provider IOptionChainProvider

The option chain provider

required

set_parameters

set_parameters(parameters: Dictionary[str, str]) -> None

Sets the parameters from the dictionary

Parameters:

Name Type Description Default
parameters Dictionary[str, str]

Dictionary containing the parameter names to values

required

set_run_time_error

set_run_time_error(exception: Exception) -> None

Set the runtime error

Parameters:

Name Type Description Default
exception Exception

Represents error that occur during execution

required

set_start_date

set_start_date(start: Union[datetime, date]) -> None

Set the start date for the backtest

Parameters:

Name Type Description Default
start Union[datetime, date]

Datetime Start date for backtest

required

set_statistics_service

set_statistics_service(
    statistics_service: IStatisticsService,
) -> None

Sets the statistics service instance to be used by the algorithm

Parameters:

Name Type Description Default
statistics_service IStatisticsService

The statistics service instance

required

set_status

set_status(status: AlgorithmStatus) -> None

Set the state of a live deployment

Parameters:

Name Type Description Default
status AlgorithmStatus

Live deployment status

required

set_tags

set_tags(tags: HashSet[str]) -> None

Sets the tags for the algorithm

Parameters:

Name Type Description Default
tags HashSet[str]

The tags

required

shortable

shortable(
    symbol: Union[Symbol, str, BaseContract],
    short_quantity: float,
    update_order_id: Optional[int] = None,
) -> bool

Determines if the Symbol is shortable at the brokerage

Parameters:

Name Type Description Default
symbol Union[Symbol, str, BaseContract]

Symbol to check if shortable

required
short_quantity float

Order's quantity to check if it is currently shortable, taking into account current holdings and open orders

required
update_order_id Optional[int]

Optionally the id of the order being updated. When updating an order we want to ignore it's submitted short quantity and use the new provided quantity to determine if we can perform the update

None

Returns:

Type Description
bool

True if the symbol can be shorted by the requested quantity.

shortable_quantity

shortable_quantity(
    symbol: Union[Symbol, str, BaseContract],
) -> int

Gets the quantity shortable for the given asset

Returns:

Type Description
int

Quantity shortable for the given asset. Zero if not shortable, or a number greater than zero if shortable.

submit_order_request

submit_order_request(
    request: SubmitOrderRequest,
) -> OrderTicket

Will submit an order request to the algorithm

Parameters:

Name Type Description Default
request SubmitOrderRequest

The request to submit

required

Returns:

Type Description
OrderTicket

The order ticket.

symbol

symbol(ticker: str) -> Symbol

Converts the string 'ticker' symbol into a full symbol object This requires that the string 'ticker' has been added to the algorithm

Parameters:

Name Type Description Default
ticker str

The ticker symbol. This should be the ticker symbol as it was added to the algorithm

required

Returns:

Type Description
Symbol

The symbol object mapped to the specified ticker.

ticker

ticker(symbol: Union[Symbol, str, BaseContract]) -> str

For the given symbol will resolve the ticker it used at the current algorithm date

Parameters:

Name Type Description Default
symbol Union[Symbol, str, BaseContract]

The symbol to get the ticker for

required

Returns:

Type Description
str

The mapped ticker for a symbol.