Broker: how to force selling multiple securities to free up cash before buying in the same bar?
suppose there is no cash in the account but we have 10 long positions. The next open we have to sell 5 securities at market and to buy 5 securities at market with the money we should get from the selling.
Is it possible to force the broker to execute all the sell orders (market) before the buy orders to free up cash and avoid to end with 5 rejected orders because the account has not enough cash?
I wouldn't mind being unable to execute one of the buy orders because after all the selling there is not enough cash. In reality I will do all the selling before the buying so I can assume I will able to get a fill on the majority of buy orders. The selling and the buying must be in the same bar at open, I will increase the slippage because of the delay in filling the longs.
On the same bar issue sell orders first, then issue buy orders. If it will be enough cash after selling, your buy orders will be executed.
btuses first in, first out approach on the orders execution.
What is the best pattern to do it? To hold all the signals in the strategy until all the data feeds are processed and then send all the sell order first?
Or we should subclass the brocker and modify its logic to process the sell orders first?
Right now I am keeping all the orders on hold until all the data are processed, then I send them to the broker like this:
self.long_signals =  self.short_signals =  # Logic for i, s in enumerate(self.datas): if not self.positions[s]: if s.membership: self.long_signals.append(s) continue if self.positions[s]: if not s.membership: self.short_signals.append(s) continue # Send orders to the broker. for s in self.short_signals: self.orders[s] = self.sell(s) for s in self.long_signals: self.orders[s] = self.buy(s)
You can send it like you are doing, or inside the data processing loop. Doesn't matter.
By "the data processing loop" do you mean the next method? The code above is inside next.
I meant this loop
for i, s in enumerate(self.datas):
but after more thoughts I think your way is correct one. Otherwise it will be a mix of sell and buy orders.