kieran-mackle / AutoTrader

A Python-based development platform for automated trading systems - from backtesting to optimisation to livetrading.
https://kieran-mackle.github.io/AutoTrader/
GNU General Public License v3.0
945 stars 217 forks source link

Position size not fully filled when I switch position direction #39

Closed SeifallahSnoussi closed 2 years ago

SeifallahSnoussi commented 2 years ago

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,

kieran-mackle commented 2 years ago

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.

SeifallahSnoussi commented 2 years ago

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

kieran-mackle commented 2 years ago

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

kieran-mackle commented 2 years ago

This has been patched in release of version 0.7.