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.algorithm.algorithm :noindex: .. automethod:: TradingAlgorithm.symbol .. automethod:: TradingAlgorithm.symbols .. automethod:: TradingAlgorithm.get_dated_asset .. 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:: 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``. .. py:module:: blueshift.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. 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 Square Off Position ^^^^^^^^^^^^^^^^^^^^ .. automethod:: TradingAlgorithm.square_off Stoploss and Take-profit +++++++++++++++++++++++++ Stoploss and Take-profit Exit Method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. py:module:: blueshift.protocol :noindex: .. autoclass:: blueshift.protocol.ExitMethod .. autoattribute:: ExitMethod.PRICE .. autoattribute:: ExitMethod.MOVE .. autoattribute:: ExitMethod.PERCENT .. autoattribute:: ExitMethod.AMOUNT Add or Remove Stoploss ^^^^^^^^^^^^^^^^^^^^^^^^ .. py:module:: blueshift.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``) can only be called within :ref:`initialize` function. A set of API functions to control trade risk and implements various limits. .. py:module:: blueshift.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 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 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. .. automethod:: TradingAlgorithm.set_slippage .. automethod:: TradingAlgorithm.set_commission .. automethod:: TradingAlgorithm.set_margin Miscellaneous API functions --------------------------- .. automethod:: TradingAlgorithm.get_datetime .. automethod:: TradingAlgorithm.record .. automethod:: TradingAlgorithm.set_benchmark .. automethod:: TradingAlgorithm.set_account_currency .. automethod:: TradingAlgorithm.set_cooloff_period .. automethod:: TradingAlgorithm.set_cooloff .. automethod:: TradingAlgorithm.set_algo_parameters .. automethod:: TradingAlgorithm.set_initial_positions .. automethod:: TradingAlgorithm.exit_when_done .. automethod:: TradingAlgorithm.is_trading_hours