AutoTrader
AutoTrader copied to clipboard
Position size not fully filled when I switch position direction
Describe the bug
In backtest, when a new signal is triggered, and it has a different direction than the current open position, the order size, is not entirely filled
Expected behavior Like with tradingview pine scripts, when I switch position direction, the existing position is immediately closed and a new one is opened with the exact ordered size.
Below, a screenshot of orders history, in which I added two columns about the desired position size (My order size) and current balance
Configuration
Position size is calculated manually in each triggered signal
position_size = floor(self.broker.get_NAV()/self.data.Close[i])
Explanation In the second order, the script has ordered 1310 units, however, only 81 were executed. Of the 1310 units, 1229 were used to close the open position and the remaining ones have been executed in the new position.
I think that this behavior comes from broker.py in lines 300 to 303
I tried to manipulate my order size to close the existing one and entirely fill the new position, but I got errors of insufficient margin
Is there any way to overcome this behavior?
Thanks,
The easiest way to overcome this is to first close your existing position before placing the next order, which can be achieved with a 'close' order type. Simply return the closing order along with your new order. Some pseudo-code to do this:
# New signal
closing_order = Order(order_type='close')
new_order = Order(direction=1, size=position_size, ...)
...
return [closing_order, new_order]
In doing so, your existing position will be closed out before placing your next order.
You raise a good point about the margin requirements, I will have to look into adjusting the requirements when trading in the opposite direction to an existing position.
I applied your suggestions.
The positions were closed successfully, however, the available margin was not updated, as shown below:
I got many insufficient margin errors,
The solution I found to fix that is by forcing the margin update at the last line of _add_funds() in broker.py
Good pickup, and good suggestion. I will add that change in the next update. Thanks!
This has been patched in release of version 0.7.