Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Robinhood Trailing Stop Loss

Hi, I'm a brand new to Quantopian. I'd like to create a simple algo that implements a simple trailing stop loss for my open positions on Robinhood. I want handle all the purchase orders through the Robinhood app and just use a Quantopian also, for my first one anyway, as a safety net that only executes sell orders for me.

Is this possible with Quantopian?

1 response

With Quantopian it seems possible to do a trailing stop loss. Here's the code I use...it's a cut-paste from another algorithm, so you might need to adapt it a tiny bit.
I assume it works with Robinhood but I've never used Robinhood so I can't really say.
If someone has a more elegant trailing stop loss implementation, I'd love to see it...good luck.


def initialize(context):  
    ...  
    context.mystock = sid(24)   # mystock = AAPL  
    context.trailing_stop_sell_pct = 0.9   # Sell if stock drops to this % of recent peak, e.g. 0.9 means 10% drop  
    context.trailing_stop_sell_price = 0   # initialize the trailing stop sell price for use in calculations below

def handle_data(context, data):  
    price = data.current(context.mystock, 'price')   # get current price of mystock this minute  
    # Set a trailing stop percent sell order  
        if context.mystock in context.portfolio.positions:  
            context.trailing_stop_sell_price = max(context.trailing_stop_sell_price, context.portfolio.positions[context.mystock].cost_basis * context.trailing_stop_sell_pct, price * context.trailing_stop_sell_pct)  
            if price < context.trailing_stop_sell_price:  
                order_target_percent(context.mystock, 0)  
                log.info('Trailing Stop Sell Order Triggered @ %s' % context.trailing_stop_sell_price)  
                context.trailing_stop_sell_price = 0   # reset value