hi, yes, resetting the stop order can be tedious. I am trying to implement a trailing stop and having a problem as well.
I am only buying 2 securities and setting a trailing stop that is in effect until 3:15pm. But the stop does not trail, it is only set once and they reiterated each minute, this just causes me to sell at each minute.
Would anyone be willing to look over my code and see where I am going wrong? I have some decent logs. I am starting to think there is a problem returning the object or something.
code below:
import talib
import datetime
import time
import pytz
from pytz import timezone
import brokers.ib
from brokers.ib import IBExchange
def initialize(context):
log.info(str(get_datetime("US/Eastern")) + ": initializing algorithm")
context.stock = sid(8554) # SPY
context.ETFs = sid(42471),sid(42472) # UWTI and DWTI
# Add other 3x ETF's later
set_benchmark(context.stock) # comparing against SPY
context.stop_price = 0
context.stop_pct = 0.99 # sets 1% trailing stop-loss
log.error
schedule_function(buy, date_rules.every_day(), time_rules.market_open(minutes=30),
half_days=True)
# I want to schedule to buy ETFs everyday 30min after the open at market price
schedule_function(sell, date_rules.every_day(), time_rules.market_close(minutes=45),
half_days=True)
# I want to schedule to sell the ETFs everyday, if no stop triggered, 45min before close
def handle_data(context, data):
set_trailing_stop(context, data)
for sec in context.ETFs:
if data[sec].price < context.stop_price:
log.info(str(get_datetime("US/Eastern")) + ": selling security [" + str(sec.symbol) + "] | current price: " + str(data[sec].price) + " < stop price: " + str(context.stop_price))
order_target(sec, 0)
context.stop_price = 0
record(UWTI_price=data[sid(42471)].price,
DWTI_price=data[sid(42472)].price,
stop=context.stop_price)
def buy(context, data):
log.info(str(get_datetime("US/Eastern")) + ": placing order for $5000 of UWTI and DWTI")
order_value(sid(42471), 5000, style=MarketOrder(exchange=IBExchange.IEX))
order_value(sid(42472), 5000, style=MarketOrder(exchange=IBExchange.IEX)) # order value orders a $5000 value of stock, roughly, it rounds down. In this case, about $5000 of UWTI and DWTI are bought.
def sell(context, data):
log.info(str(get_datetime("US/Eastern")) + ": selling current holdings of UWTI and DWTI")
order_target(sid(42471), 0, style=MarketOrder(exchange=IBExchange.IEX))
order_target(sid(42472), 0, style=MarketOrder(exchange=IBExchange.IEX)) # order target uses a target number of shares. In this case, sell in order to have 0 shares left, closes the positions in UWTI and DWTI
def set_trailing_stop(context, data):
for sec in context.ETFs:
if context.portfolio.positions[sec].amount:
price = data[sec].price
context.stop_price = max(context.stop_price, context.stop_pct * price)