Order Execution
-
Hi,
I am trying to execute buy/sell orders using all my available capital
def next_open(self): if not self.position: if self.data_pred == 1: # calculate the max number of shares ('all-in') size = int(self.broker.getcash() / self.datas[0].open) -1 # buy order self.log(f'BUY CREATED --- Size: {size}, Cash: {self.broker.getcash():.2f}, Open: {self.data_open[0]}, Close: {self.data_close[0]}, Amount:{cerebro.broker.getvalue()}') self.buy(size=size) else: if self.data_pred == 0: # sell order self.log(f'SELL CREATED --- Size: {self.position.size}, Cash: {self.broker.getcash():.2f}, Open: {self.data_open[0]}, Close: {self.data_close[0]}') self.sell(size=self.position.size)
I'm calculating the size as my available cash / Open price.
cerebro = bt.Cerebro(stdstats = False, cheat_on_open=True) cerebro.addstrategy(MLStrategy) cerebro.adddata(data_bt, name='AAPL') cerebro.broker.setcash(1000.0) cerebro.broker.setcommission(commission=0.001) cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio') # run the backtest print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) backtest_result = cerebro.run()
I have cheat_on_open available although I do not fully understand it's functionality. I want the backtesting algo to Buy if pred= 1.
The size calculation is correct but I am getting a message that order is in margin
# report failed order elif order.status in [order.Canceled]: self.log('Order Canceled') elif order.status in [order.Margin]: self.log('Order Margin') elif order.status in [order.Rejected]: self.log('Order Rejected')
Can you kindly explain why order is in margin when I have cash available? This happens randomly.
Thank you,
W -
@waterloo said in Order Execution:
stdstats
Update - With commissions set to 0, it works. So I believe the issue is that I'm getting a lot of commission fees as I'm making profit and buying more shares. Is there a way of calculating the size so that I invest all my available capital (whilst accounting for commission fees as well)?
Thank you