Buy and Sell Orders Execution order
I'm starting using backtrader, and I am running into an issue with orders execution. Here's my strategy:
- I define a set of stocks I want to invest on
- I select the two best according to some indicators, and invest 50% of my available cash on each. Everything works well until this point.
- At some point, I determine that the stocks I have in positions are not the right ones anymore, and I want to change my position. So I send sell orders to close the 2 existing positions, and then 2 buy orders to invest on 2 new stocks. These orders are setup to be executed on next day close.
My issue is sometimes, one of the buy order is treated before the sell orders. Then the order gets rejected because I don't have the cash available.
Is there a way to work around this please ?
Thank you !
Orders are executed (and evaluated for admission simulating pseudo-execution) on a FIFO basis, just like in a regular exchange.
You have to properly schedule the order. If your sell orders are sent before the buy orders and are
Marketorders, they will ALWAYS be executed before the buy orders.
Thanks for your reply. But I would like these orders to be executed on the close, next day. So I currently send my orders as "CLOSE". Can we achieve the same behavior ?
Perhaps the FIFO order queue is maintained for each stock? And because you have more than one stock, the order of execution is defined by the list of stocks and not by the placement of buy and sell orders (the FIFO queue is valid only for 1 stock, not for a list of stocks)?
The FIFO order (in backtesting) is a general one for good reasons
- If there were independent FIFO queues ... which one would have the preference? Alphabetic ordering?
- General FIFO ordering ensures that selling something ensures funds are freed for buying something then.
But I would like these orders to be executed on the close, next day. So I currently send my orders as "CLOSE". Can we achieve the same behavior ?
The question as formulated makes no sense. The only thing that matters in what you previously described is ordering.