So I think this is happening because of my second sell command. The first stop-less/sell logic sells all according to a certain condition. So order_target_percent(context.stock1,0.0) is working.
However, in the second stop-loss logic, I am trying to sell half of my current position when the price changes by a certain amount.
#sell all
elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange < X_PercSell:
order_target_percent(context.stock1,0.0)
#sell half
elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange > Y_PercSell:
for stock in context.portfolio.positions:
order_target_percent(stock, -0.5)
log.info("Sell 50% with purchase price = "+str(costBasis) + " and current price = " + str(CurPriceClose))
It's selling exactly what I can buy for 50% of my portfolio.
I tried another approach; to define the number of shares bought, then use half of the number to sell using the following:
num_of_shares= context.portfolio.positions[context.stock1].amount
elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange > Y_PercSell:
half_num_of_shares = num_of_shares/2
log.info("Half of Number of Shares = "+str(half_num_of_shares))
order_target_value(context.stock1, -half_num_of_shares)
context.trans_mode = "Sell_Half_Mode"
but it's still not working. For example, it purchases 120 shares at first, then when I am trying to sell half, it defines half_num_of_shares = 60.
but then when it commits to the sell half, it sells 180 shares instead of 60. In other words, it is adding the number of shares I want to sell to the number of shares bought 120+60. I don't understand why this is happening.
Hope that makes sense.