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/

    Find if an open position is a losing position

    General Code/Help
    3
    4
    1665
    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.
    • T
      Trade Prophet last edited by

      Hello,
      Is there a way to find if an open position is losing, when inside the Strategy next () method?
      by losing I mean its PnL<0

      Thank you.

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

        After much thinking, there is no direct method. It is possible, but if doesn't feel natural and will for sure be modeled in a better way.

        The howto:

        • Get the position for the data of your choice
        • Get the commission info object which applies to that data
        • Calculate the current profit and loss

        In code

        def next(self):
            pos = self.getposition(self.data)  # for the default data (aka self.data0 and aka self.datas[0])
            comminfo = self.broker.getcommissioninfo(self.data)
            pnl = comminfo.profitandloss(pos.size, pos.price, self.data.close[0])
        
        1 Reply Last reply Reply Quote 1
        • T
          Trade Prophet last edited by

          Eventually, I saved the open price in a file and read it in next() method, easy...

          1 Reply Last reply Reply Quote 1
          • S
            scottz1 last edited by

            You could create a dictionary in strategy.init. In notify_order: order.completed, insert an item with either the symbol or order.ref as the key, and either the order object (to later retrieve size and price), or order.executed.price as the value.

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