Placing Orders and Other API Functions

Note

Most API functions in Blueshift are implemented as methods of the main algorithm class TradingAlgorithm. In the documentation below, if you see a function is documented as TradingAlgorithm.funcname, then the API function funcname can be usually imported in the strategy code from blueshift.api module (as from blueshift.api import funcname) and can be used as regular function. A reference to the current running algorithm is automatically inserted.

Assets Fetching APIs

Blueshift treats securities as asset objects of various kinds. To refer to a tradable security you must use an asset object. The API function symbol converts a security symbol to an asset object.

TradingAlgorithm.symbol(symbol_str: str, dt=None, *args, **kwargs)

API function to resolve a symbol string to an asset. See symbology for more details.

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

  • dt (timestamp) – Optional datetime argument.

Returns:

the asset object.

Raises:

SymbolNotFound exception if no matching asset found.

TradingAlgorithm.symbols(symbols, dt=None, *args, **kwargs)

API function to resolve a list of symbols to assets.

Parameters:

symbols (list) – The list of symbols.

Returns:

A list of asset objects.

Raises:

SymbolNotFound exception if no matching asset found.

TradingAlgorithm.get_dated_asset(asset)

API function to fetch dated asset for a rolling asset.

Parameters:

asset (asset object.) – asset to convert to corresponding dated asset.

TradingAlgorithm.get_asset_for_order(asset, product_type=None)

Method to retrieve the asset for an order created from a given asset and product_type. Usually they will be the same, but maybe different if input asset is a rolling asset (in which case the equivalent dated asset will be returned), or the underlying broker has a default product type.

Note

the asset as it appears in the order attribute will always be dated, even if the order was created using a rolling asset definition.

Parameters:

order – An asset object

Returns:

The matching asset object.

TradingAlgorithm.get_asset_from_order(order)

Method to retrieve the asset for a position created from a given order. Usually they will be the same, but maybe different if order was created using a rolling asset and the underlying broker implementation tracks positions in terms of rolling assets.

Note

the asset as it appears in the order attribute will always be dated, even if the order was created using a rolling asset definition.

Parameters:

order – An order object

Returns:

The matching asset object.

For more on assets, see assets. For more on how to use symbols to refer to available instruments, see asset symbology.

Important

The symbol function will resolve a ticker name or asset symbol to an asset object representation applicable for the time at which the method was called. For example, symbol(“ABC-W0CE+0”) will refer to the first the current weekly ATM call for underlying ABC at the time when the method were called. Calling the same method later can refer to a different instruments (e.g. when the underlying has moved and the ATM strike is now at a different level than earlier). See How to fetch assets in strategy code for more.

Important

Blueshift supports multiple assets and product types as well as rolling asset symbology. As a result, the asset used for placing and order, the asset attribute of the same order, and the asset attribute of the position resulting from that order - all may be different assets. For example, specifying a regular Equity asset while placing the order, along with product_type as margin will create an order with EquityMargin asset. Specifying a rolling option asset will create an order and a position with the dated version of the option asset. In most cases, the user strategy code will not be required to track and distinguish among these. But in cases of complex algos, it maybe necessary. For this purpose, use the API function get_asset_for_order to convert an asset to the asset that and order will generate from it. Also uses get_asset_from_order to check the asset of the position generated from an order with the given asset. See Miscellaneous API functions for more.

Trading API functions

Warning

While Blueshift supports running multiple strategies under a single account, this may lead to erroneous results. We recommend running a single algo on a broker account in live or paper trading.

Order Placing APIs

Attention

All ordering APIs can only be used during active trading hours. Else they will raise exceptions. Also, do not use the undocumented parameters in the below APIs. They are meant for internal use.

Note

Blueshift now supports fractional trading, i.e. order quantity need not be an integer and fractional amount is supported (if supported by the broker). Some brokers (e.g. Crypto brokers) offer exclusively fractional trading. For such cases, Blueshift will automatically treat every order as fractional. For brokers which do not exclusively offer fractional trading (e.g. Equity brokers), you must specify a keyword argument fractional=True in the ordering API functions to make it fractional.

Place Order

The base ordering function on Blueshift is order.

TradingAlgorithm.order(asset, quantity=None, limit_price=0, stop_price=0, bypass_control=False, style=None, **kwargs)

Place a new order. This is the interface to the underlying broker for ALL order related API functions. The first argument can be an execution algo object (an instance of a subclass of IAlgoOrder). In this case, any other arguments will be ignored.

The handling of limit and stop price specification is totally implementation dependent. In case the broker supports limit orders, limit_price will be effective.

Note

You can pass an AlgoOrder object to trade execution algorithm. See Execution Algorithms.

Important

  • Orders can be placed during active trading hours only. This means only handle_data or scheduled callback functions, or appropriate trade or data callback functions are eligible to place orders.

  • Order with zero implied quantity (e.g. order size less than lot-size) will silently fail. No order will be sent to the broker.

  • At present only limit and market orders are supported. Stop loss specification will be ignored.

  • For order using rolling assets, see the caveats here.

  • For intraday products, order placement will be refused if the broker follows an intraday cut-off time ( usually 15 mins from the end of trading day).

  • Always check if the return value is None or a valid order id. For some live brokers, successful orders that result in an existing position unwind may return a None value. Also a rejected order or an order that failed validation checks may return a None value (e.g. order with 0 quantity).

  • If running in oneclick execution mode, the returned notification ID can be exchanged to an order ID using the API function get_order_by_notification_id. This will return None if the notification is cancelled or not yet confirmed by the user or is expired. Will return an order ID if the user confirmed the order.

  • The asset supplied to the order function may not be the same asset in the order object. Use get_asset_for_order to determine what the asset in the order object will be.

  • The asset supplied to the order function, or the asset in the order object may not be the same as the asset in the position resulting from the order execution. Refer to the get_asset_from_order API function for this.

Parameters:
  • asset (asset object.) – asset on which the order to be placed (or and AlgoOrder).

  • quantity (int) – units to order (> 0 is buy, < 0 is sale).

  • limit_price (float) – limit price for limit order

  • stop_price (float) – Stop-loss price (currently ignored).

  • kwargs – Extra keyword parameters passed on to the broker.

Returns:

order ID. This can be either an order ID, or a notification ID (when running in oneclicl execution mode), or None (in case the order did not generate any actual orders to be sent to the broker, e.g. order with 0 quantity).

Return type:

str or None.

Recognized keyword arguments are validity and product_type. If specified, they must be of type OrderValidity and ProductType respectively (names are also accepted, instead of enums).

Danger

No ordering function will check the capacity of the account to validate the order (e.g. cash, margin requirements etc.). You must check before placing any order.

Attention

All orders are subjected to the RMS implemented by the broker interface. The RMS can modify any incoming orders based on its requirements, and these modified orders will be sent to the actual broker.

Automatic Order Sizing

Apart from this there is a host of automatic order-sizing functions that allows one to place orders based on order value or by specifying the fraction of current portfolio value as order value.

TradingAlgorithm.order_value(asset, value, limit_price=0, stop_price=0, bypass_control=False, style=None, **kwargs)

Place a new order sized to achieve a certain dollar value, given the current price of the asset.

Parameters:
  • asset (asset object.) – asset on which the order to be placed.

  • value (float) – dollar value (> 0 is buy, < 0 is sale).

  • limit_price (float) – limit price for limit order

  • stop_price (float) – Stop-loss price (currently ignored).

  • kwargs – Extra keyword parameters passed on to the broker.

Returns:

order ID.

Return type:

str or None.

Danger

This will take into account the current price of the asset, not actual execution price. The total value of execution can exceed the specified target value.

TradingAlgorithm.order_percent(asset, percent, limit_price=0, stop_price=0, bypass_control=False, style=None, **kwargs)

Place a new order sized to achieve a certain percentage of the algo net equity, given the current price of the asset. This method applies a haircut of 2% on the current portfolio value for computing the order value, in case of market order.

Parameters:
  • asset (asset object.) – asset on which the order to be placed.

  • percent (float) – fraction of portfolio value (> 0 is buy, < 0 is sale).

  • limit_price (float) – limit price for limit order

  • stop_price (float) – Stop-loss price (currently ignored).

  • kwargs – Extra keyword parameters passed on to the broker.

Returns:

order ID.

Return type:

str or None.

Danger

This will take in to account current price of the asset and current algo net equity, not actual execution price. The total value of execution can exceed the specified percent.

Targeting Orders

In addition, Blueshift supports targeting order, which takes in a unit, a order value or a portfolio fraction as a target and tries to place order to achieve this target. These functions are idempotent and are recommended way to place orders from an algo.

TradingAlgorithm.order_target(asset, target, limit_price=0, stop_price=0, bypass_control=False, style=None, **kwargs)

Place a new order sized to achieve a position of a certain quantity of the asset, taking into account the current positions and outstanding open orders (including one-click orders that require user confirmation).

Parameters:
  • asset (asset object.) – asset on which the order to be placed.

  • target (int) – units to target (> 0 is buy, < 0 is sale).

  • limit_price (float) – limit price for limit order

  • stop_price (float) – Stop-loss price (currently ignored).

  • kwargs – Extra keyword parameters passed on to the broker.

Returns:

order ID.

Return type:

str or None.

Important

If the current position in the asset is X, and a target order is placed for Y units, and there is no outstanding open order for the asset, this will place an order for Y-X units. If X>Y, this means a sell order, if X < Y, a buy order. If X is exactly equal to Y, no actions are taken. If there are outstanding open orders, that is added to X before calculating the difference. In case of a significant delay in order update from the broker, this can compute wrong incremental units.

Targetting order will NOT work for rolling option assets (as the strike may change with the underlying for a given strike offset over time) and an error will be raised.

TradingAlgorithm.order_target_percent(asset, percent, limit_price=0, stop_price=0, bypass_control=False, style=None, **kwargs)

Place a new order sized to achieve a position of a certain percent of the net account value. This method applies a haircut of 2% on the current portfolio value for computing the order value, in case of market order.

Parameters:
  • asset (asset object.) – asset on which the order to be placed.

  • percent (float) – fraction of portfolio value to target (> 0 is buy, < 0 is sale).

  • limit_price (float) – limit price for limit order

  • stop_price (float) – Stop-loss price (currently ignored).

  • kwargs – Extra keyword parameters passed on to the broker.

Returns:

order ID.

Return type:

str or None.

TradingAlgorithm.order_target_value(asset, target, limit_price=0, stop_price=0, bypass_control=False, style=None, **kwargs)

Place a new order sized to achieve a position of a certain value of the asset, taking into account the current positions and outstanding open orders (including one-click orders that require user confirmation).

Parameters:
  • asset (asset object.) – asset on which the order to be placed.

  • target (float) – value to target (> 0 is buy, < 0 is sale).

  • limit_price (float) – limit price for limit order

  • stop_price (float) – Stop-loss price (currently ignored).

  • kwargs – Extra keyword parameters passed on to the broker.

Returns:

order ID.

Return type:

str or None.

Important

This order method computes the required unit from the target and the current market price, and does not guarantee the execution price or the value after execution.

Danger

It is highly recommended to use targeting order functions above than the basic ordering function. Basic order function, if not used correctly, may lead to sending inadvertent orders or too many orders. However, attempt to place target order will raise error for rolling option assets, as the actual strike (and hence the actual asset) may change with the underlying movement for a given strike offset.

Oneclick Trading

Blueshift can run in oneclick execution mode where each order is sent to the broker for execution only after explicit user confirmation. The potential orders generated by the algo is termed as notifications, which are sent to the front end for user actions. Each notification has an expiry (which can be set by the strategy). If the user confirms a notification within the expiry time, the corresponding order is sent to the broker. Else the notification is discarded. Strategies that intend to support this mode, may find the following API functions useful.

TradingAlgorithm.set_oneclick_timeout(timeout=None)

Overwrite the default notification timeout when running in one-click execution mode.

Parameters:

timeout (int) – The timeout (in minutes) for notification expiry.

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo.

TradingAlgorithm.get_open_notifications(algo=True)

Get a dictionary of all open notifications, keyed by their id. The return value is a dict object with notification IDs (str) as keys and order objects as values. Applicable only when running in oneclick order confirmation mode. If algo is True, notifications in the current context is returned, else all notifications in the running contexts (i.e. the main context and any sub strategy context, if added) of the current algo is returned.

Parameters:

algo (bool) – Whether to search the current context or all contexts.

Returns:

A dictionary of open notifications (yet to be confirmed or expire).

Return type:

dict

TradingAlgorithm.get_order_by_notification_id(notification_id)

Function to retrieve an order by notification id. This is only valid if the algo is running in oneclick execution mode. Notification ID is the ID returned on successful order placement in oneclick mode.

Note

If the notification did not result in an actual order ( e.g. expired, or cancelled notification), it will return None.

Parameters:

notification_id (str) – A valid notification id to retrieve.

Returns:

The matching order object.

TradingAlgorithm.get_oneclick_status(notification_id, algo=True)

Function to retrieve the status of by notification id. This is only valid if the algo is running in oneclick execution mode. Notification ID is the ID returned on successful order placement in oneclick mode. If algo is True, the current context is searched, else all the running contexts (i.e. the main context and any sub strategy context, if added) of the current algo are searched for a match.

Parameters:
  • notification_id (str) – A valid notification id to retrieve.

  • algo (bool) – Whether to search the current context or all contexts.

Returns:

The state.

TradingAlgorithm.get_oneclick_order(notification_id, algo=True)

Function to retrieve the notification order object. This may be the initial order object created (with an app generated order ID), or an actual order that has been sent to the broker ( with the actual order ID). Returns None if not found. If algo is True, order in the current context is returned, else all the running contexts (i.e. the main context and any sub strategy context, if added) of the current algo are searched for a match.

Parameters:
  • notification_id (str) – A valid notification id to retrieve.

  • algo (bool) – Whether to search the current context or all contexts.

Returns:

The order object matching the id.

Attention

Ordering functions, while running in oneclick mode, will not return an order ID on success, but a notification ID instead.

Advanced Algo Orders

See Execution Algorithms.

Order management APIs

Attention

All order management APIs can only be used during active trading hours. Else they will raise exceptions. Also, do not use the undocumented parameters in the below APIs. They are meant for internal use only.

Update Order

TradingAlgorithm.update_order(order_param, *args, **kwargs)

Function to update an existing open order. The parameter order_param can be either an Order object or an order ID. Use limit_price keyword for updating the price of a limit order. Other keyword support is implementation dependent.

Important

This API will try to modify an existing order, but will fail if the order is already executed.

Parameters:

order_param – An order object, or a valid order ID to modify.

Cancel Order

TradingAlgorithm.cancel_order(order_param, *args, **kwargs)

Function to cancel an open order not filled yet (or partially filled).

Parameters:

order_param – An order object, or a valid order ID to cancel.

Danger

This function only initiates a cancel request. It does not and cannot ensure actual cancellation.

Fetch Open Orders

TradingAlgorithm.get_open_orders(algo=True)

Get a dictionary of all open orders, keyed by their id. The return value is a dict object with order IDs (str) as keys and order objects as values. If algo is True, orders in the current context is returned, else all orders running in the context (i.e. the main context and any sub strategy context, if added) of the current algo is returned.

Note

Order asset will be dated asset. To fetch orders by rolling asset (applicable only for futures in backtest), use context.get_open_orders_by_asset instead.

Parameters:

algo (bool) – Whether to search the current context or all contexts.

Returns:

A dictionary of open orders.

Return type:

dict

Fetch Open Positions

TradingAlgorithm.get_open_positions(algo=True)

Get all open positions. The return value is a dict, keyed by assets and positions as values. If algo is True, only the open positions in the current context is returned. Else all open positions in all contexts (the main and any sub strategy contexts, if added), are returned.

Parameters:

algo (bool) – Whether to search the current context or all contexts.

Returns:

A dictionary of open orders.

Return type:

dict

Get Order by Order ID

TradingAlgorithm.get_order(order_id, algo=True)

Function to retrieve an order by order id. If algo is True, only the current context (the main or any sub strategy context), from where the method is called, is used. Otherwise, the order_id is searched across all contexts.

Parameters:
  • order_id (str) – A valid order id to retrieve.

  • algo (bool) – Whether to search the current context or all contexts.

Returns:

The matching order object.

Important

Up to what history orders can be retrieved depends on broker implementation. Usually for most cases, only the closed orders placed in the current session (day), plus all open orders are available.

Check If Tradable

TradingAlgorithm.can_trade(assets)

Function to check if asset can be traded at current dt. This requires the asset to be alive as well as we should be within trading hours.

Parameters:

assets (list) – List of assets to check

Returns:

True if all assets in the list can be traded, else False.

Return type:

bool

TradingAlgorithm.is_alive(assets)

Function to check if asset is alive (not expired or expelled otherwise).

Parameters:

assets (list) – List of assets to check

Returns:

True if all assets in the list can be traded, else False.

Return type:

bool

Square Off Position

TradingAlgorithm.square_off(assets=None, algo=False, ioc=False, remark=None)

Function to square off open positions and cancel open orders. Typically useful for end-of-day closure for intraday strategies or for risk management.

If algo is True, only the positions held in the current active context will be squared off. The cool-off enforced after such a square-off will be only enforced in that context.

If algo is False, then all positions across contexts will be squared off, and a global cool-off will be set, that will prevent all contexts (the main strategy as well as any other sub-strategies added) to enter a new trade till the cool-off period is elapsed.

if ioc is True, the orders sent for square-off will be IOC. A total 3 attempts will be made to square-off an asset in this case before giving up.

If assets is None, all existing open orders will be cancelled, and then all existing positions will be squared off. If assets is a list or a single asset, only those positions and orders will be affected.

Note

Square off order for each asset will be sent in sequence. For global square-off (algo=False), orders for each context will be sent in sequence and may lead to offsetting orders in case contexts (main and sub-strategies) have offsetting positions.

Important

A square-off will initiate an exit cool-off period till the next clock tick during which no exits in the asset is permitted - to safeguard against multiple square-off attempts. It will also trigger an entry cooloff that will remain in forced for a period defined by set_cooloff_period (defaults to 30 minutes).

Important

This API will bypass any trading controls to make sure square-off orders are not blocked by such controls. Orders will be sent to the broker directly, even in one-click execution mode. Also, see above the behaviour differences between the cases where the underlying broker does or does not support a native square-off method.

Parameters:
  • assets (list) – A list of assets, or a single asset or None

  • algo (bool) – If we should consider algo or broker positions

  • ioc (bool) – If we should use IOC order instead of DAY validity.

Danger

This function only initiates square off. It does not and cannot ensure actual square-off. Also, in case we attempt to squareoff during a cool-off period, it will be ignored (to prevent multiple squareoff attempts which may lead to unintended positions), but will attempt to cancel any open orders. Using squaring off function repeatedly may lead to cancelling of exit orders triggered by a previous call.

Stoploss and Take-profit

Stoploss and takeprofits are exit conditions that are checked at least once at every clock cycle (i.e. 1 minute usually). In live trading where the broker supports streaming data, checks will also be attempted at every data update (tick). An exit via these methods can be either a strategy level exit - where all existing positions are squared off, or position level exit - where only the position in a particular asset (for which the exit was setup) is squared off (if not skipped, see below). Setting up exits usually accept an exit method, a target and optionally a trailing factor.

Danger

The target values should always be positive - for a stoploss, it is interpreted as loss and for takeprofit, as profit. Also trailing factor should ideally be a fraction between 0 to 1. Other values, while not illegal, may result in unexpected outcome.

Strategy Stoploss and Take-profit Exit Method

ExitMethod specifies how exits (i.e. stoploss or takeprofit exits) are handled. For strategy level exits (i.e. when None is passed as asset during setting up of a stoploss or takeprofit), the methods below work as follows:

  • PRICE

    This method is NOT defined for strategy level exits.

  • MOVE

    For strategy level exits, this method tracks the change in the net account value (equivalent to change in total profit and loss) and triggers exit if the target is breached. If trailing, then for each favourable move (current value > last recorded), the entry net account value and target are updated, and the change is calculated using these updated values in the next check. The update formalue is trigger = (last value - last target) + (current value-last value)*trailing factor. and then target = current value - trigger, where value is the account net value. If trailing is off, the change is always calculated from the net account value recorded at the time of the exit method was set up (by either set_stoploss or set_takeprofit) and the target remains the same throughout.

  • PERCENT

    For strategy level exits, this method tracks the percent change in the net account value and triggers exit if the target is breached. Note: this is not the same as total PnL anymore, unlike in case of MOVE. If trailing, then for each favourable change (current value > last recorded), the entry net account value and the target are updated, and the percent change is calculated using these updated values in the next check. The updation formula is trigger = last value*(1-last target) + (current value-last value)*trailing factor and then target = 1-trigger/current net. If trailing is off, the change is always calculated from the net account value recorded at the time of the exit method was set up (by either set_stoploss or set_takeprofit) and the target remains the same throughout.

  • AMOUNT

    For strategy level exits, this method tracks the strategy level unrealized pnls (i.e. mtm, or, sum of unrealized pnls for all open positions) and triggers exit if the target is breached. If trailing is on, the target is updated for each favourable change as target = last target - (current mtm - last mtm)*trailing factor. If trailing is off, the target remains the same. Exit is triggered if the current unrealized pnls breaches the target.

  • PNL

    For strategy level exits, this method tracks the strategy level total pnls (realized + unrealized). If trailing is on, the exit target is updated for each favourable pnls changes as target = target - (current pnls - last pnls)*trailing factor. If trailing is off, the target remains the same. Exit is triggered if the current total pnls breaches the target.

Position Stoploss and Take-profit Exit Method

For position (asset) level exits (i.e. when an asset is passed during setting up of a stoploss or takeprofit), the methods work as follows:

  • PRICE

    For position level exits, this method will monitor the price of the asset in the position being tracked and will trigger an exit if the target is breached - depending on type (stoploss or takeprofit) and side (long or short) of the position. For e.g. for a stoploss on a long position, the current price must fall below the target. In case of trailing stoploss, for each favourable move (i.e. the current price is greater than target for a long position and the current price move higher than the last check), the target is updated as: target = last target + (current price -last price)*trailing factor for a long position (similar for short). If trailing is off, the target remains same throughout.

  • MOVE

    For position level exits, this method will monitor the change in the price of the asset in the positions being tracked and will trigger an exit if the target is breached - depending on type (stoploss or takeprofit) and side (long or short) of the position. For e.g. for a long position and stoploss, a negative price change must be greater than the target move in magnitude to trigger exit. In case of trailing stoploss, for each favourable move (a price higher than last), the target is updated as: trigger = (last price - last target) + (current price -last price)*trailing factor and then target = current price - trigger for a long position ( similar for short). This remains same as the initial target if the trailing factor is 1.0. For each favourable move, the entry recorded is also updated to the current price. Exit is triggered if the change in price from recorded entry breaches the target. If trailing is off, the target remains same throughout and change is calculated from the average entry price into that position.

    Warning

    For multiple entry and exit into a position (without completely exiting it), the reference price is the average entry price which is impacted by all entries and exits into that position.

  • PERCENT

    For position level exits, this method will monitor the percent change in the price of the asset in the positions being tracked and will trigger an exit if the target is breached - depending on type (stoploss or takeprofit) and side (long or short) of the position. For e.g. for a long position and stoploss, the current percent change must be negative and higher than the target percent in magnitude. In case of trailing stoploss, for each favourable move the target is updated as: trigger = last price*(1-last target) + (current price-last price)*trailing factor, and then target = 1-trigger/current price. At the same time, the last recorded price is updated as well and percentage change in calculated from this recorded value in the next check. If trailing is off, the target remains same throughout and percentage change is calculated from the average entry price in that position.

    Warning

    For multiple entry and exit into a position (without completely exiting it), the reference price is the average entry price which is impacted by all entries and exits into that position.

  • AMOUNT

    For position level exits, this method will monitor the unrealized pnls (mtm) in the position and will trigger exit if it breaches the target. If the trailing is on, for each favourable move, the target is updated as target = last target - change in unrealized pnl*trailing factor. At the same time, reference unrealized pnl is updated as well. If trailing is off, the target remains same throughout and the reference unrealized pnl remains the value at the time of entry (0 for a new position). Exit triggers if the change in unrealized loss (from the reference value) breaches the target.

  • PNL

    For position level exits, this is same as the AMOUNT method.

class blueshift.protocol.ExitMethod(value)

An enumeration.

PRICE = 0
MOVE = 1
PERCENT = 2
AMOUNT = 3
PNL = 4

Add or Remove Stoploss

TradingAlgorithm.set_stoploss(asset, method, target, trailing=False, on_stoploss=None, skip_exit=False, entry=None, rolling=False)

Set the stoploss for a position, defined for an asset or at the strategy level. Method can be one of PRICE, MOVE, PERCENT, AMOUNT or PNL.

If asset is passed as None, the stoploss applies to the current strategy context. If an asset is supplied, only the asset position is monitored. If trailing is non-zero, stoploss is updated at each lookup. Stoplosses are defined on the position for an asset, and NOT for an order. You can have multiple orders placed on the same asset, and set the stoploss just once.

If a strategy has both strategy-level and asset level stoploss, the strategy level stoploss is checked first. If hit, all asset level stoplosses and takeprofits wil be reset (unless skip_exit is True). This is done to avoid calling square-off multiple times.

if entry is specified, it must be a number, and that is taken as a basis computation where applicable (e.g. MOVE, PERCENT or trailing stoploss etc.)

Stoploss will be reset each day in before trading start routine (for both strategy-level and asset-level stoplosses).

You can pass an order object instead of asset. This is useful when using rolling option asset - which may result in a different asset in positions than the asset used to place the order. It is recommended to use an order object when using rolling assets.

Once the target is hit, if skip_exit is False, the position will be squared off and the callable on_stoploss, if provided, will be called. If skip_exit is True, only the callable will be invoked and no position exit will take place. The callable must have a signature of f(context, asset), where asset is the asset for which the trigger has been hit. The asset argument will be None for a strategy level stoploss. The callable is invoked AFTER the required square-off is triggered (if skip_exit is True).

Parameters:
  • asset (asset object.) – The asset for the stoploss check (or None).

  • method (str) – The method for the stoploss check.

  • target (float) – The stoploss target.

  • trailing (float) – Trailing stoploss.

  • on_stoploss (callable) – A callable invoked if target is hit.

  • skip_exit (bool) – If true, no exit order will be triggered.

  • entry (float) – Optional entry level.

  • rolling (bool) – Should the stoploss be rolled to next day.

Warning

stoplosses are valid only for the day. Each day in before trading start, stoplosses are reset unless rolling is set to True. Note: setting rolling to True will only work in backtest mode as no stoploss details will be saved. In live mode, no stoploss information is restored after a restart. You will need to explicitly retore any takeprofits after a restart (e.g. in the before_trading_start). Also, once a stoploss target is hit, (with or without skip_exit),the entry is automatically removed and no subsequent trigger will occur. If the asset has both a stoploss and a takeprofit target, a trigger in any will cancel (i.e. remove) both of them.

Important

If you are using a rolling option assets in your strategy, use the order object to set the stoploss, instead of the asset itself.

Important

If you are placing the entry order with a stoploss specified (if supported), do not use this function. The stoploss in the order, if supported by the broker, will automatically enable stoploss exit. This function will try to square off the position if the stoploss is hit by placing a market order. Also, after an exit, this will cause a cool-off period for that asset which will prevent further entry trade till it resets. Cool off period can be set using the set_cooloff_period api function. Also a stoploss, once set, will be valid till it is cancelled using remove_stoploss api method, or removed by a trigger (either by a stoploss or takeprofit being hit on the asset). Also note, this function can only initiate the exit orders and cannot ensure actual executions of those orders.

Note

If skip_exit is False, the function will initiate exit. These exit orders (if any) will bypass any trading controls to make sure square-off orders are not blocked by such controls. Orders will be sent to the broker directly, even in one-click execution mode.

TradingAlgorithm.get_current_stoploss(asset)

Return the currently defined stoploss for the strategy, or asset, if any. Returns a tuple of None’s if not found. Set asset to None for the stoploss set at the strategy level in the current context.

You can pass an order object instead of asset. This is useful when using rolling option asset - which may result in a different asset in positions than the asset used to place the order. It is recommended to use an order object when using rolling assets.

Parameters:

asset (asset object.) – The asset for the stoploss check.

Returns:

Tuple of (ExitMethod, target, price at entry)

Return type:

tuple

TradingAlgorithm.remove_stoploss(asset)

Remove stoploss for the strategy context or for an asset. Set asset to None for strategy-level stoloss. You can pass an order object instead of asset as well. This is useful when using rolling option asset - which may result in a different asset in positions than the asset used to place the order. It is recommended to use an order object when using rolling assets.

Parameters:

asset (asset object.) – The asset for the stoploss check.

Add or Remove Take-profit Target

TradingAlgorithm.set_takeprofit(asset, method, target, on_takeprofit=None, skip_exit=False, entry=None, rolling=False)

Set the take-profit for a position, defined for an asset or at the strategy level. Method can be one of PRICE, MOVE, PERCENT, AMOUNT or PNL.

If asset is passed as None, the takeprofit applies to the current strategy context. If an asset is supplied, only the asset position is monitored. Take-profit will be reset each day in before trading start routine.

You can pass an order object instead of asset. This is useful when using rolling option asset - which may result in a different asset in positions than the asset used to place the order. It is recommended to use an order object when using rolling assets.

If a strategy has both strategy-level and asset level takeprofit, the strategy level takeprofit is checked first. If hit, all asset level stoplosses and takeprofits wil be reset (unless skip_exit is True). This is done to avoid calling square-off multiple times.

if entry is specified, it must be a number, and that is taken as a basis computation where applicable (e.g. MOVE, PERCENT etc.)

Once the target is hit, if skip_exit is False, the position will be squared off and the callable on_takeprofit, if provided, will be called. If skip_exit is True, only the callable will be invoked and no position exit will take place. The callable must have a signature of f(context, asset), where asset is the asset for which the trigger has been hit. The asset argument will be None for a strategy level takeprofit. The callable is invoked AFTER the required square-off is triggered (if skip_exit is True).

Parameters:
  • asset (asset object.) – The asset for the stoploss check.

  • method (str) – The method for the stoploss check.

  • target (float) – The stoploss target.

  • on_takeprofit (callable) – A callable invoked if target is hit.

  • skip_exit (bool) – If true, no exit order will be triggered.

  • entry (float) – Optional entry level.

  • rolling (bool) – Should the takeproft be rolled to next day.

Warning

take-profits are valid only for the day. Each day in before trading start, take-profits are reset unless rolling is set to True. Note: setting rolling to True will only work in backtest mode as no takeprofit details will be saved. In live mode, no takeprofit information is restored after a restart. You will need to explicitly retore any takeprofits after a restart (e.g. in the before_trading_start). Also, once a take-profit target is hit, (with or without skip_exit), the entry is automatically removed and no subsequent trigger will occur. If the asset has both a stoploss anda takeprofit target, a trigger in any will cancel (i.e. remove) both of them.

Important

If you are using a rolling option assets in your strategy, use the order object to set the stoploss, instead of the asset itself.

Important

If you are placing the entry order with a takeprofit specified, do not use this function. The takeprofit in the order, if supported by the broker, will automatically enable takeprofit exit. Also a takeprofit, once set, will be valid till it is cancelled using remove_takeprofit api method, or removed by a trigger (either by a stoploss or takeprofit being hit on the asset). Also note, this function can only initiate the exit orders and cannot ensure actual executions of those orders.

Note

If skip_exit is False, the function will initiate exit. These exit orders (if any) will bypass any trading controls to make sure square-off orders are not blocked by such controls. Orders will be sent to the broker directly, even in one-click execution mode.

TradingAlgorithm.get_current_takeprofit(asset)

Return the currently defined take-profit for the strategy, or asset, if any. Returns a tuple of None’s if not found. Set asset to None for the stoploss set at the strategy level in the current context.

You can pass an order object instead of asset. This is useful when using rolling option asset - which may result in a different asset in positions than the asset used to place the order. It is recommended to use an order object when using rolling assets.

Parameters:

asset (asset object.) – The asset for the takeprofit check.

Returns:

Tuple of (ExitMethod, target, price at entry)

Return type:

tuple

TradingAlgorithm.remove_takeprofit(asset)

Remove take-profit for the strategy context or for an asset. Set asset to None for strategy-level stoloss. You can pass an order object instead of asset as well. This is useful when using rolling option asset - which may result in a different asset in positions than the asset used to place the order. It is recommended to use an order object when using rolling assets.

Parameters:

asset (asset object.) – The asset for the stoploss check.

Important

Always place stoploss or take-profit orders using assets from the strategy positions, and not using the assets used to place the orders. This is because for special cases ( rolling assets or margin products etc.) the order asset can be different than the asset in the resulting position.

Risk Management APIs

Attention

These set of API functions (apart from terminate) can only be called within initialize function.

A set of API functions to control trade risk and implements various limits.

TradingAlgorithm.set_exit_policy(cancel_orders=True, square_off=False)

Set the exit policy for this strategy. If cancel_orders is True and square_off is False, only the open order cancellation is attempted. If square_off is True, all open orders are cancelled and positions are squared off.

Parameters:
  • cancel_orders (bool) – Cancel all open order on exit.

  • square_off (bool) – Square off all positions on exit.

Important

The exit policy is triggered only during a graceful exit of the algo. Unexpected fatal errors or a crash or an explicit kill may not trigger the exit policy.

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo.

Danger

This function only initiates square off and/or order cancellation. It does not and cannot ensure actual square-off or cancellation. Also, in case we attempt to squareoff during a cool-off period, it will be ignored (to prevent multiple squareoff attempts which may lead to unintended positions), but will attempt to cancel any open orders. If the order cancellation or square-off takes too much time to get executed, the algo may exit before they are confirmed and the same may not be reflected in the final blotter.

TradingAlgorithm.set_allowed_list(assets, on_fail=None)

Defines a whitelist of assets to be ordered. Any order outside these assets will be refused (with a warning). Usually, the user script will use either this function or the blacklist function set_do_not_order_list, but not both.

Parameters:

assets (list) – A list of assets.

TradingAlgorithm.set_do_not_order_list(assets, on_fail=None)

Defines a list of assets not to be ordered. Any order on these assets will be refused (with a warning).

Parameters:

assets (list) – A list of assets.

TradingAlgorithm.set_long_only(on_fail=None)

Set a flag for long only algorithm. Any short-selling order (attempt to sell without owning the assets) will be refused (and a warning raised).

TradingAlgorithm.set_max_daily_size(assets=None, max_quantity=None, max_notional=None, on_fail=None)

Set a limit on the order size - in terms of total daily limits. If assets is None, it is applied for all assets, else only for assets in the list.

Parameters:
  • assets (list) – A list of assets for position control.

  • max_quantity (int) – Maximum order quantity allowed.

  • max_notional (float) – Maximum order value allowed.

Warning

Specifying both max_quantity and max_notional will raise exception.

Important

This control will count an order as success on a successful check and will add its quantity or order value to its daily quota, irrespective of whether the order is actually executed. For example and order that passed the check but later cancelled by the user or rejected by the broker will still count towards the daily quota.

TradingAlgorithm.set_max_exposure(max_exposure, on_fail=None)

Set a limit on the account gross exposure. Any order that can potentially exceed this limit will be refused (with a warning).

Parameters:

max_exposure (float) – Maximum allowed exposure.

TradingAlgorithm.set_max_leverage(max_leverage, on_fail=None)

Set a limit on the account gross leverage . Any order that can potentially exceed this limit will be refused (with a warning).

Parameters:

max_leverage (float) – Maximum allowed leverage.

TradingAlgorithm.set_max_order_count(max_count, on_fail=None)

Set a limit on the maximum number of orders generated in a day. Any order that can exceed this limit will be refused (and will raise a warning).

Parameters:

max_count (int) – Maximum number of orders allowed per session (day).

Important

This control will count an order as success on a successful check and will add it to the daily quota, irrespective of whether the order is actually executed. For example and order that passed the check but later cancelled by the user or rejected by the broker will still count towards the daily quota.

TradingAlgorithm.set_max_order_size(assets=None, max_quantity=None, max_notional=None, on_fail=None)

Set a limit on the order size - either in terms of quantity, or value. Any order exceeding this limit will not be processed and a warning will be raised.

Parameters:
  • assets (list) – List of assets for this control. If assets is a dict, it should be in asset:value format, and will only apply to the assets mentioned. If assets is a list, the same value wil apply to all assets. If assets is None, the control value will apply to ALL assets.

  • max_quantity (int) – Maximum quantity allowed (unsigned).

  • max_notoinal (float) – Maximum value at current price.

TradingAlgorithm.set_max_position_size(assets=None, max_quantity=None, max_notional=None, on_fail=None)

Set a limit on the position size (as opposed to order size). Any order that can exceed this position (at current prices) will be refused (and will raise a warning). If assets is None, it is applied for all assets, else only for assets in the list.

Parameters:
  • assets (list) – A list of assets for position control.

  • max_quantity (int) – Maximum position quantity allowed.

  • max_notional (float) – Maximum position exposure allowed.

Warning

Specifying both max_quantity and max_notional will raise exception.

TradingAlgorithm.terminate(error=None, cancel_orders=True, is_error=False)

Exit from the current context/ run by scheduling the algo end event. This will cause the algorithm to exit execution as soon as possible. This will also trigger the analyze API function as it exits. If called from within a sub-context, will terminate only that subcontext. If error is an exception object or if is_error is True, the exit is assumed to be with error and the on_error handler will be invoked on exit. Else on_cancel will be invoked.

Parameters:
  • error (str) – An error message (or an exception object).

  • cancel_orders (bool) – If open orders should be cancelled.

  • is_error (bool) – If exiting on error.

Danger

This function only initiates outstanding orders cancellation, and does NOT guarantee it.

Pipeline APIs

Pipelines are a set of APIs to systematically select universe by computing filter and factors.

TradingAlgorithm.attach_pipeline(pipeline, name, chunks=None, eager=True)

Register a pipeline for this algorithm. Pipeline with the same name, if exists, will be overwritten. The name can later be used in the pipeline_output function to run the pipeline computation.

Parameters:
  • pipeline (zipline_pipeline.pipeline.Pipeline) – The pipeline object to register.

  • name (str) – Name of the pipeline to register with.

  • chunks (iterable) – Iterator to specify the computation chunks.

  • eager (bool) – Compute ahead the pipeline.

Returns:

Return the pipeline object.

Return type:

zipline_pipeline.pipeline.Pipeline

TradingAlgorithm.pipeline_output(name)

Return the result of the pipeline name for the current time. The result is a pandas DataFrame, indexed by asset objects (that are trading at the current time and has passed the filtering criteria in the pipeline). Each column in the dataframe corresponds to the factors added to the pipeline definition.

Note

Pipeline output for a given date consider inputs till the previous trading day. Also, pipeline output works with daily data. Therefore running the same pipeline multiple times on the same day is superfluous as it will return the same data on each call.

Returns:

Result from the pipeline.

Return type:

pandas.DataFrame

Pipeline in live trading

Blueshift > 2.0 supports pipeline API support in live trading. In live trading, all data query is sourced from the broker feed. However, the pipeline data query is directed to Blueshift database (daily frequency). The pipeline is, as usual, evaluated on daily prices till one day before the evaluation date.

Danger

Pipeline APIs are evaluated on the last close. If the latest data from our data vendors are not updated for some reason on a particular date, the pipeline evaluation will fail. In such case, we raise an exception and the live strategy will terminate with Error.

Backtest Model Selection APIs

The following API functions allow one to customise various aspects of the backtest simulation. These functions, of course, do not apply to live trading and are ignored in live mode.

TradingAlgorithm.set_slippage(model=None, *args, **kwargs)

Set the slippage model. For more details on available slippage models, see Slippage Models. Only valid for backtests.

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo. This method is ignored in live trading.

Parameters:

model (slippage model.) – A valid slippage model object.

TradingAlgorithm.set_commission(model=None, charge_model=None, *args, **kwargs)

Set the commission (cost) model. For more details see the Commissions and Cost Models descriptions. A commission model captures trading costs that are charged by the broker or the trading venue. An optional charge_model can also be specified to capture trading charges captured by authorities (e.g. taxes and levies). Only valid for backtests.

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo. This method is ignored in live trading.

Parameters:

model (commission model.) – A valid commission model object.

TradingAlgorithm.set_margin(model)

Set the margin model. For more details on available margin models, see Margin Models. Only valid for backtests.

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo. This method is ignored in live trading.

Parameters:

model (margin model.) – A valid margin model object.

Miscellaneous API functions

TradingAlgorithm.get_datetime()

Get the current date-time of the algorithm context. For live trading, this returns the current real-time. For a backtest, this will return the simulation time at the time of the call.

Returns:

current date-time (Timestamp) in the algo loop.

Return type:

pandas.Timestamp

TradingAlgorithm.record(*args, **kwargs)

Record a list of var-name, value pairs for each day.

Parameters:

kwargs – the names and values to record. Must be in pairs.

Note

The recorded values are tracked within the context, as record_vars variable. Also, any variable record is kept as only one point per day (session). If the user script records values at multiple points in a day, only the last value will be retained. Use of this function can slow down a backtest.

TradingAlgorithm.record_state(*args)

Add one or more context variables (user defined context attributes) names as the user defined algo state. Such variables will be persisted across a algo re-start and can be useful for strategies that require tracking of algo specific states (other than orders, positions and performances which are tracked automatically).

Note

The recorded variables are saved when a context terminates, or when the algo exits. To load the states after a restart, use the load_state API function.

Warning

The name of a state must be a string and a valid Python identifier. Also the values must be of type boolean, string, number, list or dict. Maximum number of state variables that can be saved is 10. For a string, maximum allowed number of characters is 128. For a list or a dict, maximum size should not exceed 50KB.

See also

blueshift.core.algorithm.context.AlgoContext.load_state. blueshift.core.algorithm.context.AlgoContext.state.

TradingAlgorithm.load_state()

Load saved state variables (usually after a restart). This will load the saved state variables for the current context and set the save values as context attributes.

Note

The recorded values are tracked within the context, as state variable.

Warning

If the last run fails to save the states (illegal variable name or value, or some system error), the loaded state may have missing state variables.

See also

blueshift.core.algorithm.context.AlgoContext.record_state. blueshift.core.algorithm.context.AlgoContext.state.

TradingAlgorithm.set_benchmark(asset)

Overwrite the default benchmark asset for algo performance analysis.

Param:

asset object.

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo.

TradingAlgorithm.set_account_currency(currency)

Set the currency of the account. Only valid for backtests.

Parameters:

currency (str or CCY) – A supported currency code or enumeration.

Note

for non-fx brokers, this will be ignored. All non-fx brokers assume the algo performance is maintained in the LOCAL currency.

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo. This method is ignored in live trading.

TradingAlgorithm.set_cooloff_period(period=30)

Set the cool-off period following a call to the square_off function, or following an exit resulting from a take profit or stop loss, or an explicit call to trigger a cool-off period using set_cooloff method.

Parameters:

period (int) – The period (in minutes) to cool off.

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo.

Note

In general, cooloff period should be a positive integer, however, you may pass on a fraction in live trading. For backtests, any fractional number will be rounded up to integer automatically.

TradingAlgorithm.set_cooloff(assets=None)

Trigger a cool-off period. This will result in no further entry trades for the specified assets, or any assets if not specified. This cool-off period will last till the defined value (set by set_cooloff_period, defaults to 30 minutes).

Parameters:

assets (list) – List of assets (or None) to enable the cooloff for.

Important

If assets are specified, they should not be in rolling format for options, else they might be ignored.

TradingAlgorithm.set_algo_parameters(param_name='params')

Declare a context attribute as algo parameters. If any parameters are passed (from commandline for example), those will be captured and stored as a dictionary under this name.

Parameters:

param_name (str) – An attribute of the context variable.

Note

If the attribute does not exist, a new attribute is created and set to the values passed as the –parameters flag as a dictionary of key-value pairs. If it exists, it must be a dictionary, and parameter key-value pairs from the –parameters flag are added to the attribute (overwritten if exists).

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo.

TradingAlgorithm.set_initial_positions(positions)

Set starting positions for the algo. The argument positions must be a list of positions objects or a list of dictionaries that can be converted to a position objects. If the list contains dictionaries, each must have atleast asset, entry_price and quantity keys. The asset must be a valid symbol (and will be converted to an Asset object using the symbol function automatically) or an Asset object. The entry_price key must have the price at entry for the position, and quantity is a signed number of the position (negative for short position).

Parameters:

positions (list) – List of initial positions keyed by assets.

Important

The asset must match exactly with what is intended. For example, a rolling options asset may resolve to a different instrument. Also cash and margin traded equities are treated as different assets, even for the same symbol. For the later, you can either create the asset directly, or supply the product_type keyword (e.g. product_type=margin) to specify a margin equity product.

Warning

This method can only be called once in the initialize function. Calling it anywhere else will crash the algo. Also, for restarts, this call will be ignored, and the initial positions will be the last saved state of the algo.

TradingAlgorithm.finish(msg=None)

Exit from the current run by scheduling the algo end event. This will cause the algorithm to exit execution as soon as possible. This will also trigger the analyze API function as it exits. This method can be called from any subcontext as well, and will cause the whole algo to exit.

Parameters:

msg (str) – A message to print for the algo completion.

Warning

This function only initiates outstanding orders cancellation and position square-off, if specified in the exit policy and does NOT guarantee their successful completion.

TradingAlgorithm.exit_when_done(completion_msg=None, check_orders=True, check_positions=False)

Exit from the current run by scheduling the algo end event, after checking if all open orders are complete and/ or all open positions are closed out. If both check_orders and check_positions are False, it is equivalent to the finish API function.

Parameters:
  • completion_msg (str) – A completion message to display.

  • check_orders (bool) – Wait for open orders to finalize.

  • check_positions (bool) – Wait for open positions to close.

Note

If check_positions is True, it will wait for all open positions to close out, but will not initiate (square-off) on its own. You must do that (call square-off or equivalent) before you call this API function with check_positions as True, otherwise it can potentially wait a long time and /or exit with an error. Also, if check_positions is True, check_orders is automatically set to True (as otherwise the wait may not be meaningful).

Danger

This function only initiates termination but does NOT guarantee it.

TradingAlgorithm.square_off_and_exit()

Utility function that calls square-off and then wait for all positions to close before exiting the algo run.

TradingAlgorithm.is_trading_hours()

Function to check if the market is currently open for trading and the algo can place orders.

Returns:

True if open for trading, else False.

Return type:

bool