Trade max amount when flipping from short to long or vice versa
bmex test last edited by
Having read through probably most other topics related to this I still haven't come across a solution to ensure that when flipping from short to long or vice versa the max amount is traded.
Possibly I'm struggling because the open PnL of the short/long position needs to be taken into account to know how much can be bought/sold after the short/long position is closed and the PnL is realised.
However, I think there should be a simple solution to ensure the max amount is traded.
Entering the first position with the max amount is as simple as (for e.g. a sell):
size = float(self.broker.get_cash() / self.dataopen) self.order = self.sell( coo=True, exectype=bt.Order.Market, size=size )
Now if I'd like to flip from e.g. short to long I tried the following:
trade_size = 2 * float(self.broker.getvalue() / self.dataopen) self.order = self.buy( coo=True, exectype=bt.Order.Market, size=trade_size )
This however results in the buy order being rejected sometimes but I struggle to see why.
How can I ensure that when flipping from short to long that the max possible amount is traded?
Thanks and happy new year!
run-out last edited by
This code shouldn't run.
If you are trying to get 100% of your cash invested, this is very challenging since the markets move after an order is issued. Your orders are most likely rejected for this reason with a 'margin' status shown.
Typically, it's better to target investing an amount slightly less than 100%, depending on the volatility and time period of your instrument.