market buy orders not being executed when order_size is above a certain value
-
Hi,
I am experiencing strange behaviour where my orders are not being excecuted if my order size is too big.
I am using the following strategy that uses ATR to choose a stop loss and a take profit. I then calculate the order size so that only 1% of bank is risked at a time.
However none of my orders are executed.
My strategy code is:
def calculate_trade_amount(current_cash, current_price, diff, loss_frac=0.01): loss_proportion = diff / current_price bank_proportion = loss_frac / loss_proportion target_bank = current_cash * bank_proportion return round(target_bank / current_price, 5) class Mystratgey(bt.Strategy): def __init__(self): self.take_prof = None self.last_close_winner = False self._allow_entry = True self.long_exposure = False def notify_order(self, order): if order.status == order.Cancelled: order_type = 'buy' if order.isbuy() else 'sell' print(f'CANCEL@price: {order.executed.price} {order_type}') return if order.status != order.Completed: return # Discard any other notification order_price = order.executed.price if not order.isbuy(): self.last_sell = self.datetime.datetime(ago=0) print(f'[{self.last_sell}] SELL@price: {order_price}') return # We have entered the market self.last_buy = self.datetime.datetime(ago=0) print(f'[{self.last_buy}] BUY @price: {order_price}') def entry_signal(self) -> bool: return self.data.indicator > 2 def _enter_bracket_position(self): mainside = self.buy(size=self.order_size, transmit=False) self.stop_loss_order = self.sell(price=self.stop_price, size=self.order_size, exectype=bt.Order.Stop, transmit=False, parent=mainside) self.take_prof_order = self.sell(price=self.take_prof, size=self.order_size, exectype=bt.Order.Limit, transmit=True, parent=mainside) def _enter_atr_bracket(self): self.diff = float(self.data.ATR[0]) self.stop_price = self.data.close[0] - self.diff self.take_prof = self.data.close[0] + 2*self.diff self.order_size = calculate_trade_amount(self.broker.getcash(), self.data.close[0], self.diff) self._enter_bracket_position() def next(self): if not self.position and self.entry_signal(): self._enter_atr_bracket()
However when i modify the assignment of
self.order_size
toself.order_size = calculate_trade_amount(self.broker.getcash(), self.data.close[0], self.diff) / 10
Some of my orders start to get executed. I am wondering why I am experiencing this strange behaviour?
-
sometimes risk-based size calculations can return position size to open more than cash available. therefore you need to add simple check that calculated
size
is less thancurrent_cash / current_price
.i would recommend you to put more logging to figure out what is going on in your script.
-
@ab_trader Ah of course - I was trying to spend more money than I had. Thanks for the pointer.