Backtrader Community

    • 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/

    How do I set up correct position close logic?

    General Code/Help
    7
    15
    6004
    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.
    • B
      BernardLin last edited by BernardLin

      Hi I am trying to backtest my code but now I don't know how I can correctly ask the backtrader to close an existing position for me. I tried looking at the Backtrader blogs but didn't find a page that clarifies how I should do it. Thus I would appreciate immensely if anyone can offer some insights!

      def next(self): # input trade logid in this function
          self.log('Close, %.2f' % self.dataclose[0])
      
          if self.order:
              return
      
          if not self.position:
      
              if self.rsim30<30 and self.rsim60<30:
      
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  self.order = self.buy()
      
              elif self.rsim30>70 and self.rsim60>70:
                  self.log('SELL CREATE, %.2f' % self.dataclose[0])
                  self.order = self.sell()
          
          if self.position:
              if self.rsim30>70 and self.rsim60>70:
      
                  self.close(exectype=bt.Order.Close)
                  self.log('BUY POSITION CLOSED, exectype Close, price %.2f' %
                           self.data.close[0])
              if self.rsim30<30 and self.rsim60<30:
      
                  self.close(exectype=bt.Order.Close)
      
                  self.log('SELL POSITION CLOSED, exectype Close, price %.2f' %
                           self.data.close[0])
      

      My trade logic is as above, I am not sure if I am opening long/short positions at the current available market prices. can someone just check it for me? Thanks!

      And my position-closing logic don't seem to work the way I want, that is, if RSIm30>70 and RSIm60>70, close my existing long positions at market, if RSIm30<30 and RSIm60<30. close my existing short positions at market. How should I write my codes here? Thanks so much for the help beforehand!!!

      @backtrader I know this should be obvious, but I swear I have looked through the website and other backtrader strategy files and can't find how I can close long positions and short positions separately under different conditions, please help! Thanks!

      K 1 Reply Last reply Reply Quote 0
      • B
        BernardLin last edited by BernardLin

        @backtrader @ab_trader I know this should be obvious, but I swear I have looked through the website and other backtrader strategy files and can't find how I can close long positions and short positions separately under different conditions, please help! Thanks!

        1 Reply Last reply Reply Quote 0
        • A
          ab_trader last edited by

          I've used self.close() to close any type of the position with the marker order.

          • If my answer helped, hit reputation up arrow at lower right corner of the post.
          • Python Debugging With Pdb
          • New to python and bt - check this out
          B 1 Reply Last reply Reply Quote 0
          • B
            BernardLin @ab_trader last edited by BernardLin

            @ab_trader So it is self.close(), not self.buy(exectype=bt.Order.Close) right? But what if I have both existing long and short positions, I wanna close only the long position under one circumstance and short under another, how do I ask Backtrader to distinguish between them?

            For example, if I wanna close a long position, and specify in the command that close only a long position, should I use
            self.buy(exectype=bt.Order.Close)
            or
            self.sell(exectype=bt.Order.Close)
            or
            self.close() ??? (but this one seems to close all existing long and short positions, can I specify, for example, asking it to close only long positions, leaving short positions alone for me?)
            Thanks!

            B 1 Reply Last reply Reply Quote 0
            • B
              backtrader administrators @BernardLin last edited by

              @bernardlin said in How do I set up correct position close logic?:

              self.buy(exectype=bt.Order.Close)

              bt.Order.Close is an order execution type and not an instruction to close a position. This is what is also known as MOC or Market On Close, i.e.: your order will be executed when the market closes. Your broker and/or the target market have to support this. Please see:

              • Docs - Order Management and Execution

              You can obviously counter a long position with self.sell (and the right size) and a short position with self.buy

              self.close()

              This will close an open position (no matter whether long/short).

              @bernardlin said in How do I set up correct position close logic?:

              (but this one seems to close all existing long and short positions, can I specify, for example, asking it to close only long positions, leaving short positions alone for me?)

              You cannot have long and short positions simultaneously on the same assets, so it cannot close all existing long and short positions. self.close will only close what`s open on the given asset you specify, and if none is specified the first data in the system. See its reference in:

              • Docs - Cerebro
              B 1 Reply Last reply Reply Quote 0
              • B
                BernardLin @backtrader last edited by

                @backtrader Hi, thanks so much for the clarification, so it means that we cannot hedge against a position on the same asset in Backtrader, right? Is it possible to add this feature in the future?

                1 Reply Last reply Reply Quote 0
                • B
                  backtrader administrators last edited by

                  Yes you can. Buy/Sell an asset which hedges your asset: options, futures. But if you buy AAPL shares and also sell AAPL shares, both actions will logically counter each other.

                  B 1 Reply Last reply Reply Quote 0
                  • B
                    BernardLin @backtrader last edited by BernardLin

                    @backtrader Okay, but I am now only backtesting my trading strategy with the historical OHLC prices of some forex currency pairs, since it was only historical rates in imported csv files, how does backtrader distinguish the asset class? Or could there be a way to set up counter positions of forex currency paris as on many forex trading platforms such as MT4 and Oanda? Thanks for any advice!

                    B 1 Reply Last reply Reply Quote 0
                    • B
                      backtrader administrators @BernardLin last edited by

                      @bernardlin said in How do I set up correct position close logic?:

                      how does backtrader distinguish the asset class

                      It doesn't. You determine how an asset performs using Commission Schemes. See

                      • Docs Commissions

                      There are some other chapters in the documentation including how to create your own commission schemes.

                      B 1 Reply Last reply Reply Quote 1
                      • B
                        BernardLin @backtrader last edited by

                        @backtrader
                        Thanks, I will look it up.
                        A new question just hit me, to further build up on this question. It seems that your reply implies that backtrader assumes that assets are denominated in USD. What if I am trading forex pairs? I guess it works the same way for currency pairs like EURUSD as the price is denominated also in USD. But what if I am trading USDCHF, USDJPY or USDCHN? These pairs are denominated in other currencies other than USD, yet my base currency is USD and I would like my backtrader to reflect that. This seems to pose an issue, do you have any suggestions how I can solve this? Much gratitude for your help!

                        B 0 2 Replies Last reply Reply Quote 0
                        • B
                          backtrader administrators @BernardLin last edited by

                          @bernardlin said in How do I set up correct position close logic?:

                          It seems that your reply implies that backtrader assumes that assets are denominated in USD

                          No. It simply assumes nothing. The assumption is yours.

                          @bernardlin said in How do I set up correct position close logic?:

                          how I can solve this?

                          This has been discussed before and the most appropriate option is to define a CommissionInfo object which converts the profit and loss (and commissions) of the given pair to your base currency.

                          B 1 Reply Last reply Reply Quote 0
                          • B
                            BernardLin @backtrader last edited by

                            @backtrader
                            Hi, would you mind providing me a link on how 'define a CommissionInfo object which converts the profit and loss (and commissions) of the given pair to your base currency' is done? I searched throughout the community but haven't found the relating thread on this. Thanks a lot!

                            1 Reply Last reply Reply Quote 0
                            • B
                              backtrader administrators last edited by

                              @bernardlin said in How do I set up correct position close logic?:

                              Hi, would you mind providing me a link on how 'define a CommissionInfo object which converts the profit and loss (and commissions) of the given pair to your base currency' is done

                              "Discussed" is not the same as developed.

                              1 Reply Last reply Reply Quote 0
                              • K
                                kk7134 @BernardLin last edited by

                                @bernardlin You have to check whether the position is a Long Position or Short position, before trying to close it. The position object has size property which will be +ve for Long position and -Ve for short position. You have to check for this before trying to close a position

                                What it happening in your code is, the position check is being evaluated and since the system does not know whether you are looking to close a long or short position it is simply executing the condition that is being met in the 'Else' block

                                Hope it helps

                                1 Reply Last reply Reply Quote 0
                                • 0
                                  01tsos @BernardLin last edited by

                                  @bernardlin
                                  I have something critical to point out.

                                  Backtesting forex pairs trading has a major flaw. It uses a different way to calculate pnl of the backtest because the assets involved rarely have the same quote or base currencies.

                                  The only exception to this is if the assets involved have the same base currency, e.g USDCHF USDJPY. If this pair appear to be cointegrated, then the returns of the backtest would be the same as calculating pnl of, say, GLD GDX.

                                  But if the forex assets involved are of the same quote currency or of completely different currency bases and quotes, then the calculation of the pnl is completely different.

                                  If one proceeds and backtest these cointegrated pairs the same way one do regularly then one would get the wrong result.

                                  I am really keen to know how you went about backtesting cointegrated forex pairs and getting the correct result using Backtrader. I am yet to do that.

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