Backtrader python client library Bracket orders limit is not working
-
Hello All,
I am using Backtrader the testing framework for the stocks strategyI want to test my strategy for stock order placing, I want to place long(buy) order so for that I will use the bracket_order method in which I will set a limit
- at which price I want to buy the stock
- at which price I want to sell the stock after buy order limit is placed
- at which price I want to stop loss if buy order is placed and stock price is decreasing
here is the code
cerebro = bt.Cerebro() cerebro.addstrategy(MyStrategyWrapper) cerebro.adddata(data=historical_stock_data_for_the_day) cerebro.broker.setcash(1000) cerebro.run()
this is the code in which I add my strategy class and the data historical_stock_data_for_the_day for the stock
the format for the historical_stock_data_for_the_day will be like
[{2389839283: 120}, {2389839211: 130}, ....... n]
where the numbers like 2389839283 is the timestamp at which the stock price is 120when I call the cerebro.run() it will call my strategy class's method def next
for the each dict in listmy strategy class is
class MyStrategyWrapper(bt.Strategy): params = () def __init__(self, *args, **kwargs): self.is_ordered = None def next(self) -> None: """This is the first method which is executed on cerebro.run() method""" now = self.datas[0].datetime.datetime(0) last_price = self.datas[0].close[0] if self.is_ordered: print("last price ", last_price) # after placing an order here i get the last price (77.91) at which i set the limit to buy asset more than 10 times # that means after placing the order the stock reach that price return # ... # My some logic if it fullfill all conditions i want to place an bracket order # ... time_before = None if large_enough_5_min: time_before = True if time_before: brackets = self.buy_bracket(limitprice=78.99, price=77.91, stopprice=77.37, size=1, exectype = bt.Order.Limit) # (When i place the order from here limit is not reaching and order is buying stock at 77.62 instead of 77.91) self.is_ordered = True def notify_order(self, order): """callback when order is sent and any order related update""" if order.status in (order.Canceled, order.Margin, order.Rejected): return if order.status in (order.Submitted, order.Accepted): return if order.status in (order.Completed,): order_type = "long" print("Order is placed at the given limit") def notify_trade(self, trade): """callback when full trade is completed""" if not trade.isclosed: return print("Trade is completed")
i tried by changing the limit and checked on the official docs https://www.backtrader.com/docu/order-creation-execution/bracket/bracket/
to place a bracket order, also checked by placing manually order but facing issue with the limit.
please let me know if I missed something or doing wrong in this code
Thank you