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 and Stop Profit - Give me your feedback

    General Discussion
    1
    1
    607
    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.
    • mrahmadt
      mrahmadt last edited by mrahmadt

      Hello
      So I wrote this code that will allow me to automatically stop loss and stop profit based on a percentage from the original buy price, I would love to hear your feedback and if you have any suggestion to improve it.

      class myStrategy(bt.Strategy):
          params = (
              ('stopLoss', 0.40), #if current price is %40 below the original buy price then sell the stock
              ('stopWin',0.40) #if current price is %40 above the original buy price then sell the stock
          )
          def __init__(self):
              # To keep track of pending orders
              self.order = None
              self.stopOrder = None
      
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  return
      
              if order.status in [order.Completed]:
                  if order.isbuy():
                      if(self.params.stopLoss):
                          self.stopOrder = self.sell(price=order.executed.price,exectype=bt.Order.StopTrail,trailpercent=self.params.stopLoss)
      
                      if(self.params.stopWin):
                          self.stopOrder = self.sell(price=(order.executed.price*(1+self.params.stopWin)),exectype=bt.Order.Limit,oco=self.stopOrder)
              self.order = None
      
          def next(self):
              if self.order:
                  return
      
              if not self.position:
                  if self.data.close[0] > self.sma[0]:
                      self.order = self.buy(price=(self.datas[0].close[0]),exectype=bt.Order.Market)
              else:
                  if self.datas[0].close[0] < self.sma[0]:
                      self.order = self.sell(exectype=bt.Order.Market,oco=self.stopOrder)
      
      
      1 Reply Last reply Reply Quote 2
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
      $(document).ready(function () { app.coldLoad(); }); }