Objects, Models and Constants
Trading Calendar
- class blueshift.protocol.TradingCalendar
A trading calendar maintains the trading sessions for a given trading venue (e.g. an exchange like NYSE). It has an associated timezone. It tracks sessions opening/ closing times and holidays. Strategy can access it via the context variable as
AlgoContext.trading_calendar
.See also
See documentation on the Context Object.
- bump_forward(dt)
bump to the next date if dt is a holiday.
- bump_mod_forward(dt)
bump to next date, unless the result is in the next month, in which case, bump to the previous date.
- bump_mod_previous(dt)
bump to previous, unless the result is in the previous month, in which case, bump to the next date.
- bump_previous(dt)
bump to the previous date if dt is a holiday.
- property close_time
session closing time in
datetime.time
format.
- current_session(dt)
returns the current session. Returns next if not a trading session.
- is_holiday(dt)
check (
bool
) if it is a holiday, given a timestamp.
- is_open(dt)
check (
bool
) for if a trading session is in progress, given a timestamp.
- is_session(dt)
check (
bool
) if it is a trading day, given a timestamp.
- last_n_sessions(dt, n, convert=True)
Returns last n trading sessions, including dt.
- last_trading_minute(dt)
returns the last trading minute.
- property minutes_per_day
total number of minutes (
int
) in a trading session.
- property name
name (
str
) of the trading calendar.
- next_close(dt)
returns next close session time (
pandas.Timestamp
), given a timestamp.
- next_n_sessions(dt, n, convert=True)
Returns next n trading sessions, including dt.
- next_open(dt)
returns next open session time (
pandas.Timestamp
), given a timestamp.
- next_session(dt)
returns the next session.
- property open_time
session opening time in
datetime.time
format.
- previous_close(dt)
returns previous close session time (
pandas.Timestamp
).
- previous_open(dt)
returns previous open session time (
pandas.Timestamp
) , given a timestamp.
- previous_session(dt)
returns the previous session.
- sessions(start_dt, end_dt, convert=True)
list all valid sessions between dates, inclusive (
pandas.DatetimeIndex
).
- to_close(dt)
returns the close time of the curret session(
pandas.Timestamp
) , given a timestamp. Returns the next session open if the market is closed.
- to_open(dt)
returns current open session time (
pandas.Timestamp
) , given a timestamp. Returns the next session open if the market is closed.
- property tz
time-zone (
str
) of the trading calendar.
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 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 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’ should be entered in the symbol function like ‘M_M’.
Dated and Rolling Futures and Options
For futures, the symbol is SYM<YYYYMMDD>
for dated instruments
- where SYM
refers to the underlying symbol and the date part is
the expiry date. For option the format is SYM<YYYYMMDD>TYPE<STRIKE>
,
where TYPE
is the 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).
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 caveat 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).
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 are treated as specific instruments without any automatic roll.
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
- class blueshift.assets.MarketData
MarketData class encapsulates an object with which some data (pricing or otherwise) may be associated. All tradable assets are derived from this class. This can also represent other generic data series like macro-economic data or corporate fundamental data.
A MarketData object has the following attributes. All attributes are read-only from a strategy code.
Attribute
Type
Description
sid
int
Unique Identifier
symbol
str
Symbol string
name
str
Long name
start_date
pandas.Timestamp
Start date of data
end_date
pandas.Timestamp
End date of data
ccy
Asset currency
exchange_name
str
Name of the exchange
calendar_name
str
Name of the calendar
Asset
- class blueshift.assets.Asset
Asset models a tradeable asset and derives from
MarketData
.An Asset object has the following attributes in addition to the attributes of the parent class. All attributes are read-only from a strategy code.
Attribute
Type
Description
asset_class
Asset class
instrument_type
Instrument type
mult
float
Asset multiplier (lot size)
tick_size
int
Tick size (reciprocal)
auto_close_date
pandas.Timestamp
Auto-close day
can_trade
bool
If tradeable
fractional
bool
Fractional trading supported
Warning
The
mult
attribute defaults to 1. Any order placed for an asset should include this in the order size. Order placement routine will check if the order size is a multiple ofmult
. For e.g. an asset with a lot size of 75 should use order size of 150 (order(asset, 150)
) to place an order for 2 lots.Note
The attribute
tick_size
is stored as reciprocal of the actual tick size. For a tick size of 0.05, the value stored will be 20. It defaults to 100 (corresponding to a tick size of 0.01).The
auto_close_date
is the date on which the asset is automatically squared-off (if still held by the algo). This defaults to theend_date
.
Forex
- class blueshift.assets.Forex
Forex models for margin traded forex. This is derived from the
Asset
class. This has the following attributes in addition to the attributes of the parent class. All attributes are read-only from a strategy code.Attribute
Type
Description
ccy_pair
str
currency pair (XXX/YYY)
base_ccy
str
Base currency (XXX)
quote_ccy
str
Quote currency (YYY)
buy_roll
float
Roll cost for a long position
sell_roll
float
Roll cost for a short position
initial_margin
float
Initial margin
maintenance_margin
float
Maintenance margin
Note
The
asset_class
is set toFOREX
and theinstrument_type
isMARGIN
.The roll costs are for 1 unit - the overnight roll is calculated as roll cost multiplied by the quantity in open position.
Equity
Fully funded cash equity asset.
- class blueshift.assets.Equity
Equity models exchange traded equities asset. This is derived from the
Asset
class. This has the following attributes in addition to the attributes of the parent class. All attributes are read-only from a strategy code.Attribute
Type
Description
shortable
bool
If shortable
borrow_cost
float
Borrow cost if shortable
Note
The
asset_class
is set toEQUITY
and theinstrument_type
isSPOT
for equities and FUNDS for ETFs.
EquityMargin
Equity product traded on the margin.
- class blueshift.assets.EquityMargin
Margin traded equity product.
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.
- class blueshift.assets.EquityIntraday
Intraday margin traded equity product.
EquityFutures
- class blueshift.assets.EquityFutures
Equity futures models exchange traded equities futures. This is derived from the
Asset
class. This has the following attributes in addition to the attributes of the parent class. All attributes are read-only from a strategy code.Attribute
Type
Description
underlying
str
Symbol of underlying asset
root
str
Root part of the symbol
roll_day
int
Roll period if rolling asset
expiry_date
pandas.Timestamp
Date of expiry
initial_margin
float
Initial margin
maintenance_margin
float
Maintenance margin
Note
The
asset_class
is set toEQUITY
and theinstrument_type
isFUTURES
. Theroll_day
parameter determines if the asset is a rolling asset (i.e. should be rolled automatically in backtest if value is greater than -1). Theroll_day
is the offset from theexpiry_date
to determine the roll date.
EquityOption
- class blueshift.assets.EquityOption
Exchange traded equity options. This is derived from the
EquityFutures
class. This has the following attributes in addition to the attributes of the parent class. All attributes are read-only from a strategy code.Attribute
Type
Description
strike
float
Option strike
strike_type
Option strike type
option_type
Type of option
Note
The
asset_class
is set toEQUITY
and theinstrument_type
isOPT
. The parameterstrike_type
determines the offset from the ATM strike, and can be either absolute, relative from ATM (e.g. +100 or -100) or in terms of delta (multiplied by 100, e.g. 25D or -10D).
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 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 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
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.
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.
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.
- class blueshift.protocol.OrderValidity(value)
An enumeration.
- DAY = 0
- IOC = 1
- FOK = 2
- AON = 3
- GTC = 4
- OPG = 5
- CLS = 6
Note
the default validity is DAY
.
OrderSide
A BUY
order or a SELL
order.
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.
Order
- class blueshift.protocol.Order
Order object encapsulates all details about orders sent by the algo to the broker. It also tracks the order fill. Orders are automatically tracked by internal trackers. Strategy code can query its attributes to check various details and fill status.
An order object has the following attributes. All attributes are read-only from a strategy code.
Attribute
Type
Description
oid
str
Order ID
asset
Asset of the position
quantity
float
Net quantity at present
product_type
Product type
order_type
Order type
order_validity
Order validity
disclosed
float
Total amount disclosed
price
float
Limit price
trigger_price
float
Stoploss trigger price
stoploss_price
float
Limit for stop-limit order
filled
float
Amount filled so far
pending
float
Pending (quantity-filled)
average_price
float
Average price of fill
side
Order side (buy/sell)
status
Order status
timestamp
pandas.Timestamp
Timestamp of last update
fractional
bool
If a fractional order
price_at_entry
float
Mid price at entry time
create_latency
float
Latency (milli) to create
exec_latency
float
Latency (milli) to place
Note
The
oid
is the field through which the platform tracks an order (which can be different from the broker or the exchange IDs).- is_open()
Is the order still open.
- is_buy()
Is the order a buy order.
Positions
PositionSide
PositionSide captures the original side of the position - LONG
if a long position, SHORT
otherwise.
Position
- class blueshift.protocol.Position
A position reflect the current economic interest in an asset, including associated profit and losses accumulated over the lifetime of such position. Positions are maintained by the algo blotter (though a dedicated tracker) and are updated on each trade or as and when prices change.
A position object has the following attributes. All attributes are read-only from a strategy code.
Attribute
Type
Description
asset
Asset of the position
quantity
float
Net quantity at present
buy_quantity
float
Total buying quantity
buy_price
float
Average buy price
sell_quantity
float
Total sell quantity
sell_price
float
Average selling price
pnl
float
Total profit or loss
realized_pnl
float
Realised part of pnl
unrealized_pnl
float
Unrealized (MTM) part of pnl
last_price
float
Last updated price
last_fx
float
Last known FX conversion rate
underlying_price
float
Underlying price
timestamp
pandas.Timestamp
Timestamp of last update
value
float
Holding value of this position
cost_basis
float
Entry cost of this position
margin
float
Margin posted (if available)
product_type
Product type
position_side
Position side (Long/Short)
fractional
bool
If a fractional order
- if_closed()
If this position is closed out.
Simulation Models
Slippage Models
- class blueshift.finance.slippage.SlippageModel
Slippage model implements the backtest simulation. The core method simulate takes in an order and simulates the fill and the fill price.
- simulate()
Takes in an order (may be already partially filled), and returns a trade with executed price and amount, as well as the fair mid. The difference between the execution price and the fair mid is the slippage.
- class blueshift.finance.slippage.NoSlippage
Trade simulation based on OHLCV data without any slippage. The max volume executed at each trading bar is capped at max_volume fraction (defaults to 0.02, i.e. 2% of available volume at each bar) of the available volume at the bar. Setting max_volume to 0 will disable any cap and the full pending amount will be assumed to trade successfully in a single trade. The impact cost is always zero, i.e. the order is executed at the available ‘close’ price on that bar.
- Parameters:
max_volume (float) – maximum volume that can be executed at a bar.
- class blueshift.finance.slippage.BidAskSlippage
Trade simulation based on OHLCV data with bid-ask spread. The max volume executed is capped at max_volume fraction of the available volume at the bar. The impact cost equals to half the bid-ask spread. Setting`max_volume` to 0 will disable any cap and the full pending amount will be assumed to trade successfully in a single trade.
- Parameters:
max_volume (float) – maximum volume that can be executed at a bar.
Warning
This is supported only for cases where the dataset includes the ‘bid’ and ‘ask’ data. At present, only the Forex data set is suitable for this slippage model.
- class blueshift.finance.slippage.VolumeSlippage
Trade simulation based on OHLCV data with volume based slippage. In this model, the max volume that can be executed is capped at a fixed percent of the volume at the bar. The price impact is modelled based on the below.
\[\Delta P = s/2 + \alpha.\sigma.(\frac{Q}{V})^\beta\]- where:
\(\Delta P\) = impact, \(s\) = spread, \(\alpha\) = cost coefficient, \(\sigma\) = historical volatility, \(Q\) = traded volume, \(V\) = available volume, \(\beta\) = cost exponent
- Parameters:
max_volume (float) – maximum participation (defaults to 0.02).
cost_coeff (float) – cost coefficient (defaults to 0.002).
cost_exponent (float) – cost exponent (defaults to 0.5).
spread (float) – constant spread (defaults to 0).
spread_is_percentage (bool) – If false, spread is treated as absolute (defaults False).
use_vol (bool) – If false, vol is set to 1.0 (defaults to False).
vol_floor (float) – Floor value of vol (defaults to 0.05), ignored if use_vol is False.
See also
For more on the model, see here.
- class blueshift.finance.slippage.FixedSlippage
Trade simulation based on OHLCV data with a fixed slippage. The max volume executed is capped at max_volume fraction of the available volume at the bar. Slippage is half the spread.
- class blueshift.finance.slippage.FixedBasisPointsSlippage
Trade simulation based on OHLCV data with a fixed slippage expressed in basis points (100th of a percentage point). The max volume executed is capped at max_volume fraction of the available volume at the bar. Slippage is half the spread. The actual spread applied is arrived at as \(spread*close/10000\), where \(close\) is the close price at that bar.
Margin Models
- class blueshift.finance.margin.MarginModel
Margin model calculates margins required (or released) for an order execution. For a fully funded trade, (e.g. cash equities) the margin is 0. For margin trading or derivatives (futures and options), each trade adds to or releases a certain margin. Margins are charged from the available cash in the portfolio. On release, it is added back to portfolio cash. Each order, before execution, is checked for sufficient funds in the account. If sufficient funds are not available, the order is rejected.
All margin models derive from this class and concretely implement two methods, calculate and exposure_margin. The method calculate is used to determine margin requirements for a transaction. The method exposure_margin is used to calculate daily MTM settlements at the end-of-day calculation.
Note
Selection of margin models has no impact on fully funded assets (e.g. cash equities).
- calculate()
Calculate the cashflow and margin for a transaction. The algo account must have sufficient cash to cover for the transaction to happen.
- Parameters:
order (order object.) – Order object to process.
quantity (float) – Amount to trade.
price (float) – Traded price.
position (float) – Current position in the asset with sign.
timestamp (pandas.Timestamp) – Current timestamp.
last_fx (float) – FX rate for conversion.
underlying_px (float) – Underlying price for option.
pos (position object.) – Position object to process.
- Returns:
A tuple of cashflow, margin.
- Return type:
- exposure_margin()
Compute the exposure margin, given an asset and position in that asset. This is used for end-of-day mark-to-market settlement computation and is settled against the account. If the account is short of the required cash, the account is frozen for further trading.
- class blueshift.finance.margin.NoMargin
No margin. This model allows any amount of leverage for unfunded products (e.g. forex or derivatives).
- class blueshift.finance.margin.FlatMargin
Flat margin on total exposure as percentage. The parameter intial_margin is used to compute the fraction of the exposure required to be posted as margin for a transaction. This means 1/margin is the leverage offered. The default value is 10% (i.e. 10x leverage). The parameter maintenance_margin is applied for computation of margin required for carrying an overnight position. It defaults to the same value as the initial_margin - that is, no extra margin is charged for overnight positions.
- class blueshift.finance.margin.RegTMargin
RegT margin. This is derived from FlatMargin class with set values of intial_margin at 0.5 (50%) and maintenance_margin the same as the initial_margin for carrying an overnight position.
- class blueshift.finance.margin.VarMargin
Value-at-risk margin on total exposure - also known as portfolio margin. On blueshift, this is applied to each asset separately based on a multiplier of recent historical volatility. The formula is max(vol, vol_floor)*vol_factor. The default value of vol_factor is 3 (approximating a 99% VaR for normally distributed returns). The parameter vol_floor defaults to 0.05 (i.e. a minimum 5% volatility). The default value of lookback for historical volatility computation is 20. Volatilities are computed based on daily returns (daily volatility).
Commissions and Cost Models
- class blueshift.finance.commission.CostModel
CostModel defines the broking commission/ brokerage cost modelling (plus any exchange fees and/or tax/ regulatory charges, which defaults to zero and cannot be modified by the user). A concrete implementation must define the calculate method.
- Parameters:
- Keyword Arguments:
cost (
float
) – if supplied, overwrites the commission parameter.min_trade_cost (
float
) – if supplied, overwrites the cost_floor parameter.
- calculate()
Calculate the commission and charges for the transaction. Commission is the fees deducted by the broker for this particular transaction. Charges are any exchange fees and/ or government or regulatory charges on top.
- class blueshift.finance.commission.NoCommission
Zero commission and trading charges.
- class blueshift.finance.commission.PerDollar
Brokerage costs based on total value traded with cap and floor. This is derived from CostModel and takes in the same parameters. The parameter commissions (or cost) is multiplied with the traded value (quantity times the price) to determine the cost.
Brokerage costs based on total quantity traded with cap and floor. This is derived from CostModel and takes in the same parameters. The parameter commissions (or cost) is multiplied with the traded quantity to determine the cost.
- class blueshift.finance.commission.PerOrder
Flat brokerage costs per order. This is derived from CostModel and takes in the same parameters. The parameter commissions (or cost) is the flat rate per order. If an order results in multiple trades (corresponding to multiple fills), the charge is applied only once (per order).
- class blueshift.finance.commission.PipCost
Brokerage costs based on total quantity traded with cap and floor. This is derived from CostModel and takes in the same parameters. The parameter commissions (or cost) is multiplied with the traded quantity to determine the cost. In addition, this also implements the rollcost method to calculate the overnight funding cost of carrying over the position.
Note
This cost model is suitable for Forex assets only.
Risk Management System (RMS)
- class blueshift.brokers.rms.IRMS(broker)
Abstract interface for Risk Management System implemented by a broker. This is separate from built-in RMS in core blueshift and is meant to handle asset-class/geography/exchange or other specific risk management requirements.
- abstract monitor(position: Position)
Monitor a position for RMS action (e.g. auto-squareoff). Not used at present.
- abstract property name
The name of this particular RMS.
AlgoOrder Interface
To define a custom execution algorithm (to use with the ordering function), inherit from the IAlgoOrder class and overwrite the necessary methods.
- class blueshift.lib.execution.algo_orders.AlgoOrderStatus(value)
An enumeration.
- COMPLETE = ('complete',)
- OPEN = ('open',)
- REJECTED = ('rejected',)
- CANCELLED = 'cancelled'
- CREATED = 'created'
- ERRORED = 'errored'
- class blueshift.lib.execution.algo_orders.IAlgoOrder(algo, *args, **kwargs)
Interface for Algo Orders. It follows all the standard properties of the regular Order objects. During the init, pass a algo name (should be a string), and other attribute values relevant for an order object. The lifetime is started once the order object is passed on to the algo order function (which invoke its execute method). After this, periodically the update method is called, till the order reaches a terminal state. The following attributes cannot be overwritten - product_type (set to ProductType.ALGO), order_type ( set to OrderType.SMART), order_validity (DAY), order_flag (NORMAL), disclosed (0) and fractional (False). Other attributes are implemeted
- children
Child orders of this algo. Child orders are regular orders which together constitutes the exection of this algo. It is not required and all possible children are created and declared at start, child order can be added as and when required.
- filled
Returns the sum of the filled values of the children. If all child orders are not declared at the start, this will not compute the fill value correctly.
- asset
Must return a single and valid asset object. Use the asset_factory function to create dummy asset if required (for e.g. for basket orders or pair orders).
- quantity
Must return a number representing the quantity of the order. The interpretation of quantity, filled and pending remains same as regular order. If required, overwrite the filled and pending properties to make it consistent. The default implementation computes filled as sum total of filled from the children orders, and pending as the difference between quantity and filled.
- side
Must defined a OrderSide enum, for either BUY or SELL.
- abstract execute()
This method is invoked when an AlgoOrder object is passed on to the algo’s ordering function. It must initiate the execution process.
- abstract update()
This method is invoked periodically by the algo order handler. Update the order status (must be a AlgoOrderStatus enum) to reflect the current order status.
- abstract cancel()
Implement cancellation behaviour. After a successful cancellation, the status should be marked AlgoOrderStatus.CANCELLED.
- abstract reject(reason)
Implement rejection or error behaviour. After a successful handling, the status should be marked AlgoOrderStatus.REJECTED.
Miscellaneous Constants
Currency
- blueshift.protocol.CCY
alias of
Currency
Algo Modes and Other Constants
- class blueshift.protocol.AlgoMode(value)
Track the current running mode of algo - live or backtest.
BACKTEST
for backtesting mode andLIVE
for live mode.- BACKTEST = 'BACKTEST'
- LIVE = 'LIVE'
- PAPER = 'PAPER'
- EXECUTION = 'EXECUTION'
- class blueshift.protocol.ExecutionMode(value)
Track the current execution mode of a live algo.
AUTO
stands for automatic sending of orders to the broker.ONECLICK
means the user must confirm the order before it is send to the broker.- AUTO = 'AUTO'
- ONECLICK = 'ONECLICK'
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
AlgoContext.mode
for the mode of the current
running algo. Query the AlgoContext.execution_mode
attribute
from within strategy code to ascertain the current execution mode.
Example:
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
- class blueshift.protocol.OneClickState(value)
Oneclick user confirmation state.
- ACTIONED = 'actioned'
- EXPIRED = 'expired'
- ERRORED = '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.