can anyone help figure out this run-time error i get in line 62? its under Def_Handle. The line with the code toward the bottom.
set_trailing_stop(context, data):
I think its close to working right but I cant figure out this last bit of my trailing stop loss function, thanks!
here is the code:
def initialize(context):
log.info(str(get_datetime("US/Eastern")) + ": initializing algorithm")
context.stock = sid(8554) # SPY
context.ETF = sid(42477), sid(42470) # ugaz and dgaz
set_benchmark(context.stock) # comparing against SPY
context.stop_price = 0
context.stop_pct = 0.99
schedule_function(check_condition,
date_rules.every_day(),
time_rules.market_open(minutes=15),
half_days=True)
schedule_function(sell,
date_rules.every_day(),
time_rules.market_open(minutes=345),
half_days=True)
def check_condition(context, data):
global ugaz_OP
global ugaz_CP
price = history(bar_count=1, frequency='1m',
field='open_price').loc[14]
for UGAZ in context.ETF:
ugaz_OP = price[UGAZ][-14] #[-14] pulls price 14min ago
ugaz_CP = price[UGAZ][-1] #[-1] pulls the price 1min ago
if ugaz_CP - ugaz_OP > 0:
log.info(str(get_datetime("US/Eastern")) + " bought UGAZ 15min")
order_value(sid(42477), 5000,
style=MarketOrder(exchange=IBExchange.IEX))
elif ugaz_CP - ugaz_OP < 0:
log.info(str(get_datetime("US/Eastern")) + " bought DGAZ 15min")
order_value(sid(42470), 5000,
style=MarketOrder(exchange=IBExchange.IEX))
def sell(context, data):
if context.portfolio.positions[sid(42477)].amount:
log.info(str(get_datetime("US/Eastern")) + ": selling UGAZ 45min")
order_target(sid(42477), 0,
style=MarketOrder(exchange=IBExchange.IEX))
if context.portfolio.positions[sid(42470)].amount:
log.info(str(get_datetime("US/Eastern")) + ": selling DGAZ 45min")
order_target(sid(42470), 0,
style=MarketOrder(exchange=IBExchange.IEX))
def handle_data(context, data):
for ETF in context.ETF:
set_trailing_stop(context, data):
if data[context].price < context.stop_price:
order_target(context.ETF, 0)
context.stop_price = 0
def set_trailing_stop(context, data):
for ETF in context.ETF:
if context.portfolio.positions[context.ETF].amount > 0:
price = data[context.ETF].price
context.stop_price = max(context.stop_price, context.stop_pct * price)
record(price=data[context.ETF].price,stop=context.stop_price)