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/

    My plot is not showing pointers to where the trades occured and also my stoploss and take profits are not working, any help would be highly appereciated

    General Code/Help
    2
    5
    421
    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.
    • Dennis Musingila
      Dennis Musingila last edited by

      import numpy as np
      import math
      class TestStrategy(bt.Strategy):
      params = (('risk', 0.4), #risk 10%
      ('stop_dist', 0.05)) #stoploss distance 5%

      pred = []
      def log(self, txt, dt = None):
          dt = dt or self.datas[0].datetime.datetime(0)
          print('%s, %s' % (dt.isoformat(), txt))
      def __init__(self,pred=[]):
          self.dataclose = self.data.close
          self.dataopen = self.datas[0].open
          self.datahigh = self.datas[0].high
          self.datalow = self.data.low.get(size=10)
          self.units = 1000
          self.order = None
          
          #self.myslice = self.datas.open[-30:0]
          
      
      def prediction_out(self,predata):
         
          predata = np.array(predata)
          pred_data = predata.T
          pred_data = scaler.transform(pred_data)
          #print(pred_data)
          pre_data = np.array(pred_data)
          #print(pre_data.shape)
          
          pre_data =  np.reshape(pre_data, (1,pre_data.shape[0], pre_data.shape[1]))
          #print(pre_data.shape)
          predict = model.predict(pre_data)
          predict = (predict * (maxim-minim)) + minim
          #print(predict)
          TestStrategy.pred.append(predict)
          return predict
          
      def next(self):
          cash = self.broker.get_cash()
          a = self.data.close.get(size= 15)
          #print(a)
          #(self.data.close.get(ago = -5,size= 10))
          #self.log('high, %.2f' % self.datahigh[0])
          #self.log('low, %.2f' % self.datalow[0])
          #self.log('close, %.2f' % self.dataclose[0])
          #self.log('this is it' % self.myslice)
          
          #data = self.dataclose.get(size = 10)
          #print('datasdfasdfa',data)
          if len(a) > 3:
              pred_data = [(self.data.open.get(size = 15)).tolist(),
                           (self.data.high.get(size = 15)).tolist(),
                           (self.data.low.get(size = 15)).tolist(),
                           (self.data.close.get(size = 15)).tolist()]
                  
              #print(pred_data)
              prediction = self.prediction_out(pred_data)
          
          if len(TestStrategy.pred) >  15:
              
              if (TestStrategy.pred[len(TestStrategy.pred)-15][0][0]-TestStrategy.pred[-1][0][0]) > 0.00100:
                  buy_order = self.buy(size = self.units)
                  buy_order.addinfo(name='MARKET_BUY')
                  self.order = buy_order
                  return buy_order
              elif (TestStrategy.pred[len(TestStrategy.pred)-15][0][0]-TestStrategy.pred[-1][0][0]) < -0.00100:
                  self.log('Sell Create, %.2f' % self.dataclose[0])
                  stop_price = (self.data.close[0] * (1 - self.p.stop_dist))
                  short_order = self.sell(size = self.units)
                  short_order.addinfo(name = 'MARKET_SELL')
                  self.order = short_order
                  
                  
              else:
                  pass
      def notify_trade(self, trade):
          date = self.data.datetime.datetime()
          if trade.isclosed:
              print('-'*32,' NOTIFY TRADE ','-'*32)
              print('{}, Avg Price: {}, Profit, Gross {}, Net {}'.format(
                                                  date,
                                                  trade.price,
                                                  round(trade.pnl,2),
                                                  round(trade.pnlcomm,2)))
              print('-'*80)
           # placing stoploss and takeproti   
          if self.order.info['name'] == 'MARKET_BUY':
              sell_order = self.sell(size = self.units, exectype = bt.Order.Stop, price = (self.order.executed.price - 0.0002000))
              sell_order.addinfo(name = 'MARKET_BUY_STOP')
              print('this is this working ')
          
      
              take_profit = self.sell(size = self.units, exectype = bt.Order.Limit, price = self.order.executed.price + 0.0002000)
              take_profit.addinfo(name = 'Take_Profit')
         
      
          elif self.order.info['name'] == 'MARKET_SELL' :
              buy_order = self.buy(size = self.units, exectype = bt.Order.Stop, price = (self.order.executed.price + 0.0001))
              buy_order.addinfo(name = 'MARKET_SELL_STOP')
      
              take_profit = self.sell(size = self.units, exectype = bt.Order.Limit, price = self.order.executed.price - 0.0001000)
              take_profit.addinfo(name = 'Take_Profit')
              
              print('is this working')
      
      1 Reply Last reply Reply Quote 0
      • Dennis Musingila
        Dennis Musingila last edited by

        @Dennis-Musingila ![graphhhhhh.JPG

        Here is the graph its producing

        1 Reply Last reply Reply Quote 0
        • D
          dasch last edited by

          try adding the observer manually with different bardist

              cerebro.addobserver(
                  bt.observers.BuySell,
                  barplot=True,
                  bardist=config.get("plot_bar_dist", 0.001))  # buy / sell arrows
          
          1 Reply Last reply Reply Quote 1
          • D
            dasch last edited by

            removed custom config code from example:

                cerebro.addobserver(
                    bt.observers.BuySell,
                    barplot=True,
                    bardist=0.001)  # buy / sell arrows
            
            Dennis Musingila 1 Reply Last reply Reply Quote 1
            • Dennis Musingila
              Dennis Musingila @dasch last edited by

              @dasch Thanks a million mate, It worked

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