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/

    Stop Loss using Timing and Current Profit

    General Code/Help
    2
    2
    76
    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.
    • A
      AlfredSisley last edited by

      Hi All,

      How would one implement the following stop loss:

      Pseudo Code

      IF Length of Trade >= 20 minutes AND Current Profit on Trade < 0.1%:
           self.close()
      

      Thanks,
      Alfred Sisley

      1 Reply Last reply Reply Quote 0
      • mics
        mics last edited by

        I've previously used this approach for counting bars from when a condition or order has been placed. There is probably a more elegant solution but this approach has worked for me.

        It needs to be noted that the 'enter_price' is only the price that triggers the placement of the order, it is not the executed price.

        Perhaps someone else can provide some more insight on how to improve this by calling the executed price. This would improve the accuracy, particularly if you are using bracket orders.

        def __init__(self):
            self.len_bar = 20
            self.set_bar = 0
            self.enter_price = 0
        
        def next(self):
        
            if not self.position:
            
                if self.data.close[0] > [YOUR LONG CONDITION IS MET]:
                    self.buy()
                    self.set_bar = len(self.data0) #Bar when order is placed
                    self.enter_price = self.data.close[0] #Price that order is palced on
            
            if self.position.size > 0
            
                if (len(self.data0) - self.freezebar) >= self.len_bar: #Greater than 20mins from buy order
                    if (self.data.close[0] - self.enter_price) < (0.001 * self.enter_price):
                        self.sell()
                        self.set_bar = 0    #RESET
        
                    elif (self.data.close[0] - self.enter_price) >= (0.001 * self.enter_price):
                        [DO SOMETHING ELSE]
        
        
        1 Reply Last reply Reply Quote 0
        • 1 / 1
        • First post
          Last post
        Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors