How to buy on close and sell on the next day open with daily candles?
-
Hi, I'm having trouble with my next(self) function when it comes to buying at the close on day 1 and selling on the open of day 2. Can anyone help?
def next(self): self.log('Close, %.2f' % self.dataclose[0]) #print(len(self)) #print(self.order) #print(self.position) if self.position.size == 0: if round((self.data.close[0]-self.data.close[-1])/self.data.close[-1],4) >= ((self.params.perc/100)+0.005): amount_to_invest = (self.params.order_percentage * self.broker.cash) self.size = math.floor(amount_to_invest / self.data.close[0]) self.log("Buy {} shares at {}".format(self.size, self.data.close[0])) #print("Buy {} shares of {} at {}".format(self.size, symbol, self.data.close[0])) self.buy(exectype = bt.Order.Market,size = self.size) self.order = self.buy() if self.position.size > 0: if len(self) >= (self.bar_executed): #print("Sell {} shares of {} at {}".format(self.size, symbol, self.data.close[0])) self.log("Sell {} shares at {}".format(self.size, self.dataopen[0])) self.order = self.close(coo=True,exectype = bt.Order.Market)
The code will buy at the close and sell the next day, but its selling at the close of the next day instead of the open.... My log is the open is correct, but I cannot get backtrader to sell at that price. Any suggestions?
-
@zeromodz I assume you want to work on regulated stock market. When you know what is the price at the close, the candle is already finished, the market is already closed, so it is complicated to buy the close.
One way to get around this logical issue would be to process also a lower timeframe, and to take into account not the daily closing price, but the price 5mn or 10mn before the close.
Another way would be to use the cheat-on-close parameter : see : https://www.backtrader.com/docu/broker/
See also cheat on open on the same page. -
@zeromodz Have a look at cerebro.broker.set_coc(True) Cheat on close.