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/

    why I take wrong value

    Indicators/Strategies/Analyzers
    1
    1
    35
    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.
    • حسین سلطانی
      حسین سلطانی last edited by

      I run below code and when I use sl and tp I take wrong value. can you help me

      import backtrader as bt
      import pandas as pd
      from datetime import datetime
      import math
      %matplotlib inline
      class firstStrategy(bt.Strategy):
          def __init__(self):
              # initializing rsi, slow and fast sma
              self.rsi = bt.indicators.RSI(self.data.close, period=21)
              self.fast_sma = bt.indicators.SMA(self.data.close, period=50)
              self.slow_sma = bt.indicators.SMA(self.data.close, period=100)
              self.crossup = bt.ind.CrossUp(self.fast_sma, self.slow_sma)
              self.sl_order, self.tp_order = None, None
              
          def log(self, txt, dt=None):
              dt = self.datas[0].datetime.date()
              print(f'{dt}, {txt}')
          def notify_trade(self, trade):
              if trade.isclosed:
                  self.log(f'OPERATION RESULT --- Gross: {trade.pnl:.2f}, Net: {trade.pnlcomm:.2f} \n')
          def next(self):
              
              
              
              
                # process stop loss and take profit signals
              
              if self.position:
              
      
              # set stop loss and take profit prices
                  # in case of trailing stops stop loss prices can be assigned based on current indicator value
                  price_sl_long = self.position.price * 0.98
                  price_sl_short = self.position.price * 1.02
                  price_tp_long = self.position.price * 1.06
                  price_tp_short = self.position.price * 0.94
      
                  # cancel existing stop loss and take profit orders
                  if self.sl_order:
                      self.broker.cancel(self.sl_order)
      
                  if self.tp_order:
                      self.broker.cancel(self.tp_order)
      
                  # check & update stop loss order
                  sl_price = 0.0
                  if self.position.size > 0 and price_sl_long !=0: sl_price = price_sl_long
                  if self.position.size < 0 and price_sl_short !=0: sl_price = price_sl_short
      
                  if sl_price != 0.0:
                      self.sl_order = self.order_target_value(target=0.0, exectype=bt.Order.Stop, price=sl_price)
                  
                  # check & update take profit order
                  tp_price = 0.0
                  if self.position.size > 0 and price_tp_long !=0: tp_price = price_tp_long
                  if self.position.size < 0 and price_tp_short !=0: tp_price = price_tp_short
      
                  if tp_price != 0.0:
                      self.tp_order = self.order_target_value(target=0.0, exectype=bt.Order.Limit, price=tp_price)
      #         g = int(cerebro.broker.getvalue() / self.datas[0].open[0])
              if self.getposition(self.datas[0]).size>0:
                  print(self.getposition(self.datas[0]).size)
                  print(cerebro.broker.getvalue() ,'/',self.datas[0].open[0] ,': ',cerebro.broker.getvalue() / self.datas[0].open[0])
      
      #         self.order_target_percent(target=0.5)
              g=None
              if not self.position:
                  if self.rsi > 30 and self.fast_sma > self.slow_sma:
                      self.buy(size=g)
              else:
                  if self.rsi < 70:
                      self.sell(size=g)  
      # class SLTPTracking(bt.Observer):
      
      #     lines = ('stop', 'take')
      
      #     plotinfo = dict(plot=True, subplot=False)
      
      #     plotlines = dict(stop=dict(ls=':', linewidth=1.5),
      #                      take=dict(ls=':', linewidth=1.5))
      
      #     def next(self):
      
      #         if self._owner.sl_price != 0.0:
      #             self.lines.stop[0] = self._owner.sl_price
      
      #         if self._owner.tp_price != 0.0:
      #             self.lines.take[0] = self._owner.tp_price
      
      startcash = 100
      cerebro = bt.Cerebro()
      cerebro.addstrategy(firstStrategy) # adding strategy in Cerebro engine
      # cerebro.addobserver(SLTPTracking)
      df = pd.read_pickle("data_pairs_kucoin_future_1d.pkl").loc[15,'pair']
      df['date'] = df['date'].astype(str) +' '+ df['time'].astype(str)
      df['date']= pd.to_datetime(df['date'], format='%d/%m/%Y %H:%M:%S')
      df.set_index('date', inplace=True) 
      data = bt.feeds.PandasData(dataname=df)
      cerebro.adddata(data)
      cerebro.broker.setcommission(commission=0.002)
      cerebro.broker.setcash(startcash)
      
      cerebro.addsizer(bt.sizers.PercentSizer, percents=99)
      cerebro.run()
      portvalue = cerebro.broker.getvalue()
      pnl =((portvalue - startcash)/startcash)*100
      
      # Printing out the final result
      print('Final Portfolio Value: ${}'.format(portvalue))
      # print('P/L: ${}'.format(pnl))
      cerebro.plot()
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors