Hi all, I can't seem to make this code work. I'm trying to buy shares when the price increases and sell when it decreases. However, I cannot make the code sell shares when I want. Any solutions?
def initialize(context):
context.security = sid(24)
def handle_data(context, data):
prices = data.history(context.security, "price", 5, '1m')
last_min = prices.iloc[-1] # get the price 1 min ago
# We also get the stock's current price.
current_price = data.current(context.security, 'price')
money = context.portfolio.cash
sell = context.portfolio.positions[sid(24)].amount
# If our stock is currently listed on a major exchange
if data.can_trade(context.security):
if current_price > last_min:
# Place the buy order
order_value(context.security, money)
log.info("Buying %s" % (context.security.symbol))
elif current_price < last_min:
# Sell all of our shares
order_percent(context.security, -1)
log.info("Selling %s" % (context.security.symbol))
print current_price