Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    What happens to TP and SL with trades when closed.

    Indicators/Strategies/Analyzers
    2
    5
    163
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Pierre Cilliers 0
      Pierre Cilliers 0 last edited by

      Hi all.
      @backtrader @emr

      Just 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 using self.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?

      E 1 Reply Last reply Reply Quote 0
      • E
        EMR @Pierre Cilliers 0 last edited by

        @pierre-cilliers-0 Salut Pierre !
        Sorry to give an incomplete answer, I am not sure so the best is to test, this can be done by placing every order in a list and checking their status, and / or track orders status using the notify_order method.
        An example for notify order :

            def notify_order(self, order):
                print('{}: Order ref: {} / Type {} / Status {}'.format(
                    self.data.datetime.date(0),
                    order.ref, 'Buy' * order.isbuy() or 'Sell',
                    order.getstatusname()))
        

        An example for order list (for some reasons I have sometimes to cancel all orders)

                for ordre in self.orderslist:
                    if ordre.status in [ordre.Submitted, ordre.Accepted]:
                        self.logordres.info(f"ordre actif : {ordre.ref} statut : {ordre.status}")
                        self.cancel(ordre)
                        self.logordres.info(f"ordre annulé : {ordre.ref} statut : {ordre.status}")
        
        Pierre Cilliers 0 2 Replies Last reply Reply Quote 0
        • Pierre Cilliers 0
          Pierre Cilliers 0 @EMR last edited by

          @emr

          Awesome, thanks.
          Will refer back if I get an answer. (hoping it closes automatically)

          1 Reply Last reply Reply Quote 0
          • Pierre Cilliers 0
            Pierre Cilliers 0 @EMR last edited by

            @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 specific tradeid with

            self.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 this

            self.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 the tradeid when creating the order.

            E 1 Reply Last reply Reply Quote 1
            • E
              EMR @Pierre Cilliers 0 last edited by

              @pierre-cilliers-0 Thanks for your answer and the code.
              I wrote a cancel method which parse all existing orders and close active ones, but yours is more precise and smarter.

              1 Reply Last reply Reply Quote 0
              • 1 / 1
              • First post
                Last post
              Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors