Exiting on a sell stop

Does anyone know how one would code exiting on a sell stop in a strategy?





Thanks,   Jim

Blueshift does not support stop loss order type. If you wonder why, will be glad to explain if you put a comment below. Otherwise this reply explains how to code this behaviour.



The psudocode will go like this:

  1. On each iteration, check if you have any existing position at all on the asset that requires stop loss monitoring.
  2. if yes, fetch the last price for the asset
  3. check if this price is at or below your trigger price
  4. if yes, place an order to exit the position at market (or at a limit price).



    The function should look like this:



    def check_stop_trigger_and_exit(context, data, asset, trigger):

        positions = context.portfolio.positions

        if asset in positions:

            px = data.current(asset, 'close')

            if px <= trigger:

                order_target_percent(asset, 0)



    You need to call this function somewhere in handle_data (or a call chain within it), and pass on the arguments. Note, the asset argument is NOT a stock symbol, but an asset object. You can use the symbol function to convert a stock symbol to an asset object. This implementation assumes your position will be long (buy) and places a market order if your trigger price on the asset is breached. It is easy to handle the long/short cases, following this example.