Back to Community
How do I implement a stop loss?

Hi everybody,

I am trying to implement a stop loss to this strategy. However, after looking on the documentation and on the forum, I am still not quite sure how I should go about it.
Should I store the buy (and sell) price in a variable and then check manually every day if the current price has risen above or fallen under my stop loss? Or should I just use a StopOrder type of order? (if that's the case I don't know how I would implement it)

I need your advice, thank you in advance!
D

Clone Algorithm
0
Loading...
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
import quantopian.algorithm as algo
import talib as ta

def initialize(context):
    
    context.aapl = sid(24)
    context.trade_confirmation = True
    
    algo.schedule_function(
        trade,
        algo.date_rules.every_day(),
        algo.time_rules.market_open(minutes=5))
    
    context.slow_ema_period = 21
    context.fast_ema_period = 5
    
    set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0))


def trade(context, data):
    #get some data to perform calculations
    price_history = data.history(assets=context.aapl, fields='close',
                                 bar_count=30, frequency='1d')
    
    #calculate exp moving averages using ta-lib
    slow_ema = ta.EMA(price_history, timeperiod=context.slow_ema_period)[-1] #21d exp mov avg
    fast_ema = ta.EMA(price_history, timeperiod=context.fast_ema_period)[-1] #5d exp mov avg
    
    #check if the asset can be traded
    context.trade_confirmation = data.can_trade(context.aapl)
    
    #if 5d avg goes above the 21d avg, go all in in apple
    if fast_ema > slow_ema and context.trade_confirmation:
        
        order_id = algo.order_target_percent(asset=context.aapl, target=1.0)
        context.buy_order =  algo.get_order(order_id)
        log.info(context.buy_order)
    
    #if the 5d avg goes below the 21d avg, short the stock
    elif fast_ema < slow_ema and context.trade_confirmation:
        
        order_id = algo.order_target_percent(asset=context.aapl, target=-1.0)
        context.sell_order =  algo.get_order(order_id)
        log.info(context.sell_order)
There was a runtime error.
1 response

This post has an example with a trailing stop. It adresses an issue with stock splits and stops, which is the reason why I wouldn't recommend stop orders (in real life brokers often just cancel stop orders after splits).