Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Newbie need helps with Migration an algo from quantopian1 to the current quantopian

Hi Guys,

I am a newbie here and trying to add a trailing stop-loss algo from this post https://www.quantopian.com/posts/trailing-stop-loss
to my algo, but the code is pretty old now. If there's anyone who could help me with the migration of the code below, it would be highly appreciated. Thank you so much :)

Trailing stop test (minute)

def initialize(context):
context.stock = symbol("SPY")
set_benchmark(context.stock)
schedule_function(func=enter, time_rule=time_rules.market_close(minutes=1))
schedule_function(func=set_trailing_stop, time_rule=time_rules.market_close(minutes=1))
context.stop_price_bull = 0
context.stop_price_bear = 0

Trailing stop percentage

context.stop_pct_bull = 0.90  
context.stop_pct_bear = 0.90  

def enter(context, data):
#Moving averaged to determine trend (size of stop-loss and entry)
ma_trend1 = data[context.stock].mavg(200)
ma_trend2 = data[context.stock].mavg(400)
#Moving averages for entry
ma_slow_bull = data[context.stock].mavg(50)
ma_slow_bear = data[context.stock].mavg(100)
ma_fast = data[context.stock].mavg(3)
# record(mavg400=data[context.stock].mavg(400), mavg200=data[context.stock].mavg(200), mavg50=data[context.stock].mavg(50), mavg3=data[context.stock].mavg(3))

set_trailing_stop(context, data)  
if ma_trend1>ma_trend2:  
   if data[context.stock].price < context.stop_price_bull:  
    order_target(context.stock, 0)  
    context.stop_price_bull = 0  

# Buys when stock price comes above slow mavg
elif ma_fast > ma_slow_bull:
order_target_percent(context.stock, 1.0)
elif ma_trend1 ma_slow_bear:
order_target_percent(context.stock, 1.0)

   # record(price=data[context.stock].price, stop=context.stop_price_bull)  

def set_trailing_stop(context, data):
if context.portfolio.positions[context.stock].amount:
price = data[context.stock].price
context.stop_price_bull = max(context.stop_price_bull, context.stop_pct_bull * price)
context.stop_price_bear = max(context.stop_price_bear, context.stop_pct_bear * price)

def handle_data(context, data):
pass