Strategies#

All user defined strategies should inherit from the Strategy class.

from strategies import Strategy

class MyStrategy(Strategy):
   pass

The abstract class Strategy has global parameters with default values, and some properties that can be used as helpers to build trading logic.

The methods of this class can be split into several categories:

Lifecycle Methods These are executed at different times during the execution of the bot. These represent the main flow of a strategy, some are mandatory.

Strategy Methods These are strategy helper methods.

Broker Methods How to interact with the broker (buy, sell, get positions, etc)

Data Methods How to get price data easily

All the methods in each of these categories are described below.

Documentation#

class lumibot.strategies.strategy.Strategy(*args, broker=None, minutes_before_closing=1, minutes_before_opening=60, sleeptime='1M', stats_file=None, risk_free_rate=None, benchmark_asset='SPY', backtesting_start=None, backtesting_end=None, quote_asset=USD, starting_positions=None, filled_order_callback=None, name=None, budget=None, parameters={}, buy_trading_fees=[], sell_trading_fees=[], force_start_immediately=False, discord_webhook_url=None, account_history_db_connection_str=None, strategy_id=None, discord_account_summary_footer=None, **kwargs)#

Bases: _Strategy

add_line(name, value, color=None, style='solid', width=None, detail_text=None, dt=None)#

Adds a line data point to the indicator chart. This can be used to add lines such as bollinger bands, prices for specific assets, or any other line you want to add to the chart.

Parameters:
  • name (str) – The name of the line. This is used to display the name on the graph. Eg. “Overbought”, “Oversold”, “Stop Loss”, “Take Profit”, …

  • value (float or int) – The value of the line.

  • color (str) – The color of the line. Possible values are “red”, “green”, “blue”, “yellow”, “orange”, “purple”, “pink”, “brown”, “black”, “white”, “gray”, “lightgray”, “darkgray”, “lightblue”, “darkblue”, “lightgreen”, “darkgreen”, “lightred”, “darkred” and any hex color code.

  • style (str) – The style of the line. Possible values are “solid”, “dotted”, and “dashed”.

  • width (int) – The width of the line.

  • detail_text (str) – The text to display when the line is hovered over.

  • dt (datetime.datetime or pandas.Timestamp) – The datetime of the line. Default is the current datetime.

Example

>>> # Will add a line to the chart
>>> self.add_chart_line("Overbought", value=80, color="red", style="dotted", width=2)
add_marker(name, value=None, color=None, symbol='circle', size=None, detail_text=None, dt=None)#

Adds a marker to the indicators plot that loads after a backtest. This can be used to mark important events on the graph, such as price crossing a certain value, marking a support level, marking a resistance level, etc.

Parameters:
  • name (str) – The name of the marker. This is used to display the name on the graph. Eg. “Overbought”, “Oversold”, “Stop Loss”, “Take Profit”, …

  • symbol (str) – The symbol of the marker. Possible values are ‘circle’, ‘circle-open’, ‘circle-dot’, ‘circle-open-dot’, ‘square’, ‘square-open’, ‘square-dot’, ‘square-open-dot’, ‘diamond’, ‘diamond-open’, ‘diamond-dot’, ‘diamond-open-dot’, ‘cross’, ‘cross-open’, ‘cross-dot’, ‘cross-open-dot’, ‘x’, ‘x-open’, ‘x-dot’, ‘x-open-dot’, ‘triangle-up’, ‘triangle-up-open’, ‘triangle-up-dot’, ‘triangle-up-open-dot’, ‘triangle-down’, ‘triangle-down-open’, ‘triangle-down-dot’, ‘triangle-down-open-dot’, ‘triangle-left’, ‘triangle-left-open’, ‘triangle-left-dot’, ‘triangle-left-open-dot’, ‘triangle-right’, ‘triangle-right-open’, ‘triangle-right-dot’, ‘triangle-right-open-dot’, ‘triangle-ne’, ‘triangle-ne-open’, ‘triangle-ne-dot’, ‘triangle-ne-open-dot’, ‘triangle-se’, ‘triangle-se-open’, ‘triangle-se-dot’, ‘triangle-se-open-dot’, ‘triangle-sw’, ‘triangle-sw-open’, ‘triangle-sw-dot’, ‘triangle-sw-open-dot’, ‘triangle-nw’, ‘triangle-nw-open’, ‘triangle-nw-dot’, ‘triangle-nw-open-dot’, ‘pentagon’, ‘pentagon-open’, ‘pentagon-dot’, ‘pentagon-open-dot’, ‘hexagon’, ‘hexagon-open’, ‘hexagon-dot’, ‘hexagon-open-dot’, ‘hexagon2’, ‘hexagon2-open’, ‘hexagon2-dot’, ‘hexagon2-open-dot’, ‘octagon’, ‘octagon-open’, ‘octagon-dot’, ‘octagon-open-dot’, ‘star’, ‘star-open’, ‘star-dot’, ‘star-open-dot’, ‘hexagram’, ‘hexagram-open’, ‘hexagram-dot’, ‘hexagram-open-dot’, ‘star-triangle-up’, ‘star-triangle-up-open’, ‘star-triangle-up-dot’, ‘star-triangle-up-open-dot’, ‘star-triangle-down’, ‘star-triangle-down-open’, ‘star-triangle-down-dot’, ‘star-triangle-down-open-dot’, ‘star-square’, ‘star-square-open’, ‘star-square-dot’, ‘star-square-open-dot’, ‘star-diamond’, ‘star-diamond-open’, ‘star-diamond-dot’, ‘star-diamond-open-dot’, ‘diamond-tall’, ‘diamond-tall-open’, ‘diamond-tall-dot’, ‘diamond-tall-open-dot’, ‘diamond-wide’, ‘diamond-wide-open’, ‘diamond-wide-dot’, ‘diamond-wide-open-dot’, ‘hourglass’, ‘hourglass-open’, ‘bowtie’, ‘bowtie-open’, ‘circle-cross’, ‘circle-cross-open’, ‘circle-x’, ‘circle-x-open’, ‘square-cross’, ‘square-cross-open’, ‘square-x’, ‘square-x-open’, ‘diamond-cross’, ‘diamond-cross-open’, ‘diamond-x’, ‘diamond-x-open’, ‘cross-thin’, ‘cross-thin-open’, ‘x-thin’, ‘x-thin-open’, ‘asterisk’, ‘asterisk-open’, ‘hash’, ‘hash-open’, ‘hash-dot’, ‘hash-open-dot’, ‘y-up’, ‘y-up-open’, ‘y-down’, ‘y-down-open’, ‘y-left’, ‘y-left-open’, ‘y-right’, ‘y-right-open’, ‘line-ew’, ‘line-ew-open’, ‘line-ns’, ‘line-ns-open’, ‘line-ne’, ‘line-ne-open’, ‘line-nw’, ‘line-nw-open’, ‘arrow-up’, ‘arrow-up-open’, ‘arrow-down’, ‘arrow-down-open’, ‘arrow-left’, ‘arrow-left-open’, ‘arrow-right’, ‘arrow-right-open’, ‘arrow-bar-up’, ‘arrow-bar-up-open’, ‘arrow-bar-down’, ‘arrow-bar-down-open’, ‘arrow-bar-left’, ‘arrow-bar-left-open’, ‘arrow-bar-right’, ‘arrow-bar-right-open’, ‘arrow’, ‘arrow-open’, ‘arrow-wide’, ‘arrow-wide-open’

  • value (float or int) – The value of the marker. Default is the current portfolio value.

  • color (str) – The color of the marker. Possible values are “red”, “green”, “blue”, “yellow”, “orange”, “purple”, “pink”, “brown”, “black”, and “white”.

  • size (int) – The size of the marker.

  • detail_text (str) – The text to display when the marker is hovered over.

  • dt (datetime.datetime or pandas.Timestamp) – The datetime of the marker. Default is the current datetime.

Example

>>> # Will add a marker to the chart
>>> self.add_chart_marker("Overbought", symbol="circle", color="red", size=10)
after_market_closes()#

Use this lifecycle method to execute code after market closes. For example dumping stats/reports. This method is called after the last on_trading_iteration.

Parameters:

None

Return type:

None

Example

>>> # Dump stats
>>> def after_market_closes(self):
>>>     self.log_message("The market is closed")
>>>     self.log_message(f"The total value of our portfolio is {self.portfolio_value}")
>>>     self.log_message(f"The amount of cash we have is {self.cash})
property analysis#
await_market_to_close(timedelta=None)#

Sleep until market closes.

If the market is open, pauses code execution until market is closed. If an input (float) is passed as parameter, pauses code execution starting input minutes before market closes.

Parameters:

timedelta (int) – Time in minutes before market closes to pause. Overrides the self.minutes_before_closing.

Return type:

None

Example

>>> # Sleep until market closes (on_trading_iteration will stop running until the market closes)
>>> self.await_market_to_close()
await_market_to_open(timedelta=None)#

Executes infinite loop until market opens

If the market is closed, pauses code execution until self.minutes_before_opening minutes before market opens again. If an input (float) is passed as parameter, pauses code execution until input minutes before market opens again.

Parameters:

timedelta (int) – Time in minutes before market will open to pause to. Overrides the self.minutes_before_opening.

Return type:

None

Example

>>> # Await market to open (on_trading_iteration will stop running until the market opens)
>>> self.await_market_to_open()
property backtesting_end#
property backtesting_start#
before_market_closes()#

Use this lifecycle method to execude code before the market closes. You can use self.minutes_before_closing to set the number of minutes before closing

Parameters:

None

Return type:

None

Example

>>> # Execute code before market closes
>>> def before_market_closes(self):
>>>     self.sell_all()
before_market_opens()#

Use this lifecycle method to execude code self.minutes_before_opening minutes before opening.

Return type:

None

Example

>>> # Get the data for SPY and TLT for the last 2 days
>>> def before_market_opens(self):
>>>     bars_list =  self.get_historical_prices_for_assets(["SPY", "TLT"], 2, "day")
>>>     for asset_bars in bars_list:
>>>         self.log_message(asset_bars.df)

>

before_starting_trading()#

Lifecycle method executed after the market opens and before entering the trading loop. Use this method for daily resetting variables

Return type:

None

Example

>>> # Get pricing data for the last day
>>> def before_starting_trading(self):
>>>     self.get_historical_prices("SPY", 1, "day")
calculate_returns()#
cancel_open_orders()#

Cancel all the strategy open orders.

Cancels all orders that are open and awaiting execution within a given strategy. If running multiple strategies, will only cancel the orders in the current strategy.

Parameters:

None

Return type:

None

Example

>>> # Cancel all open orders
>>> self.cancel_open_orders()
cancel_order(order)#

Cancel an order.

Cancels a single open order provided.

Parameters:

cancel. (An order object that the user seeks to) –

Return type:

None

Example

>>> # Create an order then cancel it
>>> order = self.create_order("SPY", 100, "buy")
>>> self.submit_order(order)
>>> self.cancel_order(order)
cancel_orders(orders)#

Cancel orders in all strategies.

Cancels all open orders provided in any of the running strategies.

Parameters:

orders (list of Order objects.) –

Return type:

None

Example

>>> # Create two orders then cancel them
>>> order1 = self.create_order("IBM", 100, "buy")
>>> order2 = self.create_order("AAPL", 100, "buy")
>>> self.submit_orders([order1, order2])
>>>
>>> # Cancel all orders
>>> self.cancel_orders([order1, order2])
cancel_realtime_bars(asset)#

Cancels a stream of real time bars for a given asset.

Cancels the real time bars for the given asset.

Parameters:

asset (Asset) – Asset object that has streaming data to cancel.

Return type:

None

Example

>>> # Cancel the real time bars for SPY
>>> asset = self.create_asset("SPY")
>>> self.cancel_realtime_bars(asset)
property cash#

Returns the current cash. This is the money that is not used for positions or orders (in other words, the money that is available to buy new assets, or cash).

This property is updated whenever a transaction was filled by the broker or when dividends are paid.

Crypto currencies are a form of cash. Therefore cash will always be zero.

Returns:

cash – The current cash.

Return type:

float

Example

>>> # Get the current cash available in the account
>>> self.log_message(self.cash)
create_asset(symbol: str, asset_type: str = 'stock', expiration: datetime = None, strike: float = None, right: str = None, multiplier: int = 1)#

Creates an asset object. This is used to create an asset object.

Parameters:
  • symbol (str) – The symbol of the asset.

  • asset_type (str) – The type of the asset. Can be either “stock”, “option”, or “future”, “crytpo”.

  • expiration (datetime.datetime) – The expiration date of the asset (optional, only required for options and futures).

  • strike (str) – The strike price of the asset (optional, only required for options).

  • right (str) – The right of the option (optional, only required for options).

  • multiplier (int) – The multiplier of the asset (optional, only required for options and futures).

Returns:

The asset object.

Return type:

Asset

Example

>>> # Will create a stock object
>>> asset = self.create_asset("AAPL", asset_type="stock")
>>> # Will create an option object
>>> asset = self.create_asset("AAPL", asset_type="option", expiration=datetime.datetime(2020, 1, 1), strike=100, right="CALL")
>>> # Will create a future object
>>> asset = self.create_asset("AAPL", asset_type="future", multiplier=100)
>>> # Will create a FOREX asset
>>> asset = self.create_asset(symbol="EUR", asset_type="forex")
>>> # Will create a CRYPTO asset
>>> asset = self.create(symbol="BTC", asset_type="crypto"),
>>> asset = self.create(symbol="USDT", asset_type="crypto"),
>>> asset = self.create(symbol="EUR", asset_type="crypto"),
>>> asset = self.create(symbol="ETH", asset_type="crypto"),
create_order(asset, quantity, side, limit_price=None, stop_price=None, time_in_force='gtc', good_till_date=None, take_profit_price=None, stop_loss_price=None, stop_loss_limit_price=None, trail_price=None, trail_percent=None, position_filled=False, exchange=None, quote=None, pair=None, type=None, custom_params={})#

Creates a new order for this specific strategy. Once created, an order must still be submitted.

Some notes on Crypto markets:

Crypto markets require both a base currency and a quote currency to create an order. For example, use the quote parameter.:

>>> from lumibot.entities import Asset
>>>
>>> self.create_order(
>>>     Asset(symbol='BTC', asset_type=Asset.AssetType.CRYPTO),
>>>     .50,
>>>     'buy',
>>>     quote=Asset(symbol='USDT', asset_type='crypto'),
>>> )

Orders for crypto markets are restriced to: market, limit, stop_limit.

Crypto markets’ orders are simple. There are no compound orders such oco or bracket. Also, duration of orders are all GTC.

Parameters:
  • asset (str or Asset) – The asset that will be traded. If this is just a stock, then str is sufficient. However, all assets other than stocks must use Asset.

  • quantity (int string Decimal (float will deprecate)) – The number of shares or units to trade. One may enter an int, a string number eg: “3.213”, or a Decimal obect, eg: Decimal(“3.213”). Internally all will convert to Decimal.

  • side (str) – Whether the order is buy or sell.

  • type (str) – The type of order. Order types include: 'market', 'limit', 'stop', 'stop_limit', trailing_stop, 'oco', 'bracket', 'oto'. We will try to determine the order type if you do not specify it. It is mandatory to set the type for advanced order types such as 'oco', 'bracket', 'oto'.

  • limit_price (float) – A Limit order is an order to buy or sell at a specified price or better. The Limit order ensures that if the order fills, it will not fill at a price less favorable than your limit price, but it does not guarantee a fill.

  • stop_price (float) – A Stop order is an instruction to submit a buy or sell market order if and when the user-specified stop trigger price is attained or penetrated.

  • time_in_force (str) –

    Amount of time the order is in force. Order types include:
    • 'day' Orders valid for the remainder of the day.

    • 'gtc' Good until cancelled.

    • 'gtd' Good until date.

    (Default: ‘day’)

  • good_till_date (datetime.datetime) – This is the time order is valid for Good Though Date orders.

  • take_profit_price (float) – Limit price used for bracket orders and one cancels other orders.

  • stop_loss_price (float) – Stop price used for bracket orders and one cancels other orders.

  • stop_loss_limit_price (float) – Stop loss with limit price used for bracket orders and one cancels other orders.

  • trail_price (float) – Trailing stop orders allow you to continuously and automatically keep updating the stop price threshold based on the stock price movement. trail_price sets the trailing price in dollars.

  • trail_percent (float) – Trailing stop orders allow you to continuously and automatically keep updating the stop price threshold based on the stock price movement. E.g. 0.05 would be a 5% trailing stop. trail_percent sets the trailing price in percent.

  • exchange (str) – The exchange where the order will be placed. Default = 'SMART'

  • quote (Asset) – This is the currency that the main coin being bought or sold will exchange in. For example, if trading BTC/ETH this parameter will be ‘ETH’ (as an Asset object).

  • custom_params (dict) – A dictionary of custom parameters that can be used to pass additional information to the broker. This is useful for passing custom parameters to the broker that are not supported by Lumibot. E.g. custom_params={“leverage”: 3} for Kraken margin trading.

Returns:

Order object ready to be submitted for trading.

Return type:

Order

Examples

>>> # For a market buy order
>>> order = self.create_order("SPY", 100, "buy")
>>> self.submit_order(order)
>>> # For a limit order where limit price = 100
>>> limit_order = self.create_order("SPY", 1, "buy", limit_price=100)
>>> self.submit_order(limit_order)
>>> # Sell 100 shares of TLT
>>> order = self.create_order("TLT", 100, "sell")
>>> self.submit_order(order)
>>> # For a stop loss order
>>> order = self.create_order("SPY", 100, "buy", stop_price=100.00)
>>> self.submit_order(order)
>>> # For a stop limit order
>>> order = self.create_order("SPY", 100, "buy", limit_price=100.00, stop_price=100.00)
>>> self.submit_order(order)
>>> # For a market sell order
>>> order = self.create_order("SPY", 100, "sell")
>>> self.submit_order(order)
>>> # For a limit sell order
>>> order = self.create_order("SPY", 100, "sell", limit_price=100.00)
>>> self.submit_order(order)
>>> # For an order with a trailing stop
>>> order = self.create_order("SPY", 100, "buy", trail_price=100.00)
>>> self.submit_order(order)
>>> # For an OCO order
>>> order = self.create_order(
>>>                "SPY",
>>>                100,
>>>                "sell",
>>>                take_profit_price=limit,
>>>                stop_loss_price=stop_loss,
>>>                type="oco",
>>>            )
>>> # For a bracket order
>>> order = self.create_order(
>>>                "SPY",
>>>                100,
>>>                "sell",
>>>                take_profit_price=limit,
>>>                stop_loss_price=stop_loss,
>>>                stop_loss_limit_price=stop_loss_limit,
>>>                type="bracket",
>>>            )
>>> # For a bracket order with a trailing stop
>>> order = self.create_order(
>>>                "SPY",
>>>                100,
>>>                "sell",
>>>                trail_percent=trail_percent,
>>>                take_profit_price=limit,
>>>                stop_loss_price=stop_loss,
>>>                stop_loss_limit_price=stop_loss_limit,
>>>                type="bracket",
>>>            )
>>> # For an OTO order
>>> order = self.create_order(
>>>                "SPY",
>>>                100,
>>>                "sell",
>>>                take_profit_price=limit,
>>>                stop_loss_price=stop_loss,
>>>                type="oto",
>>>            )
>>> # For a futures order
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset("ES", asset_type=Asset.AssetType.FUTURE, expiration="2019-01-01")
>>> order = self.create_order(asset, 100, "buy", limit_price=100.00)
>>> self.submit_order(order)
>>> # For a futures order with a trailing stop
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset("ES", asset_type=Asset.AssetType.FUTURE, expiration="2019-01-01")
>>> order = self.create_order(
>>>                asset,
>>>                100,
>>>                "buy",
>>>                trail_percent=trail_percent,
>>>                limit_price=limit,
>>>                stop_price=stop_loss,
>>>            )
>>> self.submit_order(order)
>>> # For an option order
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset("SPY", asset_type=Asset.AssetType.OPTION, expiration="2019-01-01", strike=100.00)
>>> order = self.create_order(asset, 100, "buy", limit_price=100.00)
>>> self.submit_order(order)
>>> # For an option order with a trailing stop
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset("SPY", asset_type=Asset.AssetType.OPTION, expiration="2019-01-01", strike=100.00)
>>> order = self.create_order(
>>>                asset,
>>>                100,
>>>                "buy",
>>>                trail_percent=trail_percent,
>>>                limit_price=limit,
>>>                stop_price=stop_loss,
>>>            )
>>> self.submit_order(order)
>>> # For a FOREX order
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset(
>>>    symbol="CHF",
>>>    currency="EUR",
>>>    asset_type=Asset.AssetType.FOREX,
>>>  )
>>> order = self.create_order(asset, 100, "buy", limit_price=100.00)
>>> self.submit_order(order)
>>> # For a options order with a limit price
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset("SPY", asset_type=Asset.AssetType.OPTION, expiration="2019-01-01", strike=100.00)
>>> order = self.create_order(asset, 100, "buy", limit_price=100.00)
>>> self.submit_order(order)
>>> # For a options order with a trailing stop
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset("SPY", asset_type=Asset.AssetType.OPTION, expiration="2019-01-01", strike=100.00)
>>> order = self.create_order(
>>>                asset,
>>>                100,
>>>                "buy",
>>>                trail_percent=trail_percent,
>>>                limit_price=limit,
>>>                stop_price=stop_loss,
>>>            )
>>> self.submit_order(order)
>>> # For a cryptocurrency order with a market price
>>> from lumibot.entities import Asset
>>>
>>> base = Asset("BTC", asset_type=Asset.AssetType.CRYPTO)
>>> quote = Asset("USD", asset_type=Asset.AssetType.CRYPTO)
>>> order = self.create_order(base, 0.05, "buy", quote=quote)
>>> self.submit_order(order)
>>> # Placing a limit order with a quote asset for cryptocurrencies
>>> from lumibot.entities import Asset
>>>
>>> base = Asset("BTC", asset_type=Aset.AssetType.CRYPTO)
>>> quote = Asset("USD", asset_type=Asset.AssetType.CRYPTO)
>>> order = self.create_order(base, 0.05, "buy", limit_price=41000,  quote=quote)
>>> self.submit_order(order)
static crypto_assets_to_tuple(base, quote)#

Check for crypto quote, convert to tuple

find_first_friday(timestamp)#
property first_iteration#

Returns True if this is the first iteration of the strategy (is True if the lifecycle method on_trading_iteration is being excuted for the first time).

Returns:

first_iteration – True if this is the first iteration of the strategy.

Return type:

bool

Example

>>> # Check if this is the first iteration
>>> if self.first_iteration:
>>>     self.log_message("This is the first iteration")
get_asset_potential_total(asset)#

Get the potential total for the asset (orders + positions).

Parameters:

asset (Asset) – Asset object who’s potential total is sought.

Returns:

The potential total for the asset. Decimals are automatically returned as floats if less than 4 decimal points

Return type:

int, float or Decimal

Example

>>> # Get the potential total for the TLT asset
>>> total = self.get_asset_potential_total("TLT")
>>> self.log_message(total)
>>> # Show the potential total for an asset
>>> asset = Asset("TLT")
>>> total = self.get_asset_potential_total(asset)
>>> self.log_message(total)
>>> # Show the potential total for an asset
>>> asset = Asset("ES", asset_type="future", expiration_date="2020-01-01")
>>> total = self.get_asset_potential_total(asset)
get_bars(assets, length, timestep='minute', timeshift=None, chunk_size=100, max_workers=200, exchange=None)#

This method is deprecated and will be removed in a future version. Please use self.get_historical_prices_for_assets() instead.

get_cash()#

Get the current cash value in your account.

Parameters:

None

Returns:

The current cash value. This is the amount of cash you have in your account, which is the amount of money you can use to buy assets. For crypto assets, this is the amount of the quote asset you have in your account (eg. USDT if that is your quote asset).

Return type:

float

get_chain(chains, exchange='SMART')#

Returns option chain for a particular exchange.

Takes in a full set of chains for all the exchanges and returns on chain for a given exchange. The full chains are returned from get_chains method.

Parameters:
  • chains (dictionary of dictionaries) – The chains dictionary created by get_chains method.

  • exchange (str optional) – The exchange such as SMART, CBOE. Default is SMART

Returns:

Format: - Multiplier (str) eg: 100 - ‘Chains’ - paired Expiration/Strke info to guarentee that the stikes are valid for the specific

expiration date. Format:

chains[‘Chains’][‘CALL’][exp_date] = [strike1, strike2, …]

Expiration Date Format: 2023-07-31

Return type:

dictionary of dictionary

Example

>>> # Will return the option chains for SPY
>>> asset = "SPY"
>>> chain = self.get_chain(asset)
get_chains(asset)#

Returns option chains.

Obtains option chain information for the asset (stock) from each of the exchanges the options trade on and returns a dictionary for each exchange.

Parameters:

asset (Asset object) – The stock whose option chain is being fetched. Represented as an asset object.

Returns:

Format: - Multiplier (str) eg: 100 - ‘Chains’ - paired Expiration/Strike info to guarentee that the strikes are valid for the specific

expiration date. Format:

chains[‘Chains’][‘CALL’][exp_date] = [strike1, strike2, …]

Expiration Date Format: 2023-07-31

Return type:

dictionary of dictionary

Example

>>> # Will return the option chains for SPY
>>> asset = "SPY"
>>> chains = self.get_chains(asset)
get_datetime(adjust_for_delay=False)#

Returns the current datetime according to the data source. In a backtest this will be the current bar’s datetime. In live trading this will be the current datetime on the exchange.

Returns:

The current datetime.

Return type:

datetime.datetime

Example

>>> # Will return the current datetime
>>> datetime = self.get_datetime()
>>> self.log_message(f"The current datetime is {datetime}")
get_datetime_range(length, timestep='minute', timeshift=None)#

Returns a list of datetimes for the given length and timestep.

Parameters:
  • length (int) – The number of datetimes to return.

  • timestep (str) – The timestep of the datetimes.

  • timeshift (int) – The number of timesteps to shift the datetimes.

Returns:

A list of datetimes.

Return type:

list

Example

>>> # Will return a list of datetimes for the current day
>>> datetimes = self.get_datetime_range(length=1, timestep="day")
>>> self.log_message(f"Datetimes: {datetimes}")
get_expiration(chains)#

Returns expiration dates for an option chain for a particular exchange.

Using the chains dictionary obtained from get_chains finds all expiry dates for the option chains on a given exchange. The return list is sorted.

Parameters:
  • chains (dictionary of dictionaries) – The chains dictionary created by get_chains method.

  • exchange (str optional) – The exchange such as SMART, CBOE. Default is SMART.

Returns:

Sorted list of dates in the form of 2022-10-13.

Return type:

list of datetime.date

Example

>>> # Will return the expiry dates for SPY
>>> asset = "SPY"
>>> expiry_dates = self.get_expiration(asset)
get_greeks(asset, asset_price=None, underlying_price=None, risk_free_rate=None, query_greeks=False)#

Returns the greeks for the option asset at the current bar.

Will return all the greeks available. API Querying for prices and rates are expensive, so they should be passed in as arguments most of the time.

Parameters:
  • asset (Asset) – Option asset only for with greeks are desired.

  • asset_price (float, optional) – The price of the option asset, by default None

  • underlying_price (float, optional) – The price of the underlying asset, by default None

  • risk_free_rate (float, optional) – The risk-free rate used in interest calculations, by default None

  • query_greeks (bool, optional) – Whether to query the greeks from the broker. By default, the greeks are calculated locally, but if the broker supports it, they can be queried instead which could theoretically be more precise.

Returns:

  • Returns a dictionary with greeks as keys and greek values as

  • values.

  • implied_volatility (float) – The implied volatility.

  • delta (float) – The option delta value.

  • option_price (float) – The option price.

  • pv_dividend (float) – The present value of dividends expected on the option’s underlying.

  • gamma (float) – The option gamma value.

  • vega (float) – The option vega value.

  • theta (float) – The option theta value.

  • underlying_price – The price of the underlying.

Example

>>> # Will return the greeks for SPY
>>> opt_asset = Asset("SPY", expiration=date(2021, 1, 1), strike=100, option_type="call"
>>> greeks = self.get_greeks(opt_asset)
>>> implied_volatility = greeks["implied_volatility"]
>>> delta = greeks["delta"]
>>> gamma = greeks["gamma"]
>>> vega = greeks["vega"]
>>> theta = greeks["theta"]
get_historical_bot_stats()#

Get the historical account value.

Returns:

The historical bot stats.

Return type:

pandas.DataFrame

Example

>>> # Get the historical bot stats
>>> bot_stats = self.get_historical_bot_stats()
>>> # Show the historical bot stats
>>> self.log_message(account_value)
get_historical_prices(asset: Asset | str, length: int, timestep: str = '', timeshift: timedelta = None, quote: Asset = None, exchange: str = None, include_after_hours: bool = True)#

Get historical pricing data for a given symbol or asset.

Return data bars for a given symbol or asset. Any number of bars can be return limited by the data available. This is set with ‘length’ in number of bars. Bars may be returned as daily or by minute. And the starting point can be shifted backwards by time or bars.

Parameters:
  • asset (str or Asset) – The symbol string representation (e.g. AAPL, GOOG, …) or asset object. Cryptocurrencies must also specify the quote currency.

  • length (int) – The number of rows (number of timesteps)

  • timestep (str) – Either "minute" for minutes data or "day" for days data default value depends on the data_source (minute for alpaca, day for yahoo, …). If you need, you can specify the width of the bars by adding a number before the timestep (e.g. “5 minutes”, “15 minutes”, “1 day”, “2 weeks”, “1month”, …)

  • timeshift (timedelta) – None by default. If specified indicates the time shift from the present. If backtesting in Pandas, use integer representing number of bars.

  • quote (Asset) – The quote currency for crypto currencies (e.g. USD, USDT, EUR, …). Default is the quote asset for the strategy.

  • exchange (str) – The exchange to pull the historical data from. Default is None (decided based on the broker)

  • include_after_hours (bool) – Whether to include after hours data. Default is True. Currently only works with Interactive Brokers.

Returns:

The bars object with all the historical pricing data. Please check the Entities.Bars object documentation for more details on how to use Bars objects. To get a DataFrame from the Bars object, use bars.df.

Return type:

Bars

Example

Extract 2 rows of SPY data with one day timestep between each row with the latest data being 24h ago (timedelta(days=1)) (in a backtest)

>>> # Get the data for SPY for the last 2 days
>>> bars =  self.get_historical_prices("SPY", 2, "day")
>>> # To get the DataFrame of SPY data
>>> df = bars.df
>>>
>>> # Then, to get the DataFrame of SPY data
>>> df = bars.df
>>> last_ohlc = df.iloc[-1] # Get the last row of the DataFrame (the most recent pricing data we have)
>>> self.log_message(f"Last price of BTC in USD: {last_ohlc['close']}, and the open price was {last_ohlc['open']}")
>>> # Get the data for AAPL for the last 30 minutes
>>> bars =  self.get_historical_prices("AAPL", 30, "minute")
>>>
>>> # Then, to get the DataFrame of SPY data
>>> df = bars.df
>>> last_ohlc = df.iloc[-1] # Get the last row of the DataFrame (the most recent pricing data we have)
>>> self.log_message(f"Last price of BTC in USD: {last_ohlc['close']}, and the open price was {last_ohlc['open']}")
>>> # Get the historical data for an AAPL option for the last 30 minutes
>>> asset = self.create_asset("AAPL", asset_type="option", expiration=datetime.datetime(2020, 1, 1), strike=100, right="call")
>>> bars =  self.get_historical_prices(asset, 30, "minute")
>>>
>>> # Then, to get the DataFrame of SPY data
>>> df = bars.df
>>> last_ohlc = df.iloc[-1] # Get the last row of the DataFrame (the most recent pricing data we have)
>>> self.log_message(f"Last price of BTC in USD: {last_ohlc['close']}, and the open price was {last_ohlc['open']}")
>>> # Get the data for BTC in USD  for the last 2 days
>>> asset_base = self.create(symbol="BTC", asset_type="crypto"),
>>> asset_quote = self.create(symbol="USDT", asset_type="crypto"),
>>>
>>> bars =  self.get_historical_prices(asset_base, 2, "day", quote=asset_quote)
>>>
>>> # Then, to get the DataFrame of SPY data
>>> df = bars.df
>>> last_ohlc = df.iloc[-1] # Get the last row of the DataFrame (the most recent pricing data we have)
>>> self.log_message(f"Last price of BTC in USD: {last_ohlc['close']}, and the open price was {last_ohlc['open']}")
get_historical_prices_for_assets(assets, length, timestep='minute', timeshift=None, chunk_size=100, max_workers=200, exchange=None, include_after_hours=True)#

Get historical pricing data for the list of assets.

Return data bars for a list of symbols or assets. Return a dictionary of bars for a given list of symbols. Works the same as get_historical_prices but take as first parameter a list of assets. Any number of bars can be return limited by the data available. This is set with length in number of bars. Bars may be returned as daily or by minute. And the starting point can be shifted backwards by time or bars.

Parameters:
  • assets (list(str/asset)) – The symbol string representation (e.g. AAPL, GOOG, …) or asset objects. Cryptocurrencies must specify the quote asset. Use tuples with the two asset objects, base first, quote second. ‘(Asset(ETH), Asset(BTC))’

  • length (int) – The number of rows (number of timesteps)

  • timestep (str) – Either "minute" for minutes data or "day" for days data default value depends on the data_source (minute for alpaca, day for yahoo, …). If you need, you can specify the width of the bars by adding a number before the timestep (e.g. “5 minutes”, “15 minutes”, “1 day”, “2 weeks”, “1month”, …)

  • timeshift (timedelta) – None by default. If specified indicates the time shift from the present. If backtesting in Pandas, use integer representing number of bars.

  • include_after_hours (bool) – True by default. If False, only return bars that are during regular trading hours. If True, return all bars. Currently only works for Interactive Brokers.

Returns:

dictionary – Return a dictionary bars for a given list of symbols. Works the same as get_historical_prices take as first parameter a list of symbols.

Return type:

Asset : bars

Example

>>> # Get the data for SPY and TLT for the last 2 days
>>> bars =  self.get_historical_prices_for_assets(["SPY", "TLT"], 2, "day")
>>> for asset in bars:
>>>     self.log_message(asset.df)
>>> # Get the data for AAPL and GOOG for the last 30 minutes
>>> bars =  self.get_historical_prices_for_assets(["AAPL", "GOOG"], 30, "minute")
>>> for asset in bars:
>>>     self.log_message(asset.df)
>>> # Get the price data for EURUSD for the last 2 days
>>> from lumibot.entities import Asset
>>> asset_base = Asset(symbol="EUR", asset_type="forex")
>>> asset_quote = Asset(symbol="USD", asset_type="forex")
>>> bars =  self.get_historical_prices_for_assets(asset_base, 2, "day", quote=asset_quote)
>>> df = bars.df
get_last_day()#

Returns the last day of the current month. In a backtest this will be the current bar’s timestamp. In live trading this will be the current timestamp on the exchange.

Returns:

The last day of the current month.

Return type:

int

Example

>>> # Will return the last day of the current month
>>> last_day = self.get_last_day()
>>> self.log_message(f"The last day of the current month is {last_day}")
get_last_minute()#

Returns the last minute of the current day. In a backtest this will be the current bar’s timestamp. In live trading this will be the current timestamp on the exchange.

Returns:

The last minute of the current day.

Return type:

int

Example

>>> # Will return the last minute of the current day
>>> last_minute = self.get_last_minute()
>>> self.log_message(f"The last minute of the current day is {last_minute}")
get_last_price(asset, quote=None, exchange=None, should_use_last_close=True)#

Takes an asset and returns the last known price

Makes an active call to the market to retrieve the last price. In backtesting will provide the close of the last complete bar.

Parameters:
  • asset (Asset object or str) – Asset object for which the last closed price will be retrieved.

  • quote (Asset object) – Quote asset object for which the last closed price will be retrieved. This is required for cryptocurrency pairs.

  • exchange (str) – Exchange name for which the last closed price will be retrieved. This is required for some cryptocurrency pairs.

  • should_use_last_close (bool) – If False, it will make Interactive Brokers only return the price of an asset if it has been trading today. Defaults to True. TODO: Should this option be depricated? It is now commented out below

Returns:

Last closed price as either a float or Decimal object.

Return type:

Float or Decimal

Example

>>> # Will return the last price for the asset
>>> asset = "SPY"
>>> last_price = self.get_last_price(asset)
>>> self.log_message(f"Last price for {asset} is {last_price}")
>>> # Will return the last price for a crypto asset
>>> base = Asset(symbol="BTC", asset_type="crypto")
>>> quote = Asset(symbol="USDT", asset_type="crypto")
>>> last_price = self.get_last_price(base, quote=quote)
>>> self.log_message(f"Last price for BTC/USDT is {last_price}")
>>> # Will return the last price for a crypto asset
>>> base = Asset(symbol="BTC", asset_type="crypto")
>>> quote = Asset(symbol="USD", asset_type="forex")
>>> last_price = self.get_last_price(base, quote=quote)
>>> self.log_message(f"Last price for BTC/USDT is {last_price}")
>>> # Will return the last price for a futures asset
>>> self.base = Asset(
>>>     symbol="ES",
>>>     asset_type="future",
>>>     expiration=date(2022, 12, 16),
>>> )
>>> price = self.get_last_price(asset=self.base, exchange="CME")
get_last_prices(assets, quote=None, exchange=None)#

Takes a list of assets and returns the last known prices

Makes an active call to the market to retrieve the last price. In backtesting will provide the close of the last complete bar.

Parameters:
  • assets (list of Asset objects) – List of Asset objects for which the last closed price will be retrieved.

  • quote (Asset object) – Quote asset object for which the last closed price will be retrieved. This is required for cryptocurrency pairs.

  • exchange (str) – The exchange to get the prices of.

Returns:

Last known closing prices as either a list of floats or Decimal objects.

Return type:

list of floats or Decimals

Example

>>> # Will return the last price for the assets
>>> assets = ["SPY", "TLT"]
>>> last_prices = self.get_last_prices(assets)
get_lines_df()#

Returns a dataframe of the lines on the indicator chart.

Returns:

The lines on the indicator chart.

Return type:

pandas.DataFrame

get_markers_df()#

Returns the markers on the indicator chart as a pandas DataFrame.

Returns:

The markers on the indicator chart.

Return type:

pandas.DataFrame

get_multiplier(chains, exchange='SMART')#

Returns option chain for a particular exchange.

Using the chains dictionary obtained from get_chains finds all the multipliers for the option chains on a given exchange.

Parameters:
  • chains (dictionary of dictionaries) – The chains dictionary created by get_chains method.

  • exchange (str optional) – The exchange such as SMART, CBOE. Default is SMART

Returns:

Sorted list of dates in the form of 20221013.

Return type:

list of str

Example

>>> # Will return the multiplier for SPY
>>> asset = "SPY"
>>> multiplier = self.get_multiplier(asset)
get_next_trading_day(date, exchange='NYSE')#

Finds the next trading day for the given date and exchange.

Parameters:
  • date (str) – The date from which to find the next trading day, in ‘YYYY-MM-DD’ format.

  • exchange (str) – The exchange calendar to use, default is ‘NYSE’.

Returns:

The next trading day after the given date.

Return type:

next_trading_day (datetime.date)

get_option_expiration_after_date(dt: date)#

Returns the next option expiration date after the given date.

Parameters:

dt (datetime.date) – The date to find the next option expiration date after.

Returns:

The next option expiration date after the given date.

Return type:

datetime.date

Example

>>> # Will return the next option expiration date after the given date
>>> dt = datetime.date(2021, 1, 1)
>>> next_option_expiration = self.get_next_option_expiration(dt)
get_order(identifier)#

Get a tracked order given an identifier. Check the details of the order including status, etc.

Returns:

An order objects for the identifier

Return type:

Order or None

Example

>>> # Get the order object for the order id
>>> order = self.get_order(order_id)
>>> # Show the status of the order
>>> self.log_message(order.status)
get_orders()#

Get all the current open orders.

Returns:

Order objects for the strategy if there are tracked

Return type:

list of Order objects

Example

>>> # Get all tracked orders
>>> orders = self.get_orders()
>>> for order in orders:
>>>     # Show the status of each order
>>>     self.log_message(order.status)
>>> # Get all open orders
>>> orders = self.get_tracked_orders()
>>> for order in orders:
>>>     # Show the status of each order
>>>     self.log_message(order.status)
>>>     # Check if the order is open
>>>     if order.status == "open":
>>>         # Cancel the order
>>>         self.cancel_order(order)
get_parameters()#

Get the parameters of the strategy.

Returns:

parameters – The parameters of the strategy.

Return type:

dict

get_portfolio_value()#

Get the current portfolio value (cash + net equity).

Parameters:

None

Returns:

The current portfolio value, which is the sum of the cash and net equity. This is the total value of your account, which is the amount of money you would have if you sold all your assets and closed all your positions. For crypto assets, this is the total value of your account in the quote asset (eg. USDT if that is your quote asset).

Return type:

float

get_position(asset)#

Get a tracked position given an asset for the current strategy.

Seeks out and returns the position object for the given asset in the current strategy.

Parameters:

asset (Asset or str) – Asset object who’s traded positions is sought.

Returns:

A position object for the assset if there is a tracked position or returns None to indicate no tracked position.

Return type:

Position or None

Example

>>> # Get the position for the TLT asset
>>> position = self.get_position("TLT")
>>> # Show the quantity of the TLT position
>>> self.log_message(position.quantity)
get_positions()#

Get all positions for the account.

Parameters:

None

Returns:

A list of Position objects for the strategy if there are tracked positions or returns and empty list to indicate no tracked position.

Return type:

list

Example

>>> # Get all tracked positions
>>> positions = self.get_positions()
>>> for position in positions:
>>>     # Show the quantity of each position
>>>     self.log_message(position.quantity)
>>>     # Show the asset of each position
>>>     self.log_message(position.asset)
get_quote(asset)#

Get a quote for the asset.

NOTE: This currently only works with Tradier. It does not work with backtetsing or other brokers.

Parameters:

asset (Asset object) – The asset for which the quote is needed.

Returns:

A dictionary with the quote information, eg. bid, ask, etc.

Return type:

dict

get_realtime_bars(asset)#

Retrieve the real time bars as dataframe.

Returns the current set of real time bars as a dataframe. The datetime will be in the index. The columns of the dataframe are:

  • open

  • high

  • low

  • close

  • volume

  • vwap

  • count (trade count)

Parameters:

asset (Asset object) – The asset that has a stream active.

Returns:

dataframe – Dataframe containing the most recent pricing information for the asset. The data returned will be the datetime in the index and the following columns.

  • open

  • high

  • low

  • close

  • volume

  • vwap

  • count (trade count)

The length of the dataframe will have been set the intial start of the real time bars.

Return type:

Pandas Dataframe.

get_round_day(timeshift=0)#

Returns the current day rounded to the nearest day. In a backtest this will be the current bar’s timestamp. In live trading this will be the current timestamp on the exchange.

Parameters:

timeshift (int) – The number of days to shift the time.

Returns:

The current day rounded to the nearest day.

Return type:

int

Example

>>> # Will return the current day rounded to the nearest day
>>> round_day = self.get_round_day()
>>> self.log_message(f"The current day rounded to the nearest day is {round_day}")
get_round_minute(timeshift=0)#

Returns the current minute rounded to the nearest minute. In a backtest this will be the current bar’s timestamp. In live trading this will be the current timestamp on the exchange.

Parameters:

timeshift (int) – The number of minutes to shift the time.

Returns:

The current minute rounded to the nearest minute.

Return type:

int

Example

>>> # Will return the current minute rounded to the nearest minute
>>> round_minute = self.get_round_minute()
>>> self.log_message(f"The current minute rounded to the nearest minute is {round_minute}")
get_selling_order(position)#

Get the selling order for a position.

Parameters:

position (Position) – The position to get the selling order for.

Return type:

Order or None

Example

>>> # Get the selling order for a position
>>> position = self.get_position("SPY")
>>> order = self.get_selling_order(position)
>>> self.submit_order(order)
>>> # Sell all positions owned by the account
>>> for position in self.get_positions():
>>>    order = self.get_selling_order(position)
>>>    self.submit_order(order)
get_stats_from_database(stats_table_name)#
get_strikes(asset, chains=None)#

Returns a list of strikes for a give underlying asset.

Using the chains dictionary obtained from get_chains finds all the multiplier for the option chains on a given exchange.

Parameters:
  • asset (Asset) – Asset object as normally used for an option but without the strike information. The Asset object must be an option asset type.

  • chains (dictionary of dictionaries, optional) – The chains dictionary created by get_chains method. If not provided, the method will fetch the chains for the asset.

Returns:

Sorted list of strikes as floats.

Return type:

list of floats

Example

>>> # Will return the strikes for SPY
>>> asset = "SPY"
>>> strikes = self.get_strikes(asset)
get_symbol_bars(asset, length, timestep='', timeshift=None, quote=None, exchange=None)#

This method is deprecated and will be removed in a future version. Please use self.get_historical_prices() instead.

get_tick(asset)#

Takes an Asset and returns the last known price

get_timestamp()#

Returns the current timestamp according to the data source. In a backtest this will be the current bar’s timestamp. In live trading this will be the current timestamp on the exchange.

Returns:

The current timestamp.

Return type:

int

Example

>>> # Will return the current timestamp
>>> timestamp = self.get_timestamp()
>>> self.log_message(f"The current timestamp is {timestamp}")
get_tracked_assets()#

Get the list of assets for positions and open orders for the current strategy

Returns:

A list of assets for the strategy if there are tracked positions or returns and empty list to indicate no tracked.

Return type:

list

Example

>>> # Get all tracked assets
>>> assets = self.get_tracked_assets()
>>> for asset in assets:
>>>     # Show the asset name
>>>     self.log_message(asset.symbol)
>>>     # Show the quantity of the asset
>>>     self.log_message(asset.quantity)
get_tracked_order(identifier)#

Deprecated, will be removed in the future. Please use get_order() instead.

get_tracked_orders(identifier)#

Deprecated, will be removed in the future. Please use get_orders() instead.

get_tracked_position(asset)#

Deprecated, will be removed in the future. Please use get_position() instead.

get_tracked_positions()#

Deprecated, will be removed in the future. Please use get_positions() instead.

get_yesterday_dividend(asset)#

Get the dividend for the previous day.

Parameters:

asset (Asset object) – The asset to get the dividend for.

Returns:

dividend – The dividend amount.

Return type:

float

Example

>>> # Get the dividend for SPY
>>> asset = self.create_asset("SPY")
>>> self.get_yesterday_dividend(asset)
get_yesterday_dividends(assets)#

Get the dividends for the previous day.

Parameters:

assets (list(Asset object)) – The assets to get the dividends for.

Returns:

dividends – The dividend amount for each asset.

Return type:

list(float)

Example

>>> # Get the dividends for SPY and TLT
>>> from lumibot.entities import Asset
>>> assets = [Asset("SPY"), Asset("TLT")]
>>> self.get_yesterday_dividends(assets)
property initial_budget#

Returns the initial budget for the strategy.

Returns:

The initial budget for the strategy.

Return type:

float

Example

>>> self.log_message(f'Strategy initial budget: {self.initial_budget}')
initialize(parameters=None)#

Initialize the strategy. Use this lifecycle method to initialize parameters.

This method is called once before the first time the strategy is run.

Return type:

None

Example

>>> # Initialize the strategy
>>> def initialize(self):
>>>   self.sleeptime = 5
>>>   self.ticker = "AAPL"
>>>   self.minutes_before_closing = 5
>>>   self.max_bars = 100
>>> # Initialize the strategy
>>> def initialize(self):
>>>   # Set the strategy to call on_trading_interation every 2 seconds
>>>   self.sleeptime = "2S"
>>>   self.count = 0
>>> # Initialize the strategy
>>> def initialize(self):
>>>   # Set the strategy to call on_trading_interation every 10 minutes
>>>   self.sleeptime = "10M"
>>>   self.count = 0
>>> # Initialize the strategy
>>> def initialize(self):
>>>   # Set the strategy to call on_trading_interation every 20 hours
>>>   self.sleeptime = "20H"
>>>   self.count = 0
>>> # Initialize the strategy
>>> def initialize(self):
>>>   # Set the strategy to call on_trading_interation every 2 days (48 hours)
>>>   self.sleeptime = "2D"
>>>   self.count = 0
property is_backtesting#

Returns True if the strategy is running in backtesting mode.

Returns:

is_backtesting – True if the strategy is running in backtesting mode.

Return type:

bool

Example

>>> # Check if the strategy is running in backtesting mode
>>> if self.is_backtesting:
>>>     self.log_message("Running in backtesting mode")
property last_on_trading_iteration_datetime#

Returns the datetime of the last iteration.

Returns:

The datetime of the last iteration.

Return type:

datetime

Example

>>> self.log_message(f'The last trading iteration happened at: {self.last_on_trading_iteration_datetime}')
load_pandas(asset, df)#
localize_datetime(dt: datetime)#

Returns a datetime localized to the data source’s timezone.

Parameters:

dt (datetime.datetime) – The datetime to localize.

Returns:

The localized datetime.

Return type:

datetime.datetime

Example

>>> # Will return a datetime localized to the data source's timezone
>>> localize_datetime = self.localize_datetime(dt=datetime.datetime(2020, 1, 1))
>>> self.log_message(f"Localized datetime: {localize_datetime}")
log_message(message, color=None, broadcast=False)#

Logs an info message prefixed with the strategy name.

Uses python logging to log the message at the info level. Logging goes to the logging file, not the console.

Parameters:
  • message (str) – String message for logging.

  • color (str) – Color of the message. Eg. “red” or “green”.

  • broadcast (bool) – If True, the message will be broadcasted to any connected message services.

Returns:

message – Strategy name plus the original message.

Return type:

str

Example

>>> self.log_message('Sending a buy order')
property minutes_before_closing#

Get or set the number of minutes that the strategy will stop executing before market closes.

The lifecycle method on_trading_iteration is executed inside a loop that stops only when there is only minutes_before_closing minutes remaining before market closes. By default equals to 5 minutes.

Parameters:

minutes_before_closing (int) – The number of minutes before market closes that the strategy will stop executing.

Returns:

minutes_before_closing – The number of minutes before market closes that the strategy will stop executing.

Return type:

int

Example

>>> # Set the minutes before closing to 5
>>> self.minutes_before_closing = 5
>>> # Get the minutes before closing
>>> self.log_message(self.minutes_before_closing)
>>> # Set the minutes before closing to 10 in the initialize method
>>> def initialize(self):
>>>     self.minutes_before_closing = 10
property minutes_before_opening#

Get or set the number of minutes that the strategy will start executing before the market opens. The lifecycle method before_market_opens is executed minutes_before_opening minutes before the market opens. By default, equals to 60 minutes.

Returns:

The number of minutes before the market opens.

Return type:

int

Example

>>> # Set the number of minutes before the market opens
>>> self.minutes_before_opening = 10
>>> # Set the number of minutes before the market opens to 0 in the initialize method
>>> def initialize(self):
>>>     self.minutes_before_opening = 0
property name#

Returns the name of the strategy.

Returns:

The name of the strategy.

Return type:

str

Example

>>> self.log_message(f'Strategy name: {self.name}')
on_abrupt_closing()#

Use this lifecycle event to execute code when the main trader was shut down (Keybord Interuption)

Parameters:

None

Return type:

None

Example

>>> def on_abrupt_closing(self):
>>>     self.log_message("Abrupt closing")
>>>     self.sell_all()
on_bot_crash(error)#

Use this lifecycle event to execute code when an exception is raised and the bot crashes

Parameters:

error (Exception) – The exception that was raised.

Return type:

None

Example

>>> def on_bot_crash(self, error):
>>>     self.log_message(error)
>>> # Sell all assets on crash
>>> def on_bot_crash(self, error):
>>>     self.sell_all()
on_canceled_order(order)#

Use this lifecycle event to execute code when an order is canceled.

Parameters:

order (Order object) – The order that is being canceled.

Return type:

None

Example

>>> def on_canceled_order(self, order):
>>>     if order.asset == "AAPL":
>>>         self.log_message("Order for AAPL canceled")
on_filled_order(position, order, price, quantity, multiplier)#

Use this lifecycle event to execute code when an order has been filled by the broker.

Parameters:
  • position (Position object) – The position that is being filled.

  • order (Order object) – The order that is being filled.

  • price (float) – The price of the fill.

  • quantity (int) – The quantity of the fill.

  • multiplier (float) – The multiplier of the fill.

Return type:

None

Example

>>> def on_filled_order(self, position, order, price, quantity, multiplier):
>>>     if order.asset == "AAPL":
>>>         self.log_message("Order for AAPL filled")
>>>         self.log_message(f"Price: {price}")
>>> # Update dictionary with new position
>>> def on_filled_order(self, position, order, price, quantity, multiplier):
>>>     if order.asset == "AAPL":
>>>         self.log_message("Order for AAPL filled")
>>>         self.log_message(f"Price: {price}")
>>>         self.positions["AAPL"] = position
on_new_order(order)#

Use this lifecycle event to execute code when a new order is being processed by the broker

Parameters:

order (Order object) – The order that is being processed.

Return type:

None

Example

>>> def on_new_order(self, order):
>>>     if order.asset == "AAPL":
>>>         self.log_message("Order for AAPL")
on_parameters_updated(parameters)#

Use this lifecycle event to execute code when the parameters are updated.

Parameters:

parameters (dict) – The parameters that are being updated.

Return type:

None

Example

>>> def on_parameters_updated(self, parameters):
>>>     self.log_message(f"Parameters updated: {parameters}")
on_partially_filled_order(position, order, price, quantity, multiplier)#

Use this lifecycle event to execute code when an order has been partially filled by the broker

Parameters:
  • position (Position object) – The position that is being filled.

  • order (Order object) – The order that is being filled.

  • price (float) – The price of the fill.

  • quantity (int) – The quantity of the fill.

  • multiplier (float) – The multiplier of the fill.

Return type:

None

Example

>>> def on_partially_filled_order(self, position, order, price, quantity, multiplier):
>>>     if order.asset == "AAPL":
>>>         self.log_message(f"{quantity} shares of AAPL partially filled")
>>>         self.log_message(f"Price: {price}")
on_strategy_end()#

Use this lifecycle method to execute code when strategy reached its end. Used to dump statistics when backtesting finishes

Parameters:

None

Return type:

None

Example

>>> # Log end of strategy
>>> def on_strategy_end(self):
>>>     self.log_message("The strategy is complete")
on_trading_iteration()#

Use this lifecycle method for your main trading loop. This method is called every self.sleeptime minutes (or seconds/hours/days if self.sleeptime is “30S”, “1H”, “1D”, etc.).

Example

>>> def on_trading_iteration(self):
>>>     self.log_message("Hello")
>>>     order = self.create_order("SPY", 10, "buy")
>>>     self.submit_order(order)
options_expiry_to_datetime_date(date)#

Converts an IB Options expiry to datetime.date.

Parameters:

date (str) – String in the format of ‘YYYYMMDD’

Return type:

datetime.date

Example

>>> # Will return the date for the expiry
>>> date = "20200101"
>>> expiry_date = self.options_expiry_to_datetime_date(date)
>>> self.log_message(f"Expiry date for {date} is {expiry_date}")
property portfolio_value#

Returns the current portfolio value (cash + positions value).

Returns the portfolio value of positions plus cash in US dollars.

Crypto markets will attempt to resove to US dollars as a quote currency.

Returns:

portfolio_value – The current portfolio value. Includes the actual values of shares held by the current strategy plus the total cash.

Return type:

float

Example

>>> # Get the current portfolio value
>>> self.log_message(self.portfolio_value)
property positions#
property pytz#

Returns the pytz object of the data source. By default, America/New_York.

Returns:

The pytz object of the data source.

Return type:

pytz.timezone

Example

>>> # Will return the pytz object of the data source
>>> pytz = self.pytz
>>> self.log_message(f"pytz: {pytz}")
property quote_asset#

Returns the quote asset for the strategy. The quote asset is what is considered “cash” (as in self.cash), and it is the currency that self.portfolio_value uses.

Returns:

The quote asset for the strategy

Return type:

Asset

Example

>>> self.log_message(f"The quote asset for this strategy is {self.quote_asset}")
property risk_free_rate#
sell_all(cancel_open_orders=True)#

Sell all strategy positions.

The system will generate closing market orders for each open position. If cancel_open_orders is True, then all open orders will also be cancelled.

Open orders are cancelled before the positions are closed.

Parameters:

cancel_open_orders (boolean) – Cancel all order if True, leave all orders in place if False. Default is True.

Return type:

None

Example

>>> # Will close all positions for the strategy
>>> self.sell_all()
send_account_summary_to_discord()#
send_discord_message(message, image_buf=None, silent=True)#

Sends a message to Discord

send_result_text_to_discord(returns_text, portfolio_value, cash)#
send_spark_chart_to_discord(stats_df, portfolio_value, now, days=180)#
set_market(market)#

Set the market for trading hours.

Setting the market will determine the trading hours for live trading and for Yahoo backtesting. Not applicable to Pandas backtesting.

Crypto markets are always 24/7. NASDAQ is default.

Parameters:

market (str) –

Short form for the markets. List of markets available are:

”MarketCalendar”, “ASX”, “BMF”, “CFE”, “NYSE”, “stock”, “NASDAQ”, “BATS”, “CME_Equity”, “CBOT_Equity”, “CME_Agriculture”, “CBOT_Agriculture”, “COMEX_Agriculture”, “NYMEX_Agriculture”, “CME_Rate”, “CBOT_Rate”, “CME_InterestRate”, “CBOT_InterestRate”, “CME_Bond”, “CBOT_Bond”, “EUREX”, “HKEX”, “ICE”, “ICEUS”, “NYFE”, “JPX”, “LSE”, “OSE”, “SIX”, “SSE”, “TSX”, “TSXV”, “BSE”, “TASE”, “TradingCalendar”, “ASEX”, “BVMF”, “CMES”, “IEPA”, “XAMS”, “XASX”, “XBKK”, “XBOG”, “XBOM”, “XBRU”, “XBUD”, “XBUE”, “XCBF”, “XCSE”, “XDUB”, “XFRA”, “XETR”, “XHEL”, “XHKG”, “XICE”, “XIDX”, “XIST”, “XJSE”, “XKAR”, “XKLS”, “XKRX”, “XLIM”, “XLIS”, “XLON”, “XMAD”, “XMEX”, “XMIL”, “XMOS”, “XNYS”, “XNZE”, “XOSL”, “XPAR”, “XPHS”, “XPRA”, “XSES”, “XSGO”, “XSHG”, “XSTO”, “XSWX”, “XTAE”, “XTAI”, “XTKS”, “XTSE”, “XWAR”, “XWBO”, “us_futures”, “24/7”, “24/5”,

(default: NASDAQ)

The market to set.

Return type:

None

Example

>>> # Set the market to 24/7
>>> def initialize(self):
>>>    # Set the market to 24/7
>>>    self.set_market('24/7')
>>> # Set the market to NASDAQ
>>> self.set_market('NASDAQ')
>>> # Set the market to NYSE
>>> self.set_market('NYSE')
>>> # Set the market to 24/5
>>> self.set_market('24/5')
>>> # Set the market to us_futures
>>> self.set_market('us_futures')
>>> # Set the market to stock
>>> self.set_market('stock')
>>> # Set the market to BATS
>>> self.set_market('BATS')
>>> # Set the market to CME_Equity
>>> self.set_market('CME_Equity')
set_parameter_defaults(parameters)#

Set the default parameters of the strategy.

Parameters:

parameters (dict) – The parameters to set defaults for. This will not overwrite existing parameters if they have already been set.

Return type:

None

set_parameters(parameters)#

Set the default parameters of the strategy.

Parameters:

parameters (dict) – The parameters to set. These new parameters will overwrite the existing parameters (including the default settings).

Return type:

None

should_send_account_summary_to_discord()#
sleep(sleeptime)#

Sleep for sleeptime seconds.

Use to pause the execution of the program. This should be used instead of time.sleep within the strategy.

Parameters:

sleeptime (float) – Time in seconds the program will be paused.

Return type:

None

Example

>>> # Sleep for 5 seconds
>>> self.sleep(5)
property sleeptime#

Get or set the current sleep time for the strategy.

Sleep time is the time the program will pause between executions of on_trading_iteration and trace_stats. This is used to control the speed of the program.

By default, equals 1 minute. You can set the sleep time as an integer which will be interpreted as minutes. eg: sleeptime = 50 would be 50 minutes. Conversely, you can enter the time as a string with the duration numbers first, followed by the time units: ‘M’ for minutes, ‘S’ for seconds eg: ‘”300S”’ is 300 seconds, ‘”10M”’ is 10 minutes.

Returns:

sleeptime – Sleep time in minutes or a string with the duration numbers first, followed by the time units: S for seconds, M for minutes, H for hours’ or D for days.

Return type:

int or str

Example

>>> # This is usually used in the initialize method
>>> # Set the sleep time to 5 minutes in the initialize method
>>> def initialize(self): # Your initialize lifecycle method
>>>     self.sleeptime = '5M'
>>> # Set the sleep time to 10 seconds in the initialize method
>>> def initialize(self): # Your initialize lifecycle method
>>>     self.sleeptime = '10S'
>>> # Set the sleeptime to 10 minutes
>>> self.sleeptime = 10
>>> # Set the sleeptime to 300 seconds
>>> self.sleeptime = "300S"
>>> # Set the sleep time to 5 minutes
>>> self.sleeptime = 5
>>> # Set the sleep time to 5 seconds
>>> self.sleeptime = "5S"
>>> # Set the sleep time to 2 hours
>>> self.sleeptime = "2H"
>>> # Set the sleep time to 2 days
>>> self.sleeptime = "2D"
start_realtime_bars(asset, keep_bars=30)#

Starts a real time stream of tickers for Interactive Broker only.

This allows for real time data to stream to the strategy. Bars are fixed at every fix seconds. They will arrive in the strategy in the form of a dataframe. The data returned will be:

  • datetime

  • open

  • high

  • low

  • close

  • volume

  • vwap

  • count (trade count)

Parameters:
  • asset (Asset object) – The asset to stream.

  • keep_bars (int) – How many bars/rows to keep of data. If running for an extended period of time, it may be desirable to limit the size of the data kept.

Return type:

None

property stats#
property stats_file#
submit_order(order)#

Submit an order for an asset

Submits an order object for processing by the active broker.

Parameters:

order (Order object) – Order object containing the asset and instructions for executing the order.

Returns:

Processed order object.

Return type:

Order object

Example

>>> # For a market buy order
>>> order = self.create_order("SPY", 100, "buy")
>>> self.submit_order(order)
>>> # For a limit buy order
>>> order = self.create_order("SPY", 100, "buy", limit_price=100.00)
>>> self.submit_order(order)
>>> # For a stop loss order
>>> order = self.create_order("SPY", 100, "buy", stop_price=100.00)
>>> self.submit_order(order)
>>> # For a stop limit order
>>> order = self.create_order("SPY", 100, "buy", limit_price=100.00, stop_price=100.00)
>>> self.submit_order(order)
>>> # For a market sell order
>>> order = self.create_order("SPY", 100, "sell")
>>> self.submit_order(order)
>>> # For a limit sell order
>>> order = self.create_order("SPY", 100, "sell", limit_price=100.00)
>>> self.submit_order(order)
>>> # For buying a future
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset(
>>>    "ES",
>>>    asset_type=Asset.AssetType.FUTURE,
>>>    expiration_date="2020-01-01",
>>>    multiplier=100)
>>> order = self.create_order(asset, 100, "buy")
>>> self.submit_order(order)
>>> # For selling a future
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset(
>>>    "ES",
>>>    asset_type=Asset.AssetType.FUTURE,
>>>    expiration_date="2020-01-01"
>>>    multiplier=100)
>>> order = self.create_order(asset, 100, "sell")
>>> self.submit_order(order)
>>> # For buying an option
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset(
>>>    "SPY",
>>>    asset_type=Asset.AssetType.OPTION,
>>>    expiration_date="2020-01-01",
>>>    strike_price=100.00,
>>>    right="call")
>>> order = self.create_order(asset, 10, "buy")
>>> self.submit_order(order)
>>> # For selling an option
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset(
>>>    "SPY",
>>>    asset_type=Asset.AssetType.OPTION,
>>>    expiration_date="2020-01-01",
>>>    strike_price=100.00,
>>>    right="call")
>>> order = self.create_order(asset, 10, "sell")
>>> self.submit_order(order)
>>> # For buying a stock
>>> asset = Asset("SPY")
>>> order = self.create_order(asset, 10, "buy")
>>> self.submit_order(order)
>>> # For selling a stock
>>> asset = Asset("SPY")
>>> order = self.create_order(asset, 10, "sell")
>>> self.submit_order(order)
>>> # For buying a stock with a limit price
>>> asset = Asset("SPY")
>>> order = self.create_order(asset, 10, "buy", limit_price=100.00)
>>> self.submit_order(order)
>>> # For selling a stock with a limit price
>>> asset = Asset("SPY")
>>> order = self.create_order(asset, 10, "sell", limit_price=100.00)
>>> self.submit_order(order)
>>> # For buying a stock with a stop price
>>> asset = Asset("SPY")
>>> order = self.create_order(asset, 10, "buy", stop_price=100.00)
>>> self.submit_order(order)
>>> # For buying FOREX
>>> from lumibot.entities import Asset
>>>
>>> base_asset = Asset(
    symbol="GBP,
    asset_type=Asset.AssetType.FOREX,
)
>>> quote_asset = Asset(
    symbol="USD",
    asset_type=Asset.AssetType.FOREX,
)
>>> order = self.create_order(asset, 10, "buy", quote=quote_asset)
>>> self.submit_order(order)
>>> # For selling FOREX
>>> from lumibot.entities import Asset
>>>
>>> base_asset = Asset(
    symbol="EUR",
    asset_type=Asset.AssetType.FOREX,
)
>>> quote_asset = Asset(
    symbol="USD",
    asset_type=Asset.AssetType.FOREX,
)
>>> order = self.create_order(asset, 10, "sell", quote=quote_asset)
>>> self.submit_order(order)
>>> # For buying an option with a limit price
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset(
>>>    "SPY",
>>>    asset_type=Aset.AssetType.OPTION,
>>>    expiration_date="2020-01-01",
>>>    strike_price=100.00,
>>>    right="call")
>>> order = self.create_order(asset, 10, "buy", limit_price=100.00)
>>> self.submit_order(order)
>>> # For selling an option with a limit price
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset(
>>>    "SPY",
>>>    asset_type=Asset.AssetType.OPTION,
>>>    expiration_date="2020-01-01",
>>>    strike_price=100.00,
>>>    right="call")
>>> order = self.create_order(asset, 10, "sell", limit_price=100.00)
>>> self.submit_order(order)
>>> # For buying an option with a stop price
>>> from lumibot.entities import Asset
>>>
>>> asset = Asset(
>>>    "SPY",
>>>    asset_type=Asset.AssetType.OPTION,
>>>    expiration_date="2020-01-01",
>>>    strike_price=100.00,
>>>    right="call")
>>> order = self.create_order(asset, 10, "buy", stop_price=100.00)
>>> # For selling a stock with a stop price
>>> asset = Asset("SPY")
>>> order = self.create_order(asset, 10, "sell", stop_price=100.00)
>>> self.submit_order(order)
>>> # For buying a stock with a trailing stop price
>>> asset = Asset("SPY")
>>> order = self.create_order(asset, 10, "buy", trailing_stop_price=100.00)
>>> self.submit_order(order)
>>> # For selling a stock with a trailing stop price
>>> asset = Asset("SPY")
>>> order = self.create_order(asset, 10, "sell", trailing_stop_price=100.00)
>>> self.submit_order(order)
>>> # For buying a crypto with a market price
>>> from lumibot.entities import Asset
>>>
>>> asset_base = Asset(
>>>    "BTC",
>>>    asset_type=Asset.AssetType.CRYPTO,
>>> )
>>> asset_quote = Asset(
>>>    "USD",
>>>    asset_type=Asset.AssetType.CRYPTO,
>>> )
>>> order = self.create_order(asset_base, 0.1, "buy", quote=asset_quote)
>>> or...
>>> order = self.create_order((asset_base, asset_quote), 0.1, "buy")
>>> self.submit_order(order)
>>> # For buying a crypto with a limit price
>>> from lumibot.entities import Asset
>>>
>>> asset_base = Asset(
>>>    "BTC",
>>>    asset_type=Asset.AssetType.CRYPTO,
>>> )
>>> asset_quote = Asset(
>>>    "USD",
>>>    asset_type=Asset.AssetType.CRYPTO,
>>> )
>>> order = self.create_order(asset_base, 0.1, "buy", limit_price="41250", quote=asset_quote)
>>> or...
>>> order = self.create_order((asset_base, asset_quote), 0.1, "buy", limit_price="41250")
>>> self.submit_order(order)
>>> # For buying a crypto with a stop limit price
>>> from lumibot.entities import Asset
>>>
>>> asset_base = Asset(
>>>    "BTC",
>>>    asset_type=Asset.AssetType.CRYPTO,
>>> )
>>> asset_quote = Asset(
>>>    "USD",
>>>    asset_type=Asset.AssetType.CRYPTO,
>>> )
>>> order = self.create_order(asset_base, 0.1, "buy", limit_price="41325", stop_price="41300", quote=asset_quote)
>>> or...
>>> order = self.create_order((asset_base, asset_quote), 0.1, "buy", limit_price="41325", stop_price="41300",)
>>> self.submit_order(order)
>>> # For an OCO order
>>> order = self.create_order(
>>>                "SPY",
>>>                100,
>>>                "sell",
>>>                take_profit_price=limit,
>>>                stop_loss_price=stop_loss,
>>>                type="oco",
>>>            )
>>> self.submit_order(order)
submit_orders(orders, **kwargs)#

Submit a list of orders

Submits a list of orders for processing by the active broker.

Parameters:
  • orders (list of orders) – A list of order objects containing the asset and instructions for the orders.

  • is_multileg (bool) – Tradier only. A boolean value to indicate if the orders are part of one multileg order. Currently this is only available for Tradier.

  • order_type (str) – Tradier only. The order type for the multileg order. Possible values are: (‘market’, ‘debit’, ‘credit’, ‘even’). Default is ‘market’.

  • duration (str) – Tradier only. The duration for the multileg order. Possible values are: (‘day’, ‘gtc’, ‘pre’, ‘post’). Default is ‘day’.

  • price (float) – Tradier only. The limit price for the multileg order. Required for ‘debit’ and ‘credit’ order types.

  • tag (str) – Tradier only. A tag for the multileg order.

Returns:

List of processed order objects.

Return type:

list of Order objects

Example

>>> # For 2 market buy orders
>>> order1 = self.create_order("SPY", 100, "buy")
>>> order2 = self.create_order("TLT", 200, "buy")
>>> self.submit_orders([order1, order2])
>>> # For 2 limit buy orders
>>> order1 = self.create_order("SPY", 100, "buy", limit_price=100.00)
>>> order2 = self.create_order("TLT", 200, "buy", limit_price=100.00)
>>> self.submit_orders([order1, order2])
>>> # For 2 stop loss orders
>>> order1 = self.create_order("SPY", 100, "buy", stop_price=100.00)
>>> order2 = self.create_order("TLT", 200, "buy", stop_price=100.00)
>>> self.submit_orders([order1, order2])
>>> # For 2 stop limit orders
>>> order1 = self.create_order("SPY", 100, "buy", limit_price=100.00, stop_price=100.00)
>>> order2 = self.create_order("TLT", 200, "buy", limit_price=100.00, stop_price=100.00)
>>> self.submit_orders([order1, order2])
>>> # For 2 market sell orders
>>> order1 = self.create_order("SPY", 100, "sell")
>>> order2 = self.create_order("TLT", 200, "sell")
>>> self.submit_orders([order1, order2])
>>> # For 2 limit sell orders
>>> order1 = self.create_order("SPY", 100, "sell", limit_price=100.00)
>>> order2 = self.create_order("TLT", 200, "sell", limit_price=100.00)
>>> self.submit_orders([order1, order2])
>>> # For 2 stop loss orders
>>> order1 = self.create_order("SPY", 100, "sell", stop_price=100.00)
>>> order2 = self.create_order("TLT", 200, "sell", stop_price=100.00)
>>> self.submit_orders([order1, order2])
>>> # For 2 stop limit orders
>>> order1 = self.create_order("SPY", 100, "sell", limit_price=100.00, stop_price=100.00)
>>> order2 = self.create_order("TLT", 200, "sell", limit_price=100.00, stop_price=100.00)
>>> self.submit_orders([order1, order2])
>>> # For 2 FOREX buy orders
>>> from lumibot.entities import Asset
>>>
>>> base_asset = Asset(
    symbol="EUR",
    asset_type=Asset.AssetType.FOREX,
)
>>> quote_asset = Asset(
    symbol="USD",
    asset_type=Asset.AssetType.FOREX,
)
>>> order1 = self.create_order(base_asset, 100, "buy", quote=quote_asset)
>>> order2 = self.create_order(base_asset, 200, "buy", quote=quote_asset)
>>> self.submit_orders([order1, order2])
>>> # For 2 FOREX sell orders
>>> from lumibot.entities import Asset
>>>
>>> base_asset = Asset(
    symbol="EUR",
    asset_type=Asset.AssetType.FOREX,
)
>>> quote_asset = Asset(
    symbol="USD",
    asset_type=Asset.AssetType.FOREX,
)
>>> order1 = self.create_order(base_asset, 100, "sell", quote=quote_asset)
>>> order2 = self.create_order(base_asset, 200, "sell", quote=quote_asset)
>>> self.submit_orders([order1, order2])
>>> # For 2 CRYPTO buy orders.
>>> from lumibot.entities import Asset
>>>
>>> asset_BTC = Asset(
>>>    "BTC",
>>>    asset_type=Asset.AssetType.CRYPTO,
>>> )
>>> asset_ETH = Asset(
>>>    "ETH",
>>>    asset_type=Asset.AssetType.CRYPTO,
>>> )
>>> asset_quote = Asset(
>>>    "USD",
>>>    asset_type=Aset.AssetType.FOREX,
>>> )
>>> order1 = self.create_order(asset_BTC, 0.1, "buy", quote=asset_quote)
>>> order2 = self.create_order(asset_ETH, 10, "buy", quote=asset_quote)
>>> self.submit_order([order1, order2])
>>> or...
>>> order1 = self.create_order((asset_BTC, asset_quote), 0.1, "buy")
>>> order2 = self.create_order((asset_ETH, asset_quote), 10, "buy")
>>> self.submit_order([order1, order2])
property timezone#

Returns the timezone of the data source. By default, America/New_York.

Returns:

The timezone of the data source.

Return type:

str

Example

>>> # Will return the timezone of the data source
>>> timezone = self.timezone
>>> self.log_message(f"Timezone: {timezone}")
to_default_timezone(dt: datetime)#

Returns a datetime localized to the data source’s default timezone.

Parameters:

dt (datetime.datetime) – The datetime to localize.

Returns:

The localized datetime.

Return type:

datetime.datetime

Example

>>> # Will return a datetime localized to the data source's default timezone
>>> to_default_timezone = self.to_default_timezone(dt=datetime.datetime(2020, 1, 1))
>>> self.log_message(f"Localized datetime: {to_default_timezone}")
to_sql(stats_df, stats_table_name, connection_string, if_exists, index)#
trace_stats(context, snapshot_before)#

Lifecycle method that will be executed after on_trading_iteration. context is a dictionary containing on_trading_iteration locals() in last call. Use this method to dump stats

Parameters:
  • context (dict) – Dictionary containing locals() from current call to on_trading_iteration method.

  • snapshot_before (dict) – Dictionary containing locals() from last call to on_trading_iteration method.

Returns:

Dictionary containing the stats to be logged.

Return type:

dict

Example

>>> def trace_stats(self, context, snapshot_before):
>>>     self.log_message("Trace stats")
>>>     self.log_message(f"Context: {context}")
>>>     self.log_message(f"Snapshot before: {snapshot_before}")
>>>     return {
>>>         "my_stat": context["my_stat"],
>>>         "my_other_stat": context["my_other_stat"],
>>>         "portfolio_value": self.portfolio_value,
>>>         "cash": self.cash,
>>>     }
property unspent_money#

Deprecated, will be removed in the future. Please use self.cash instead.

update_parameters(parameters)#

Update the parameters of the strategy.

Parameters:

parameters (dict) – The parameters to update.

Return type:

None

wait_for_order_execution(order)#

Wait for one specific order to be executed or canceled by the broker

Parameters:

order (Order object) – Order object to be executed by the broker.

Return type:

Order object

Example

>>> # For a market buy order
>>> order = self.create_order("SPY", 100, "buy")
>>> self.submit_order(order)
>>> self.wait_for_order_execution(order)
wait_for_order_registration(order)#

Wait for the order to be registered by the broker

Parameters:

order (Order object) – Order object to be registered by the broker.

Return type:

Order object

Example

>>> # For a market buy order
>>> order = self.create_order("SPY", 100, "buy")
>>> self.submit_order(order)
>>> self.wait_for_order_registration(order)
>>> # For a limit buy order
>>> order = self.create_order("SPY", 100, "buy", limit_price=100.00)
>>> self.submit_order(order)
>>> self.wait_for_order_registration(order)
wait_for_orders_execution(orders)#

Wait for a list of orders to be executed or canceled by the broker

Parameters:

orders (list of orders) – List of order objects to be executed by the broker.

Return type:

list of orders

Example

>>> # For 2 market buy orders
>>> order1 = self.create_order("SPY", 100, "buy")
>>> order2 = self.create_order("TLT", 200, "buy")
>>> self.submit_orders([order1, order2])
>>> self.wait_for_orders_execution([order1, order2])
wait_for_orders_registration(orders)#

Wait for the orders to be registered by the broker

Parameters:

orders (list of orders) – List of order objects to be registered by the broker.

Return type:

list of orders

Example

>>> # For 2 market buy orders
>>> order1 = self.create_order("SPY", 100, "buy")
>>> order2 = self.create_order("TLT", 200, "buy")
>>> self.submit_orders([order1, order2])
>>> self.wait_for_orders_registration([order1, order2])
write_backtest_settings(settings_file)#

Redefined in the Strategy class to that it has access to all the needed variables.