I have the following test code:
def handle_data(context, data):
for stock in context.stocks:
h = history(bar_count=1,frequency="1d",field="high")
l = history(bar_count=1,frequency="1d",field="low")
# Check if we are already in a position.
pos = context.portfolio.positions[stock]
# Handle open positions
if pos.amount != 0:
# Check stop-loss value and close if breached.
if data[stock].price/pos.cost_basis-1 > context.max_loss:
order_target(stock,0)
context.open_trade_dt[stock.sid] = None
# Check if we have passed the max duration to take profit/loss.
if data[stock].datetime - context.open_trade_dt[stock.sid] > dt.timedelta(hours=context.max_duration):
order_target(stock,0)
context.open_trade_dt[stock.sid] = None
# Or see if we meet Long trade criteria
elif data[stock].price > h[stock][0]:
order(stock,int(context.max_pos_value/data[stock].price))
context.open_trade_dt[stock.sid] = dt.datetime.now()
elif data[stock].price < l[stock][0]:
order(stock,-int(context.max_pos_value/data[stock].price))
context.open_trade_dt[stock.sid] = dt.datetime.now()
The Build is failing with:
2 Error Runtime exception: TypeError: unsupported operand type(s) for -: 'Timestamp' and 'NoneType'
But the assignment is clearly made when the code actually opens a trade. Any reason for this?