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/

    Trade max amount when flipping from short to long or vice versa

    General Code/Help
    2
    2
    61
    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.
    • bmex test
      bmex test last edited by

      Hi!
      Having read through probably most other topics related to this I still haven't come across a solution to ensure that when flipping from short to long or vice versa the max amount is traded.
      Possibly I'm struggling because the open PnL of the short/long position needs to be taken into account to know how much can be bought/sold after the short/long position is closed and the PnL is realised.
      However, I think there should be a simple solution to ensure the max amount is traded.

      Entering the first position with the max amount is as simple as (for e.g. a sell):

      size = float(self.broker.get_cash() / self.dataopen[1])
      self.order = self.sell(
          coo=True,
          exectype=bt.Order.Market,
          size=size
      )
      

      Now if I'd like to flip from e.g. short to long I tried the following:

      trade_size = 2 * float(self.broker.getvalue() / self.dataopen[1])
      self.order = self.buy(
          coo=True,
          exectype=bt.Order.Market,
          size=trade_size
      )
      

      This however results in the buy order being rejected sometimes but I struggle to see why.
      How can I ensure that when flipping from short to long that the max possible amount is traded?

      Thanks and happy new year!

      run-out 1 Reply Last reply Reply Quote 0
      • run-out
        run-out @bmex test last edited by

        @bmex-test said in Trade max amount when flipping from short to long or vice versa:

        self.dataopen[1]

        This code shouldn't run.

        Check out this article and this page.

        If you are trying to get 100% of your cash invested, this is very challenging since the markets move after an order is issued. Your orders are most likely rejected for this reason with a 'margin' status shown.

        Typically, it's better to target investing an amount slightly less than 100%, depending on the volatility and time period of your instrument.

        RunBacktest.com

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