There seems to be two issues. First, the
list_positions method may have a small delay in reporting current positions after a trade. Second, your logic seems to be flawed and not doing exactly what you intended.
Let’s look at the first issue and see if we can discern when the
list_positions method shows updated values. It appears you went long CNHI at 15:51:09 UTC when an order for 102 shares was filed. At that point you had 102 shares in your account. Then, at 20:51:10 UTC, these shares were sold. You then had 0 shares in your account. All good so far.
Then, at 20:51:18 UTC the algo placed another order to sell 102 shares. Presumably it checked
list_positions and still found 102 shares in your account (ie the positions hadn’t been updated). Not sure when it checked for updated positions but it was between 0-8 seconds after the first trade was placed. Then at 20:51:29 UTC you again placed an order to sell 102 shares. Again, presumably because
list_positions thought there were 102 shares there (however it may have thought there were -102 shares, more on that below). That was 19 seconds after the first ‘correct’ order. Now it gets interesting. At 20:51:34 an order was placed to sell 204 shares. This implies the
list_positions method showed an updated quantity. This was within 24 seconds of the first ‘correct’ order. So, it seems reasonable there may be some delay in updating the portfolio stats after a fill, and from the above time, but that delay in this case is less than 24 seconds.
Moving to the second issue. It appears your logic isn’t looking at the ‘sign’ or the ‘side’ (ie long or short) when trying to close the position. In looking at the 20:51:34 order to sell 204 shares, that probably should have been an order to ‘buy’ 204 shares to close a short position. I seems at that point you were short that many shares in your account.
Maybe put in a 1 minute or so delay before re-checking your
list_position logic, and also verify you are handling the ‘side’ properly when closing positions.