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.

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.

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(“NIFTY-W0CE+0”) will refer to the first the current weekly ATM call 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).

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 handling of limit and stop price specification is totally implementation dependent. In case the broker supports limit orders, limit_price will be effective.

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).

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

  • 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.

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.

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.

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.

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.

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.

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)

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.

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.

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.

Parameters

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

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.

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=True)

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 the underlying broker natively support squaring off open positions, this method will use that interface. In such cases, squaring off will only happen if there is an open position with the broker, not just with this algo. An example of such a case is two algos placing opposite orders - resulting in opposite positions in each algo, but no open positions with the broker. In such a case the square-off will do nothing. This behaviour is intentional to avoid creating unintended positions during square-off. Also, in such case, no cool-off period is enforced.

If the underlying broker does not support square-off natively, then the algo positions will be considered. In such case, a square-off may actually create a new position with the underlying broker. This will also result in a cool-off period during which a new entry into the same asset(s) will not be allowed. Additionally, during cool-off period, additional call to this method will not result in positions unwinding, but will cancel open orders. This behaviour is intentional to avoid creating unintended positions with repeated sqauare-off attempts.

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.

Important

This API will bypass any trading controls to make sure square-off orders are not blocked by such controls. 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

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.

Stoploss and Take-profit

Add or Remove Stoploss

TradingAlgorithm.set_stoploss(asset, method, target, trailing=False, on_stoploss=<function noop>)

Set the stoploss for a position, defined by an asset. Method can be one of PRICE, MOVE, PERCENT. PRICE set the target as the stop level. MOVE will add the target to the entry price to compute stop level, whereas PERCENT will compute the percent move from the entry price. If trailing is True, stoploss is updated at each lookup frequency ( i.e. every minute).

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

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

  • target (float) – The stoploss target.

  • trailing (bool) – If it is a trailing stoploss.

Important

If you are placing the entry order with a stoploss specified, 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.

TradingAlgorithm.remove_stoploss(asset)

Remove stoploss for an asset.

Parameters

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

Add or Remove Take-profit Target

TradingAlgorithm.set_takeprofit(asset, method, target, on_takeprofit=<function noop>)

Set the take-profit for a position, defined by an asset. Method can be one of PRICE, MOVE, PERCENT. PRICE set the target as the level. MOVE will add the target to the entry price to compute level, whereas PERCENT will compute the percent move from the entry price.

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

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

  • target (float) – The stoploss target.

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.

TradingAlgorithm.remove_takeprofit(asset)

Remove takeproft for an asset.

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_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.

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).

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_message=None, cancel_orders=True)

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.

Parameters

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

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 will be overwritten.

Args:

pipeline (obj): A pipeline object to register.

name (str): Name of the pipeline.

chunks (iterable): Iterator to specify the computation chunks.

eager (bool): Compute ahead the pipeline.

Returns:

Returns the pipeline object registered.

TradingAlgorithm.pipeline_output(name)

return pipeline output for the given name.

Pipeline in live trading

Blueshift 2.0 introduces 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.

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).

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.

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.

See blueshift.algorithm.context.AlgoContext.record_vars.

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.

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.

Parameters

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

TradingAlgorithm.set_algo_parameters(param_name='params')

Declare a context attribute as algo parameters.

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 value 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).