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/

    Sell Order not getting executed

    General Code/Help
    2
    5
    64
    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.
    • M
      mukeshcm last edited by

      Dear All,

      Please help as I am not able to figure out why the Sell orders are not getting executed , only first buy occur and then no trade occur. I am new to community so request senior followers to help me out.

      '''
      class testStrategy(bt.Strategy):
      params = (('portfolio_expo', 0.10), ('trade_risk', 0.02), ('atrdist', 4.0))

      def __init__(self):
          self.obv = OnBalanceVolume(self.data)
          self.sma = bt.indicators.SMA(self.data.close, period=100)
          self.atr = bt.indicators.ATR(period=10)
      
      def log(self, txt, dt=None):
          ''' Logging function fot this strategy'''
          dt = dt or self.datas[0].datetime.date(0)
          print('%s, %s' % (dt.isoformat(), txt))  
          
      
      
      def notify_order(self, order):
          self.bar_executed = len(self)
          if order.status in [order.Submitted, order.Accepted]:
              # Buy/Sell order submitted/accepted to/by broker - Nothing to do
              return
      
          # Check if an order has been completed
          # Attention: broker could reject order if not enough cash
          if order.status in [order.Completed]:
      
              if order.isbuy():
                  self.log('BUY EXECUTED')
      
                  #self.buyprice = order.executed.price
                  #self.buycomm = order.executed.comm
                  #self.opsize = order.executed.size
              else:  # Sell
                  self.log('SELL EXECUTED')
                #      'SELL EXECUTED, Size: %.2f, OpenPrice: %.2f, Closeprice: %.2f, Comm %.2f' %
                 #          (order.executed.size,
                  #          order.executed.price,
                   #         order.executed.value,
                    #        order.executed.comm))
      
              
      
      
          
      
          # Write down: no pending order
          #self.order = None
          
      def notify_trade(self, trade):
          if not trade.isclosed:
              return
          ##self.log('BUY, RSI %.2f, NET %.2f' %
            ##       (trade.pnl, trade.pnlcomm))
      
      def next(self):
              print("{}: Close: {}, Close1: {} Close2: {}  Close3: {} SMA {}".format(
                  self.data.datetime.date(),
                  self.data.close[0],
                  self.data.close[-1],
                  self.data.close[-2],
                  self.data.close[-3],
                  self.sma[0]))
      
              cash = self.broker.get_cash()
              print(cash)
              if self.order:
                  return  # pending order execution
      
              if not self.position:  # check if we already have an open position on the stock
      
                  if self.data.close[0]>self.sma and  self.data.close[0]< self.data.close[-1] and self.data.close[-1]< self.data.close[-2] and self.data.close[-2]< self.data.close[-3]:
                          pdist = self.atr[0] * self.p.atrdist
                          self.pstop = self.data.close[0] - pdist
                          qty = math.floor((cash * self.p.trade_risk) / pdist)
      
                          portfolio_exposure_calc = qty * self.data.close[0]
                          portfolio_exposure_strategy = cash * self.p.portfolio_expo
                          print('QTY '+str(qty))
                          if portfolio_exposure_calc <= portfolio_exposure_strategy:
                              self.order = self.buy(size=qty)
                          else:
                              qty = math.floor(portfolio_exposure_strategy / self.data.close[0])
                              self.order = self.buy(size=qty)
      
      
              else:  # in the market
                      pclose = self.data.close[0]
                      pstop = self.pstop
                      print("{}: Close: {}, Stop: {}",format(self.data.datetime.date(),pclose,pstop)) 
              # Add detection if we are already short or long
                      if pclose < pstop:
                          self.close()  # stop met - get out
                      else:
                          pdist = self.atr[0] * self.p.atrdist
                          # Update only if greater than
                          self.pstop = max(pstop, pclose - pdist)
          
      def start(self):
          self.order = None  # sentinel to avoid operations on pending order
          self.curpos = None
      
      def prenext(self):
          self.next()
      

      @ab_trader

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

        Look here:

        if self.order:
            return  # pending order execution
        

        Then here:

         # Write down: no pending order
         #self.order = None
        

        Set some debuggers please and you can resolve this on your own.

        RunBacktest.com

        M 1 Reply Last reply Reply Quote 0
        • M
          mukeshcm @run-out last edited by

          @run-out Thanks I think understood your point and corrected the same, ofcourse will not shy used help from community only now only problem I am getting error at this line, that is divisibility by zero...Please guide
          self.profit_factor = self.gross_profits / self.gross_losses

          '''
          class testStrategy(bt.Strategy):
          average_period = 15
          total_trades = 0
          wins = 0
          losses = 0
          gross_profits = 0
          gross_losses = 0
          percent_profitable = 0
          profit_factor = 0
          params = (('portfolio_expo', 0.10), ('trade_risk', 0.02), ('atrdist', 4.0))

          def __init__(self):
              self.order = None
              self.buyprice = None
              self.buycomm = None # again optional
              self.obv = OnBalanceVolume(self.data)
              self.sma = bt.indicators.SMA(self.data.close, period=100)
              self.atr = bt.indicators.ATR(period=10)
          
          def log(self, txt, dt=None):
              ''' Logging function fot this strategy'''
              dt = dt or self.datas[0].datetime.date(0)
              print('%s, %s' % (dt.isoformat(), txt))  
              
          
          
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  return
          
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log(
                          "BUY, price: {}, cost: {}, comm: {}".format(
                              order.executed.price,
                              order.executed.value,
                              order.executed.comm,
                          )
                      )
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  elif order.issell():
                      self.log(
                          "SELL, price: {}, cost: {}, comm: {}".format(
                              order.executed.price,
                              order.executed.value,
                              order.executed.comm,
                          )
                      )
                  self.bar_executed = len(self)
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log("Order Canceled/Margin/Rejected")
          
              self.order = None
              
          def notify_trade(self, trade):
              if not trade.isclosed:
                  return
          
              if trade.pnl > 0:
                  self.wins += 1
                  self.gross_profits += trade.pnl
              else:
                  self.losses += 1
                  self.gross_losses -= trade.pnl
              self.percent_profitable = self.wins / self.total_trades
              #self.profit_factor = self.gross_profits / self.gross_losses
          
              self.log("PROFIT, gross: {}, net: {}".format(trade.pnl, trade.pnlcomm))
          
          def next(self):
                  print("{}: Close: {}, Close1: {} Close2: {}  Close3: {} SMA {}".format(
                      self.data.datetime.date(),
                      self.data.close[0],
                      self.data.close[-1],
                      self.data.close[-2],
                      self.data.close[-3],
                      self.sma[0]))
          
                  cash = self.broker.get_cash()
                  print(cash)
                  if self.order:
                      return  # pending order execution
          
                  if not self.position:  # check if we already have an open position on the stock
          
                      if self.data.close[0]>self.sma and  self.data.close[0]< self.data.close[-1] and self.data.close[-1]< self.data.close[-2] and self.data.close[-2]< self.data.close[-3]:
                              pdist = self.atr[0] * self.p.atrdist
                              self.pstop = self.data.close[0] - pdist
                              qty = math.floor((cash * self.p.trade_risk) / pdist)
          
                              portfolio_exposure_calc = qty * self.data.close[0]
                              portfolio_exposure_strategy = cash * self.p.portfolio_expo
                              print('QTY '+str(qty))
                              if portfolio_exposure_calc <= portfolio_exposure_strategy:
                                  self.order = self.buy(size=qty)
                              else:
                                  qty = math.floor(portfolio_exposure_strategy / self.data.close[0])
                                  self.order = self.buy(size=qty)
          
          
                  else:  # in the market
                          pclose = self.data.close[0]
                          pstop = self.pstop
                          #print("{}: Close: {} Stop: {}",format(self.data.datetime.date(),pclose)) 
                  # Add detection if we are already short or long
                          if pclose < pstop:
                              self.total_trades += 1
                              self.close()  # stop met - get out
                          else:
                              pdist = self.atr[0] * self.p.atrdist
                              # Update only if greater than
                              self.pstop = max(pstop, pclose - pdist)
              
          def stop(self):
              print("Total Trades: {}".format(self.total_trades))
              print("Percent Profitable: {}".format(self.percent_profitable))
              print("Profit Factor: {}".format(self.profit_factor))
              super().stop()
          
          1 Reply Last reply Reply Quote 0
          • run-out
            run-out last edited by

            Well you set self.gross_losses = 0 then divided by it without check to see if it was still zero.

            RunBacktest.com

            1 Reply Last reply Reply Quote 0
            • M
              mukeshcm last edited by

              @run-out yes very foolish thing from my side but issue was some where else, last guidance from you ,quantstats not saving report in defined path either in jupyter or colab notebook. Earlier it was doing same and this piece of code I did not change could you please guide. Title it is changing with ticker name but output it is genreating in root and overriding so in last i have one file with last ticker
              '''
              for x in tickers:
              #print(apple.iloc[x,1],apple.iloc[x,2],apple.iloc[x,3])
              #for y in tickers:
              cerebro = bt.Cerebro()

                data = bt.feeds.PandasData(dataname=yf.download(x+'.ns', '2015-01-01', '2022-01-01'))
                cerebro.adddata(data)
                
                strats = cerebro.addstrategy(
                        testStrategy)
                
                
                cerebro.broker.setcash(1000000.0)
                
                cerebro.addsizer(bt.sizers.PercentSizer, percents = 10)
                #cerebro.addanalyzer(btanalyzers.SharpeRatio, _name = "sharpe")
                #cerebro.addanalyzer(btanalyzers.DrawDown, _name = "drawdown")
                #cerebro.addanalyzer(btanalyzers.Returns, _name = "returns")
                cerebro.addanalyzer(bt.analyzers.PyFolio, _name='PyFolio')
                cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
                cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
                cerebro.addanalyzer(bt.analyzers.DrawDown, _name="dd")
                print(x)
                initial_value = cerebro.broker.getvalue()
                results = cerebro.run()
                strat = results[0]
                
                print(initial_value)
                final_value = cerebro.broker.getvalue()
                total=total+(final_value-initial_value)
                #printTradeAnalysis(strat.analyzers.ta.get_analysis())
                #printDrawDownAnalysis(strat.analyzers.dd.get_analysis())
                #printSQN(strat.analyzers.sqn.get_analysis())
                portfolio_stats = strat.analyzers.getbyname('PyFolio')
                returns, positions, transactions, gross_lev = portfolio_stats.get_pf_items()
                returns.index = returns.index.tz_convert(None)
                quantstats.reports.html(returns, output='/quants/'+x+'.html', title=x+' Sentiment')
              
              1 Reply Last reply Reply Quote 0
              • 1 / 1
              • First post
                Last post
              Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors