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/

    How to close current position at the end of backtest?

    General Code/Help
    3
    3
    1704
    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.
    • H
      Henry Gong last edited by

      When it calls next() how to know if the current data is the last bar is my question. Eventually, I want to sell what I have at the end of backtesting.

      C B 2 Replies Last reply Reply Quote 0
      • C
        crystalet @Henry Gong last edited by

        @henry-gong
        I am very very new to backtrader, but from my understanding you add a stop method (https://www.backtrader.com/docu/strategy.html?highlight=stop#backtrader.Strategy.stop) to your strategy where you close the position.

        without having tried it, the below should do the trick:

        def stop(self):
          targetsize = 0 
          self.order = self.order_target_size(target=targetsize)
        
        1 Reply Last reply Reply Quote 0
        • B
          backtrader administrators @Henry Gong last edited by

          @henry-gong

          That depends on how the data feed is loaded. If the data feed is not preloaded, the platform cannot know when it will be the last bar, it will simply happen and it will then be too late for you close your position.

          If you preload your data, you can check that this equality is True

          len(self.data) == self.data.buflen()
          

          If you have multiple data feeds, you would need then to check it for all of them.

          1 Reply Last reply Reply Quote 0
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
          $(document).ready(function () { app.coldLoad(); }); }