AutoTrader icon indicating copy to clipboard operation
AutoTrader copied to clipboard

Position size not fully filled when I switch position direction

Open SeifallahSnoussi opened this issue 2 years ago • 3 comments

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

image

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

image

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,

SeifallahSnoussi avatar Jul 08 '22 20:07 SeifallahSnoussi

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.

kieran-mackle avatar Jul 10 '22 21:07 kieran-mackle

I applied your suggestions.

The positions were closed successfully, however, the available margin was not updated, as shown below:

image

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 image

SeifallahSnoussi avatar Jul 10 '22 23:07 SeifallahSnoussi

Good pickup, and good suggestion. I will add that change in the next update. Thanks!

kieran-mackle avatar Jul 10 '22 23:07 kieran-mackle

This has been patched in release of version 0.7.

kieran-mackle avatar Aug 13 '22 00:08 kieran-mackle