Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Example of an intraday trailing stop loss

Summary
Because theres no built in order method for a trailing stop loss, an approach was developed to address this issue, heres a quick summary of how it works

Note: This method was developed assuming a holding period of less than a day, it begins 10 minutes after the morning bell & ends 10 minutes before close. There should be no issue converting this to compensate for the time since buying the position

How it works
1. The current price is tracked
2. The time since market open is tracked to later be referenced in data.history
The get_datetime function is referenced, converted to a string, sliced to find desired fields, then split between hours and minutes
The hours and minutes are then converted to integers & adjusted to account for the time of market open (hours set to 0 at market open and multiplied by 60 to convert to minutes).. (minutes set to 0 at market open) both hours and minutes are then added

  1. data.history is then referenced using the time since market open in the window_length field.
    This is then converted to a list and pythons max( ) function is used to find the highest price since market open
  2. Actually the rest is explained in the algo
4 responses

Here are a few changes I made

  • Added a stop loss decay multiplier... every X minutes the stop loss gets Y% smaller
    In this example I had the stop loss get 0.085% smaller every 12 minutes
  • The stop loss now iterates over the whole portfolio

*I haven't completely proofread & tested it to see if either of the two are working the way they should

You should probably check for any outstanding (ie unfilled) orders before placing any more orders. This is true even when selling all. If you sell twice, you will end up shorting the security.

Thats a good point. I should also note that this is just the concept & the algo as a whole is definitely not made for live trading

If the stop loss is not triggered on day T, the position is closed on the morning of T+1. Subsequent buy open order does not occur until T+2. The problem with this, is there is no "open" exposure on T+1. To avoid this, you can 1) close out the position at the end of day T and open on morning of T+1 or 2) let the open position continue to "run" on T+1, until the stop is triggered.

Another observation, it seems "take profit/loss" (i.e. sell order) happens either when there is a stop loss trigger or time trigger. There is no profit trigger to mitigate the loss trigger. For the algo, to lock in profits, shouldn't you include condition where there take profit (e.g. +1%) trigger?