What happens to TP and SL with trades when closed.
-
Hi all.
@backtrader @emrJust a quick one.
I create a
buy
with TP and SL trade as follows:self.buy_bracket(tradeid = key, exectype = bt.Order.Market, price = close_price, size = 0.01, limitprice = tp_price, stopprice = sl_price)
I understand that a
buy_bracket
creates 3 x orders:- market order for the entry,
- limit order for TP, and a
- stop order for SL.
If I, for example, manually close the
buy
trade by usingself.close()
, like this:self.close(tradeid = key, size = 0.01)
what happens to the TP and SL orders in the backtrader backend?
I have decoded and tracked the closing of trades and I can clearly see that the trade gets closed by the following
notify_trade()
method:def notify_trade(self, trade): if trade.justopened: print(f'New trade {trade.tradeid} opened') elif trade.isclosed: print(f'Trade {trade.tradeid} recently closed')
Does the TP and SL orders get cancelled automatically or do I have to
self.cancel()
these corresponding orders when closing the trade? -
@emr
Awesome, thanks.
Will refer back if I get an answer. (hoping it closes automatically) -
@emr
Sorry for the delayed answer to my question but here it goes:
For
buy_bracket
orders it generates 3 x orders:-
market order for the entry,
-
limit order for TP, and a
-
stop order for SL.
The market order is triggered at market price, therefore becomes an active trade (can track this in
notify_trade()
). You can successfully close this position by pointing to the specifictradeid
withself.close(tradeid = key, size = 0.01)
I can confirm that the remaining 1. limit order for TP and 2. stop order for SL are still dangling in backtrader backend. These need to be removed if you close the market order otherwise they will be triggered at their limit price at a later stage.
The manner in which I did this is tracking your orders in a
self.buy_trade
dictionary.
For example, I populate this dictionary like thisself.buy_trade[key] = self.buy_bracket(tradeid = key, exectype = bt.Order.Market, price = close_price, size = 0.01, limitprice = tp_price, stopprice = sl_price)
This self.buy_trade[key] dictionary contains three backtrader object, representing the market order, stop order and limit order, respectively.
You can track these limit and stop orders manually and delete them as follows:
self.cancel(self.buy_trade[key][1]) # cancelling SL order self.cancel(self.buy_trade[key][2]) # cancelling TP order
Therefore if you want to delete an active trade, it might look like this:
self.close(tradeid = key, size = 0.01) self.cancel(self.buy_trade[key][1]) # cancelling SL order self.cancel(self.buy_trade[key][2]) # cancelling TP order
where
key
points to thetradeid
when creating the order. -