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.
- TradingAlgorithm.symbols(symbols, dt=None, *args, **kwargs)
API function to resolve a list of symbols to assets.
- 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.
- TradingAlgorithm.get_asset_for_order(asset, product_type=None)
Method to retrieve the asset for an order created from a given asset and product_type. Usually they will be the same, but maybe different if input asset is a rolling asset (in which case the equivalent dated asset will be returned), or the underlying broker has a default product type.
Note
the asset as it appears in the order attribute will always be dated, even if the order was created using a rolling asset definition.
- TradingAlgorithm.get_asset_from_order(order)
Method to retrieve the asset for a position created from a given order. Usually they will be the same, but maybe different if order was created using a rolling asset and the underlying broker implementation tracks positions in terms of rolling assets.
Note
the asset as it appears in the order attribute will always be dated, even if the order was created using a rolling asset definition.
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(“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 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 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
.
- 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 first argument can be an execution algo object (an instance of a subclass of IAlgoOrder). In this case, any other arguments will be ignored.
The handling of limit and stop price specification is totally implementation dependent. In case the broker supports limit orders, limit_price will be effective.
Note
You can pass an AlgoOrder object to trade execution algorithm. See Execution Algorithms.
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 aNone
value (e.g. order with 0 quantity).If running in oneclick execution mode, the returned notification ID can be exchanged to an order ID using the API function get_order_by_notification_id. This will return None if the notification is cancelled or not yet confirmed by the user or is expired. Will return an order ID if the user confirmed the order.
The asset supplied to the order function may not be the same asset in the order object. Use get_asset_for_order to determine what the asset in the order object will be.
The asset supplied to the order function, or the asset in the order object may not be the same as the asset in the position resulting from the order execution. Refer to the get_asset_from_order API function for this.
- Parameters
asset (asset object.) – asset on which the order to be placed (or and AlgoOrder).
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. This can be either an order ID, or a notification ID (when running in oneclicl execution mode), or None (in case the order did not generate any actual orders to be sent to the broker, e.g. order with 0 quantity).
- 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).
See also
blueshift.algorithm.algorithm.TradingAlgorithm.get_order
blueshift.algorithm.algorithm.TradingAlgorithm.get_open_orders
blueshift.algorithm.algorithm.TradingAlgorithm.get_order_by_notification_id
blueshift.algorithm.algorithm.TradingAlgorithm.get_asset_for_order
blueshift.algorithm.algorithm.TradingAlgorithm.get_asset_from_order
blueshift_objects.execution.algo_orders.IAlgoOrder
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.
Attention
All orders are subjected to the 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.
- 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
- 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 (including one-click orders that require user confirmation).
- Parameters
- 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.
Targetting order will NOT work for rolling option assets (as the strike may change with the underlying for a given strike offset over time) and an error will be raised.
- 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 (including one-click orders that require user confirmation).
- Parameters
- 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. 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 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.
- TradingAlgorithm.set_oneclick_timeout(timeout=None)
Overwrite the default benchmark asset for algo performance analysis.
- Parameters
timeout (int) – The timeout (in minutes) for notification expiry.
Warning
This method can only be called once in the initialize function. Calling it anywhere else will crash the algo.
- TradingAlgorithm.get_open_notifications()
Get a dictionary of all open notifications, keyed by their id. The return value is a dict object with order IDs (str) as keys and order objects as values. Applicable only when running in oneclick order confirmation mode.
- Returns
A dictionary of open notifications (yet to be confirmed or expire).
- Return type
- TradingAlgorithm.get_order_by_notification_id(notification_id)
Function to retrieve an order by notification id. This is only valid if the algo is running in oneclick execution mode. Notification ID is the ID returned on successful order placement in oneclick mode.
Note
If the notification did not result in an actual order ( e.g. expired, or cancelled notification), it will return None.
- TradingAlgorithm.get_oneclick_status(notification_id)
Function to retrieve the status of by notification id. This is only valid if the algo is running in oneclick execution mode. Notification ID is the ID returned on successful order placement in oneclick mode.
- TradingAlgorithm.get_oneclick_order(notification_id)
Function to retrieve the notification order object. This may be the initial order object created (with an app generated order ID), or an actual order that has been sent to the broker ( with the actual order ID). Returns None if not found.
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 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
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.
Note
Order asset will be dated asset. To fetch orders by rolling asset (applicable only for futures in backtest), use context.get_open_orders_by_asset instead.
- Returns
A dictionary of open orders.
- Return type
Fetch Open Positions
Get Order by Order ID
- TradingAlgorithm.get_order(order_id, algo=True)
Function to retrieve an order by order id.
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
Square Off Position
- TradingAlgorithm.square_off(assets=None, algo=True, ioc=False)
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 algo is False and 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. User strategies should not set algo to False in general.
If algo is True, then only 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 ioc is True, the orders sent for square-off will be IOC. A total 3 attempts will be made to square-off an asset in this case before giving up.
If
assets
is None, all existing open orders will be cancelled, and then all existing positions will be squared off. Ifassets
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. Orders will be sent to the broker directly, even in one-click execution mode. Also, see above the behaviour differences between the cases where the underlying broker does or does not support a native square-off method.
- Parameters
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. Using squaring off function repeatedly may lead to cancelling of exit orders triggered by a previous call.
Stoploss and Take-profit
Stoploss and Take-profit Exit Method
Add or Remove Stoploss
- TradingAlgorithm.set_stoploss(asset, method, target, trailing=False, on_stoploss=<function noop>, skip_exit=False)
Set the stoploss for a position, defined by an asset. Method can be one of PRICE, MOVE, PERCENT or AMOUNT. 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. Finally, AMOUNT will check the current unrealized profit and loss for the postiion an will trigger exit if breached against the target. If trailing is True, stoploss is updated at each lookup frequency. Stoploss will be reset each day in before trading start routine.
Once the target is hit, if skip_exit is False, the position will be squared off and the callable on_stoploss, if provided, will be called. If skip_exit is True, only the callable will be invoked and no position exit will take place. The callable must have a signature of f(context, asset), where asset is the asset for which the trigger has been hit.
- 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.
on_stoploss (callable) – A callable invoked if target is hit.
skip_exit (bool) – If true, no exit order will be triggered.
Warning
stoplosses are valid only for the day. Each day in before trading start, stoplosses are reset.
Important
If you are placing the entry order with a stoploss specified (if supported), 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. Also note, this function can only initiate the exit orders and cannot ensure actual executions of those orders.
Note
If skip_exit is False, the function will initiate exit. These exit orders (if any) will bypass any trading controls to make sure square-off orders are not blocked by such controls. Orders will be sent to the broker directly, even in one-click execution mode.
- TradingAlgorithm.get_current_stoploss(asset)
Return the currently defined stoploss for the asset, if any. Returns a tuple of None’s if not found.
Add or Remove Take-profit Target
- TradingAlgorithm.set_takeprofit(asset, method, target, on_takeprofit=<function noop>, skip_exit=False)
Set the take-profit for a position, defined by an asset. Method can be one of PRICE, MOVE, PERCENT or AMOUNT. 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. Finally, AMOUNT will check the current unrealized profit and loss for the postiion an will trigger exit if breached against the target. Take-profit will be reset each day in before trading start routine.
Once the target is hit, if skip_exit is False, the position will be squared off and the callable on_takeprofit, if provided, will be called. If skip_exit is True, only the callable will be invoked and no position exit will take place. The callable must have a signature of f(context, asset), where asset is the asset for which the trigger has been hit.
- Parameters
Warning
take-profits are valid only for the day. Each day in before trading start, take-profits are reset.
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. Also note, this function can only initiate the exit orders and cannot ensure actual executions of those orders.
Note
If skip_exit is False, the function will initiate exit. These exit orders (if any) will bypass any trading controls to make sure square-off orders are not blocked by such controls. Orders will be sent to the broker directly, even in one-click execution mode.
- TradingAlgorithm.get_current_takeprofit(asset)
Return the currently defined takeprofit for the asset, if any. Returns a tuple of None’s if not found.
- 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_exit_policy(cancel_orders=True, square_off=False)
Set the exit policy for this strategy. If cancel_orders is True and square_off is False, only the open order cancellation is attempted. If square_off is True, all open orders are cancelled and positions are squared off. The algo will wait for the changes to take effect before issuing an Algo End event to exit.
- Parameters
Important
The exit policy is triggered only during a graceful exit of the algo. Unexpected fatal errors or a crash may not trigger the exit policy.
Danger
This function only initiates square off and/or order cancellation. It does not and cannot ensure actual square-off or cancellation. 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. If the order cancellation or square-off takes too much time to get executed, the algo may exit before they are confirmed and the same may not be reflected in the final blotter.
- 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
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
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. If called from within a sub-context, will terminate only that subcontext.- 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)
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.
- 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_cooloff(assets=None)
Trigger a cool-off period. This will result in no further entry trades for the specified assets, or any assets if not specified. This cool-off period will last till the defined value (set by set_cooloff_period, defaults to 30 minutes).
- Parameters
assets (list) – List of assets (or None) to enable the cooloff for.
Important
If assets are specified, they should not be in rolling format for options, else they might be ignored.
- 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).
- TradingAlgorithm.set_initial_positions(positions)
Set starting positions for the algo. The argument positions must be a list of positions objects or a list of dictionaries that can be converted to a position objects. If the list contains dictionaries, each must have atleast asset, entry_price and quantity keys. The asset must be a valid symbol (and will be converted to an Asset object using the symbol function automatically) or an Asset object. The entry_price key must have the price at entry for the position, and quantity is a signed number of the position (negative for short position).
- Parameters
positions (list) – List of initial positions keyed by assets.
Important
The asset must match exactly with what is intended. For example, a rolling options asset may resolve to a different instrument. Also cash and margin traded equities are treated as different assets, even for the same symbol. For the later, you can either create the asset directly, or supply the product_type keyword (e.g. product_type=margin) to specify a margin equity product.
Warning
This method can only be called once in the initialize function. Calling it anywhere else will crash the algo. Also, for restarts, this call will be ignored, and the initial positions will be the last saved state of the algo.
- TradingAlgorithm.exit_when_done(error_message=None, check_orders=True, check_positions=True)
Exit from the current run by scheduling the algo end event, after checking if all open orders are complete and/ or all open positions are closed out. If both check_orders and check_positions are False, it is equivalent to the terminte API function with cancel_orders set as True. If called from within a sub-context, will terminate only that subcontext.
- Parameters
Note
If check_positions is True, it will open for all open positions to close out, but will not initiate (square-off) on its own. You must do that (call square-off or equivalent) before you call this API function with check_positions as True, otherwise it can potentially wait forever. Also, if check_positions is True, check_orders is automatically set to True (as otherwise the wait may not be meaningful).
Danger
This function only initiates termination but does NOT guarantee it.