Hello fellow investors,
If you are a robinhood user, you may have noticed that the platform does not support trailing stop loss orders. Using the power of google and the quantopian forums, I was able to write a simple code that would sell when a stock falls 3.5% from the highest price since I bought it. Can anyone review my code and give me suggestions on how to make it better? My ultimate goal is to make it so that the algorithm makes a trailing stop loss to whatever stock I have bought. Thank you in advance
def initialize(context):
context.stock = symbol("NAK")
set_benchmark(context.stock)
context.stop_price = 1.34
context.stop_pct = 0.965
def handle_data(context, data):
set_trailing_stop(context, data)
if data.current(context.stock, 'price') < context.stop_price:
order_target(context.stock, 0)
context.stop_price = 0
record(price=data.current(context.stock, 'price'), stop=context.stop_price)
def set_trailing_stop(context, data):
if context.portfolio.positions[context.stock].amount:
price = data.current(context.stock, 'price')
context.stop_price = max(context.stop_price, context.stop_pct * price)