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 :ref:`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. .. py:module:: blueshift.core.algorithm.algorithm :noindex: .. automethod:: TradingAlgorithm.symbol .. automethod:: TradingAlgorithm.symbols .. automethod:: TradingAlgorithm.get_dated_asset .. automethod:: TradingAlgorithm.sid .. automethod:: TradingAlgorithm.get_asset_for_order .. automethod:: TradingAlgorithm.get_asset_from_order For more on assets, see :ref:`assets`. For more on how to use symbols to refer to available instruments, see :ref:`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 :ref:`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 :ref:`Miscellaneous API functions` for more. Trading API functions --------------------- .. warning:: Blueshift supports running multiple strategies under a single account by using the concept of virtual account. In most cases, it should be fine with properly designed algos. However, be aware that in some cases with misbehaving algos, this can lead to issues. For example, running two algos - once placing a buy and another a sell order on the same stock at the same time, may lead this orders being flagged as wash trades by the broker or your compliance monitoring tools. 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``. .. py:module:: blueshift.core.algorithm.algorithm :noindex: .. automethod:: TradingAlgorithm.order .. attention:: All orders are subjected to the :ref:`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. .. automethod:: TradingAlgorithm.order_value .. automethod:: TradingAlgorithm.order_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. .. automethod:: TradingAlgorithm.order_target .. automethod:: TradingAlgorithm.order_target_percent .. automethod:: TradingAlgorithm.order_target_value .. 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. Automatic Order Slicing ^^^^^^^^^^^^^^^^^^^^^^^^ For simple order slicing requirements, one can use the automatic order slicing API method which accepts a total quantity and size of each slice, and essentially uses the `order` function above repeatedly to place orders for the slices. For more advanced requirements, see :ref:`algo orders`. .. automethod:: TradingAlgorithm.order_slice Place Order with retries ^^^^^^^^^^^^^^^^^^^^^^^^^ Use this method to place a simple order and wait for its execution. This is placed as an IOC order and with retries (in case the original order is cancelled or rejected). Unlike the base `order` method, this ensures the order is executed before it returns (the order ID(s)), or raise exception (`OrderError`) otherwise. This makes writing algorithm straight forward without the need to schedule a check for order execution (at the cost of more flexibility). .. automethod:: TradingAlgorithm.order_with_retry Oneclick Trading ^^^^^^^^^^^^^^^^^ Blueshift can run in `oneclick` :ref:`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. .. automethod:: TradingAlgorithm.set_oneclick_timeout .. automethod:: TradingAlgorithm.get_open_notifications .. automethod:: TradingAlgorithm.get_order_by_notification_id .. automethod:: TradingAlgorithm.get_oneclick_status .. automethod:: TradingAlgorithm.get_oneclick_order .. 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 :ref:`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 ^^^^^^^^^^^^ .. automethod:: TradingAlgorithm.update_order Cancel Order ^^^^^^^^^^^^ .. automethod:: TradingAlgorithm.cancel_order Fetch Open Orders ^^^^^^^^^^^^^^^^^^ .. automethod:: TradingAlgorithm.get_open_orders Fetch Open Positions ^^^^^^^^^^^^^^^^^^^^^ .. automethod:: TradingAlgorithm.get_open_positions Get Order by Order ID ^^^^^^^^^^^^^^^^^^^^^^ .. automethod:: TradingAlgorithm.get_order Check If Tradable ^^^^^^^^^^^^^^^^^^ .. automethod:: TradingAlgorithm.can_trade .. automethod:: TradingAlgorithm.is_alive Square Off Position ^^^^^^^^^^^^^^^^^^^^ .. automethod:: TradingAlgorithm.square_off 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. .. py:module:: blueshift.protocol :noindex: .. autoclass:: blueshift.protocol.ExitMethod .. autoattribute:: ExitMethod.PRICE .. autoattribute:: ExitMethod.MOVE .. autoattribute:: ExitMethod.PERCENT .. autoattribute:: ExitMethod.AMOUNT .. autoattribute:: ExitMethod.PNL Add or Remove Stoploss ^^^^^^^^^^^^^^^^^^^^^^^^ .. py:module:: blueshift.core.algorithm.algorithm :noindex: .. automethod:: TradingAlgorithm.set_stoploss .. automethod:: TradingAlgorithm.get_current_stoploss .. automethod:: TradingAlgorithm.remove_stoploss Add or Remove Take-profit Target ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. automethod:: TradingAlgorithm.set_takeprofit .. automethod:: TradingAlgorithm.get_current_takeprofit .. automethod:: TradingAlgorithm.remove_takeprofit .. important:: Always place stoploss or take-profit orders using assets from the :ref:`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`` and ``check_exits``) should only be called within :ref:`initialize` function. A set of API functions to control trade risk and implements various limits. .. py:module:: blueshift.core.algorithm.algorithm :noindex: .. automethod:: TradingAlgorithm.set_exit_policy .. automethod:: TradingAlgorithm.set_allowed_list .. automethod:: TradingAlgorithm.set_do_not_order_list .. automethod:: TradingAlgorithm.set_long_only .. automethod:: TradingAlgorithm.set_max_daily_size .. automethod:: TradingAlgorithm.set_max_exposure .. automethod:: TradingAlgorithm.set_max_leverage .. automethod:: TradingAlgorithm.set_max_order_count .. automethod:: TradingAlgorithm.set_max_order_size .. automethod:: TradingAlgorithm.set_max_position_size .. automethod:: TradingAlgorithm.terminate .. automethod:: TradingAlgorithm.check_exits Pipeline APIs ------------- Pipelines are a set of APIs to systematically select universe by computing filter and factors. .. automethod:: TradingAlgorithm.attach_pipeline .. automethod:: TradingAlgorithm.pipeline_output 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. .. automethod:: TradingAlgorithm.set_slippage .. automethod:: TradingAlgorithm.set_commission .. automethod:: TradingAlgorithm.set_margin Miscellaneous API functions ---------------------------- .. automethod:: TradingAlgorithm.get_datetime .. automethod:: TradingAlgorithm.record .. automethod:: TradingAlgorithm.record_state .. automethod:: TradingAlgorithm.load_state .. automethod:: TradingAlgorithm.fund_transfer .. automethod:: TradingAlgorithm.set_benchmark .. automethod:: TradingAlgorithm.set_account_currency .. automethod:: TradingAlgorithm.set_cooloff_period .. automethod:: TradingAlgorithm.set_cooloff .. automethod:: TradingAlgorithm.reset_cooloff .. automethod:: TradingAlgorithm.set_algo_parameters .. automethod:: TradingAlgorithm.set_initial_positions .. automethod:: TradingAlgorithm.finish .. automethod:: TradingAlgorithm.exit_when_done .. automethod:: TradingAlgorithm.wait_for_trade .. automethod:: TradingAlgorithm.wait_for_exit .. automethod:: TradingAlgorithm.square_off_and_exit .. automethod:: TradingAlgorithm.is_trading_hours