Hello,
I've been trying to get an answer regarding this issue, but still cannot figure it out. For my algo, I am trying to build a stop-loss logic as the following: (after a purchase is made)
- If stock percent change goes down by a certain percent (say X%), Sell all 100% using
#sell all
elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange < X_PercSell:
order_target_percent(context.stock1,0.0)
- If stock percent change goes up by a certain percent (say Y%), Sell half (50%) of current position using
#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)
The first stop-loss logic is working and selling exactly the purchased amount of shares. However, in the second stop-loss logic, it's not putting an order to exactly sell half the number of shares.
I tried another approach; to define the number of shares bought, then use half of the number to sell using the following:
#get the number of shares bought
num_of_shares = context.portfolio.positions[context.stock1].amount
half_num_of_shares = num_of_shares/2
#sell half
elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange > Y_PercSell:
order_target_value(context.stock1, -half_num_of_shares)
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 my description of the problem makes sense.