Objects, Models and Constants ============================= Trading Calendar ---------------- .. py:module:: blueshift.protocol .. autoclass:: TradingCalendar() :noindex: :members: .. note:: Calendar objects can be imported into the strategy code from ``blueshift.protocol`` module. But there is no reasonable case that a user strategy may need to import this class or instantiate an instance. Use :attr:`.AlgoContext.trading_calendar` to get a reference to the trading calendar of the running algo. Assets ------ Assets are objects in Blueshift that encapsulates information about tradable instruments (e.g. equities) or non-tradable market data (e.g. a market index). User strategy code uses the :ref:`symbol` function to convert a symbol name to the corresponding asset objects. This asset object then can be passed on to market data query, order placing functions etc. Asset Symbology ++++++++++++++++ The symbology followed on Blueshift is pretty straightforward. Exchange traded equities are referred to by their respective exchange symbols. Forex assets are referred to as ``CCY1/CCY2`` (with the conventional meaning). In all cases, you can optionally add the exchange reference as ``EXCHANGE:SYMBOL``. Note, adding exchange is NOT required at present, as Blueshift does not support multiple exchanges for the same security currently. Also, specifying a wrong exchange name can raise the ``SymbolNotFound`` exception. .. note:: Special characters in symbol names (e.g. '-' or '&') are replaced by an underscore ('_') in Blueshift. This means a symbol like 'M&M' becomes 'M_M'. Dated and Rolling Symbols ^^^^^^^^^^^^^^^^^^^^^^^^^^ Difference between a dated and rolling instrument is important for futures and options instruments. A dated instrument refers to a specific instrument with a given expiry (and strike price in case of option). A rolling instrument is a generic representation of a series of actual instruments, defined by a relative expiry (e.g. monthly futures) and/ or a relative strike price (e.g. ATM options). For futures, the symbol is ``SYM`` for dated instruments - where ``SYM`` refers to the underlying symbol and the date part is the expiry date. For option the format is ``SYMTYPE``, where ``TYPE`` is the :ref:`option type` and can be either ``CE`` or ``PE``. The ``STRIKE`` is the strike price of the option (with no leading or trailing zeros). Referring to rolling (continuous) futures and options are simple. Instead of the expiry date, specify the expiry series. For monthly futures and options, specify ``-I`` for the near month and ``-II`` for the far month. For weekly options, specify ``-W{n}`` instead, where n is the week offset (starting from 0 for the current week). For specifying relative strike, use + or - and specify the strike difference from the ATM. Add the keyword argument use_spot=True to specify the offset from the current spot levels. By default the offset will be calculated from the implied futures. Below shows some examples for a hypothetical underlying ABC. Option strikes can also be specified in terms of steps from ATM (instead of offset from ATM) - by specifying ``IMT{n}`` or ``OTM{n}`` after the symbol, expiry and option type part ('ABC-ICEOTM2'). For an underlying wich has traded strikes, say, 100 points apart, this is equivalent to 'ABC-ICE200' (OTM 2 signifies 2 strikes away from the ATM, and hence 2*100=200 in terms of point offset). Additionally, specifying strike in terms of delta or premium is also supported. For delta replace the strike part with ``+{X}D`` or ``-{X}D`` where X is an interger equal to the delta fraction multiplied by 100 ( i.e. 20 for 0.2 delta). Similarly, specify the premium as ``{X}P`` where X is the premium in the nearest cents. Note, using this symbology will initiate a search for the matching instrument. You should check the actual delta or price of the instrument to ensure the the correct instrument is returned. Also for delta or premium based symbology, the instrument returned will be a dated asset (i.e. a fixed strike which match the delta or premium specified at the time of the query). If you are using ``dt`` argument of the ``symbol`` function, it always resolves to a dated instrument, corresponding to the timestamp, even if the symbol representation itself is rolling. Using ``dt`` argument with a dated symbol representation is not much useful, but it is not an error. .. code-block:: python from blueshift.api import symbol def initialize(context): asset0= symbol('ABC') # ABC equity asset1= symbol('NYSE:ABC') # Specify the exchange (not needed) asset2= symbol('ABC20210826') # ABC Aug 2021 futures asset3= symbol('ABC20210826CE16000') # ABC Aug 21 call at 16K strike asset4= symbol('ABC-I') #first month futures asset5= symbol('ABC-ICE+100') # ABC ATM+100 call near-month asset6= symbol('ABC-W0PE-0') # ABC current-week ATMF put asset7= symbol('ABC-W0PE-100', use_spot=True) # 100 from the spot level asset8= symbol('ABC-IPE5OTM') # 5th OTM strike asset9= symbol('ABC-ICE20D') # call with delta 0.2 asset10= symbol('ABC-ICE5000P') # call with premium 50 asset11= symbol('ABC-ICE+100', dt=get_datetime()) # dated instrument You can use the rolling symbology for both data query and placing orders. See the caveats below on how rolling symbology differs for futures and options in backtesting and live trading. For placing orders, it is recommended to use a dated symbol (i.e. pass the `dt` parameter in the `symbol` function). .. important:: If ``dt`` argument is ommitted, in case of backtest, a rolling symbol representation will result in a rolling instrument. Querying for data using a rolling instrument in backtest will respect the rolling representation, i.e. it will return, for e.g., the ATM option price for an ATM option symbol, even as the ATM strike keeps on changing during the data query interval. For live trading, symbols always resolves to a dated instrument. So data query will return results for a specifc strike, (the current prevailing ATM strike in this case), even if the representation is for ATM. .. warning:: Be careful when using rolling assets on Blueshift for placing orders. Futures and options rolling assets behave differently in backtesting. Positions from orders with rolling futures are tracked as the rolling futures itself, and the position is automatically rolled on expiry date. Orders for rolling options creates positions in the specific expiry and strike prevailing at the time of the order. Such positions will not be rolled automatically. In live trading, both resolves to dated instruments - without any automatic roll. Asset Related Constants ++++++++++++++++++++++++ Below are constants related to asset definitions. AssetClass ^^^^^^^^^^^ Asset class of the asset object. .. py:module:: blueshift.assets .. autoclass:: AssetClass .. autoattribute:: AssetClass.EQUITY .. autoattribute:: AssetClass.FOREX InstrumentType ^^^^^^^^^^^^^^^ Instrument type of the asset object. ``SPOT`` assets are traded with full price paid during buying and selling. ``MARGIN`` assets are traded on the margin. ``FUTURES`` as futures derivatives on another underlying asset. ``OPT`` are options on another underlying asset. .. py:module:: blueshift.assets :noindex: .. autoclass:: InstrumentType .. autoattribute:: InstrumentType.SPOT .. autoattribute:: InstrumentType.FUTURES .. autoattribute:: InstrumentType.OPT .. autoattribute:: InstrumentType.MARGIN .. autoattribute:: InstrumentType.FUNDS OptionType ^^^^^^^^^^^ Options assets can be either ``CALL`` or ``PUT``. All options are at present assumed to be of the European type. .. py:module:: blueshift.assets :noindex: .. autoclass:: OptionType .. autoattribute:: OptionType.CALL .. autoattribute:: OptionType.PUT StrikeType ^^^^^^^^^^^ Blueshift asset symbology supports specifying options strikes as either absolute (ABS) or relative (to the future-implied ATM strike, REL). .. py:module:: blueshift.assets :noindex: .. autoclass:: StrikeType .. autoattribute:: StrikeType.ABS .. autoattribute:: StrikeType.REL Types of Asset +++++++++++++++ Different assets are modelled as objects of different classes. The base class is `MarketData`. All asset classes are derived from it. Below provides a list of supported assets. Market Data ^^^^^^^^^^^ .. py:module:: blueshift.assets :noindex: .. autoclass:: MarketData Asset ^^^^^^ .. autoclass:: Asset Forex ^^^^^^ .. autoclass:: Forex :members: Equity ^^^^^^^ Fully funded cash equity asset. .. autoclass:: Equity :members: EquityMargin ^^^^^^^^^^^^ Equity product traded on the margin. .. autoclass:: EquityMargin :members: EquityIntraday ^^^^^^^^^^^^^^ Equity products traded on the margin which cannot be carried overnight. Usually fresh orders are restricted after a cut-off time towards the closing hours of the market. .. autoclass:: EquityIntraday :members: EquityFutures ^^^^^^^^^^^^^^ .. autoclass:: EquityFutures :members: EquityOption ^^^^^^^^^^^^^ .. autoclass:: EquityOption :members: .. note:: All these objects can be imported into the strategy code from ``blueshift.assets``. Data and Simulation Models for Assets ++++++++++++++++++++++++++++++++++++++ On Blueshift, the data availability and default simulation behaviours depend on the asset class. By default, equities are considered fully funded instruments. That is, buying requires the full cost to be paid in cash (and shorting generates the opposite cash flow). The default simulation model is the :py:class:`blueshift.finance.slippage.VolumeSlippage`. For modelling equity trading on the margin, use `EquityMargin`, which uses the same slippage model, but tracks the required margins and related cash flows through the :py:class:`blueshift.finance.margin.FlatMargin` by default. `EquityFutures` uses the same default slippage and margin models. `EquityOptions` slippage are computed differently. The slippage, in this case, is based on the options vega instead of volumes. The maximum transaction limit per bar is 100 lots, and the impact is calculated as a 0.5% bump on the vega (i.e. vega*implied_vol*0.005). Also, since the volatilty smile is computed from puts for below ATM and from calls for above ATM strikes, strategies exploring put and call implied volatity discrepancies at the same strike (for example, put call parity)) cannot be modelled. The forex related assets are modelled using the :py:class:`blueshift.finance.slippage.BidAskSlippage` by default. Orders ------- ProductType +++++++++++ ProductType determines the handling of the position. ``DELIVERY`` is the usual type, where an asset is purchased by paying the full price and is held till it is sold (or auto-closed by the algo). ``MARGIN`` is when the asset is purchased on the margin (paying a fraction of the cost). ``INTRADAY`` is specific to certain geographies , it is same as margin, but the asset is automatically squared-off the same day (if not already done so), by the broker, after a cut-off time. .. py:module:: blueshift.protocol :noindex: .. autoclass:: ProductType .. autoattribute:: ProductType.INTRADAY .. autoattribute:: ProductType.DELIVERY .. autoattribute:: ProductType.MARGIN OrderType ++++++++++ Order types determines how the orders are to be executed. A ``MARKET`` order is executed at the best available price. A ``LIMIT`` order is put in the order book and is executed at the limit price or better. A ``STOPLOSS_MARKET`` order is an order that gets activated after a certain trigger (stoploss price) and becomes a market order after that. A ``STOPLOSS`` (or a stop-limit) order gets activated after a trigger is breached (stoploss price), and then becomes a limit order. A limit price is required for a limit order. A stoploss price is required for a stoploss market order. Specifying both is required for a stop-limit order. .. py:module:: blueshift.protocol :noindex: .. autoclass:: OrderType .. autoattribute:: OrderType.MARKET .. autoattribute:: OrderType.LIMIT .. autoattribute:: OrderType.STOPLOSS .. autoattribute:: OrderType.STOPLOSS_MARKET OrderValidity +++++++++++++ Validity of an order. ``DAY`` means valid for the entire trading day (till cancelled by the algo). ``IOC`` or immediate-or-cancel ensures the order is filled fully or as much as possible as soon as it arrives, and the remaining part is cancelled if it cannot be filled immediately. ``FOK`` or fill or kill orders are filled either fully or cancelled (i.e. avoids partial fill). ``AON`` or all-or-none is similar to fill-or-kill, but they are not cancelled and remain in the order book - but can be filled either fully or none at all. ``GTC`` is valid till the order is explicitly cancelled. ``OPG`` (market-on-open) and ``CLS`` (market-on-close) are not implemented, but can be supported by a live broker. .. py:module:: blueshift.protocol :noindex: .. autoclass:: OrderValidity .. autoattribute:: OrderValidity.DAY .. autoattribute:: OrderValidity.IOC .. autoattribute:: OrderValidity.FOK .. autoattribute:: OrderValidity.AON .. autoattribute:: OrderValidity.GTC .. autoattribute:: OrderValidity.OPG .. autoattribute:: OrderValidity.CLS .. note:: the default validity is ``DAY``. OrderSide +++++++++ A ``BUY`` order or a ``SELL`` order. .. py:module:: blueshift.protocol :noindex: .. autoclass:: OrderSide .. autoattribute:: OrderSide.BUY .. autoattribute:: OrderSide.SELL OrderStatus +++++++++++ Status of an order. ``COMPLETE`` means fully executed. ``OPEN`` means partially (including 0) executed and still active. ``REJECTED`` means the order is no longer active, and is rejected by the broker. ``CANCELLED`` means the order is no longer active and is cancelled by the algo. A rejected or cancelled order can be partially filled. .. py:module:: blueshift.protocol :noindex: .. autoclass:: OrderStatus .. autoattribute:: OrderStatus.COMPLETE .. autoattribute:: OrderStatus.OPEN .. autoattribute:: OrderStatus.REJECTED .. autoattribute:: OrderStatus.CANCELLED Order +++++ .. py:module:: blueshift.protocol :noindex: .. autoclass:: Order .. automethod:: Order.is_open .. automethod:: Order.is_buy Positions --------- PositionSide ++++++++++++ PositionSide captures the original side of the position - ``LONG`` if a long position, ``SHORT`` otherwise. .. py:module:: blueshift.protocol :noindex: .. autoclass:: PositionSide .. autoattribute:: PositionSide.LONG .. autoattribute:: PositionSide.SHORT Position ++++++++ .. py:module:: blueshift.protocol :noindex: .. autoclass:: Position .. automethod:: Position.if_closed Simulation Models ------------------ Slippage Models ++++++++++++++++ .. py:module:: blueshift.finance.slippage :noindex: .. autoclass:: SlippageModel :members: .. autoclass:: NoSlippage .. autoclass:: BidAskSlippage .. autoclass:: VolumeSlippage .. autoclass:: FixedSlippage .. autoclass:: FixedBasisPointsSlippage Margin Models ++++++++++++++ .. py:module:: blueshift.finance.margin :noindex: .. autoclass:: MarginModel :members: .. autoclass:: NoMargin .. autoclass:: FlatMargin .. autoclass:: RegTMargin .. autoclass:: VarMargin Commissions and Cost Models ++++++++++++++++++++++++++++ .. py:module:: blueshift.finance.commission :noindex: .. autoclass:: CostModel :members: .. autoclass:: NoCommission .. autoclass:: PerDollar .. autoclass:: PerShare .. autoclass:: PerOrder .. autoclass:: PipCost Risk Management System (RMS) +++++++++++++++++++++++++++++ .. py:module:: blueshift.brokers.rms .. autoclass:: IRMS :members: AlgoOrder Interface -------------------- To define a custom execution algorithm (to use with the ordering function), inherit from the `IAlgoOrder` class and overwrite the necessary methods. .. py:module:: blueshift.lib.execution.algo_orders .. autoclass:: AlgoOrderStatus .. autoattribute:: AlgoOrderStatus.COMPLETE .. autoattribute:: AlgoOrderStatus.OPEN .. autoattribute:: AlgoOrderStatus.REJECTED .. autoattribute:: AlgoOrderStatus.CANCELLED .. autoattribute:: AlgoOrderStatus.CREATED .. autoattribute:: AlgoOrderStatus.ERRORED .. autoclass:: IAlgoOrder .. autoattribute:: children .. autoattribute:: filled .. autoattribute:: asset .. autoattribute:: quantity .. autoattribute:: side .. automethod:: execute .. automethod:: update .. automethod:: cancel .. automethod:: reject Miscellaneous Constants ------------------------ Currency +++++++++ .. py:module:: blueshift.protocol :noindex: .. autoclass:: CCY .. autoattribute:: CCY.LOCAL .. autoattribute:: CCY.USD .. autoattribute:: CCY.EUR .. autoattribute:: CCY.GBP .. autoattribute:: CCY.AUD .. autoattribute:: CCY.JPY .. autoattribute:: CCY.NZD .. autoattribute:: CCY.CHF .. autoattribute:: CCY.INR Algo Modes and Other Constants +++++++++++++++++++++++++++++++ .. autoclass:: AlgoMode .. autoattribute:: AlgoMode.BACKTEST .. autoattribute:: AlgoMode.LIVE .. autoattribute:: AlgoMode.PAPER .. autoattribute:: AlgoMode.EXECUTION .. autoclass:: ExecutionMode .. autoattribute:: ExecutionMode.AUTO .. autoattribute:: ExecutionMode.ONECLICK .. autoclass:: AlgoCallBack .. autoattribute:: AlgoCallBack.DATA .. autoattribute:: AlgoCallBack.TRADE .. note:: All these objects can be import into the strategy code from ``blueshift.api``. These constants are useful when doing different processing based on the algo mode or execution mode. Query the :attr:`.AlgoContext.mode` for the mode of the current running algo. Query the :attr:`.AlgoContext.execution_mode` attribute from within strategy code to ascertain the current execution mode. Example: .. code-block:: python from blueshift.protocol import AlgoMode def initialize(context): if context.mode == AlgoMode.LIVE: print('some extra debug prints only during live trading ') Oneclick notification status +++++++++++++++++++++++++++++ .. py:module:: blueshift.protocol :noindex: .. autoclass:: OneClickState .. autoattribute:: OneClickState.ACTIONED .. autoattribute:: OneClickState.EXPIRED .. autoattribute:: OneClickState.ERRORED Only applicable in oneclick execution mode. `ACTIONED` means the user confirmed the order. `EXPIRED` means the order notification expired without user confirmation, and `ERRORED` means the confirmation or the notification encountered an error and will not be processed any further.