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



  • 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)