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/

    Hourly indicator with intraday strategy doesnt trade

    Indicators/Strategies/Analyzers
    1
    2
    150
    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.
    • H
      hakankaan last edited by

      I'm creating a strategy that i want it to use 1m or 5m candles to trade -to make it more realistic-.
      Trades will happen if price touches from above to 1h and 4h Vidya lines.

      Problem is if i use 30m or 1h datafeeds to buy or sell it trades. But smaller timeframes like 1m and 5m creates lesser trades.

      I couldnt find the source of the problem.
      Below the full code and some result examples with different used timeframes.

      What can be the problem?

      Start date: 01.01.2021
      End date: 01.06.2021

      import backtrader as bt
      import backtrader.analyzers as btanalyzers
      from Vidya import Vidya
      import math
      from PrintAnalyzers import printTradeAnalysis, printSQN
      from utils import size_by_percent
      from get_binance_data import get_data
      
      
      TF1 = '5m'
      TF2 = '1h'
      
      
      class VidyaTouchStrategy(bt.Strategy):
          params = dict(profit_percent=10, stop_loss_percent=5,
                        cash_percent=10, oneplot=True)
      
          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 __init__(self):
              self.startcash = self.broker.getvalue()
              self.inds = dict()
              self.orders = dict()
              self.winning_trades = 0
              self.losing_trades = 0
      
              for i, d in enumerate(self.datas):
                  dn = d._name
                  if "TF1" not in dn:
                      self.inds[d] = dict()
                      self.inds[d]['vidya100'] = self.vidya100 = Vidya(
                          d, period=21)
      
                  if i > 0:
                      if self.p.oneplot:
                          d.plotinfo.plotmaster = self.datas[0]
      
          def next(self):
              for i, d in enumerate(self.datas):
                  dt, dn = self.datetime.date(), d._name           # Get time and stock code
                  if "TF1" not in dn:
                      is_not_last = len(self) < len(d.high.array) - 3
                      pos = self.getposition(d).size
      
                      stop_loss = self.getposition(d).price * \
                          (1 - self.p.stop_loss_percent /
                           100) if self.getposition(d).price else None
      
                      take_profit = self.getposition(d).price * \
                          (1 + self.p.profit_percent /
                           100) if self.getposition(d).price else None
      
                      touched_above = self.inds[d]['vidya100'].vidya[1] if is_not_last and self.inds[
                          d]['vidya100'].touched_above[1] else None
                      orders = self.broker.get_orders_open()
                      # is_same_order = any(s.price == touched_above for s in orders)
                      is_order = len(orders) > 0
                      if not is_order:
                          if not pos:   # Not in the market, you can buy
                              if touched_above and not math.isnan(touched_above):
                                  stake_size = size_by_percent(
                                      percent=self.p.cash_percent, current_price=touched_above, current_cash=self.broker.get_cash())
                                  self.buy(data=d, size=stake_size, exectype=bt.Order.Limit,
                                           price=touched_above,
                                           )
                          # take profit
                          elif pos and is_not_last and take_profit <= d.high[0]:
                              self.close(data=d)
                          elif pos and is_not_last and take_profit <= d.high[1]:
                              self.close(data=d, exectype=bt.Order.Limit,
                                         price=take_profit,
                                         )
                          # stoploss
                          elif pos and is_not_last and stop_loss >= d.low[0]:
                              self.close(data=d)
                          elif pos and is_not_last and stop_loss >= d.low[1]:
                              self.close(data=d, exectype=bt.Order.Limit,
                                         price=stop_loss,
                                         )
      
          def notify_trade(self, trade):
              dt = self.data.datetime.date()
              if trade.isclosed:
                  print('#######{} {} price {} Closed: PnL Gross {}, Net {}#######\n'.format(
                      dt,
                      trade.data._name,
                      round(trade.price, 2),
                      round(trade.pnl, 2),
                      round(trade.pnlcomm, 2)))
                  if round(trade.pnlcomm, 2) > 0:
                      self.winning_trades += 1
                  else:
                      self.losing_trades += 1
      
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                  return
      
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log(
                          'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                          (order.executed.price,
                           order.executed.value,
                           order.executed.comm))
      
                  else:  # Sell
                      self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                               (order.executed.price,
                                order.executed.value,
                                order.executed.comm))
      
              # elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  # self.log('Order Canceled/Margin/Rejected')
      
          def stop(self):
              pnl = round(self.broker.getvalue() - self.startcash, 2)
              print('Profit Percent: {} Stop-loss Percent: {} Final PnL: {}'.format(
                  self.p.profit_percent, self.p.stop_loss_percent, pnl, ))
              print(
                  f"Total Trades: {self.winning_trades + self.losing_trades}\n Winning Trades: {self.winning_trades} \n Losing Trades: {self.losing_trades}")
      
      
      tickers = [
          'BTCUSDT',
          # 'ETHUSDT',
          # 'ADAUSDT',
          # 'LINKUSDT',
          # 'SOLUSDT',
          # 'ZILUSDT',
      ]
      
      for ticker in tickers:
          cerebro = bt.Cerebro()
          df = get_data(ticker, TF1)
          data = bt.feeds.PandasData(
              dataname=df, timeframe=bt.TimeFrame.Minutes, compression=1)
          cerebro.adddata(data, name=ticker+"TF1")
      
          df2 = get_data(ticker, TF2)
          data2 = bt.feeds.PandasData(dataname=df2)
          cerebro.adddata(data2, name=ticker+"TF2")
      
          cerebro.addstrategy(VidyaTouchStrategy)
      
          cerebro.broker.setcash(100000)
      
          cerebro.broker.setcommission(commission=0.001)
      
          cerebro.addobserver(bt.observers.Trades)
          cerebro.addobserver(bt.observers.BuySell)
      
          cerebro.addanalyzer(btanalyzers.SharpeRatio, _name="sharpe")
          cerebro.addanalyzer(btanalyzers.TradeAnalyzer, _name="trade")
      
          back = cerebro.run(stdstats=False)
      
          print(cerebro.broker.getvalue())
      
          printTradeAnalysis(back[0].analyzers.trade.get_analysis())
          print(back[0].analyzers.sharpe.get_analysis())
      
          cerebro.plot(style='candle')
      
      

      Result for 5m and 1h timeframes:
      Total trades: 1

      every time pre_load consume time :12.597188472747803
      2021-01-10, BUY EXECUTED, Price: 35919.11, Cost: 10000.00, Comm 10.00
      2021-01-11, SELL EXECUTED, Price: 37237.67, Cost: 10000.00, Comm 10.37
      #######2021-01-11 BTCUSDTTF2 price 35919.11 Closed: PnL Gross 367.09, Net 346.72#######
      
      Profit Percent: 10 Stop-loss Percent: 5 Final PnL: 346.72
      

      Result for 15m and 1h timeframes:
      Total trades: 6

      every time pre_load consume time :5.127857685089111
      2021-01-10, BUY EXECUTED, Price: 35919.11, Cost: 10000.00, Comm 10.00
      2021-01-11, SELL EXECUTED, Price: 37237.67, Cost: 10000.00, Comm 10.37
      #######2021-01-11 BTCUSDTTF2 price 35919.11 Closed: PnL Gross 367.09, Net 346.72#######
      
      2021-01-15, BUY EXECUTED, Price: 35228.91, Cost: 10034.67, Comm 10.03
      2021-01-20, SELL EXECUTED, Price: 34875.87, Cost: 10034.67, Comm 9.93
      #######2021-01-20 BTCUSDTTF2 price 35228.91 Closed: PnL Gross -100.56, Net -120.53#######
      
      2021-01-25, BUY EXECUTED, Price: 32764.47, Cost: 10022.62, Comm 10.02
      2021-01-26, SELL EXECUTED, Price: 32062.32, Cost: 10022.62, Comm 9.81
      #######2021-01-26 BTCUSDTTF2 price 32764.47 Closed: PnL Gross -214.79, Net -234.62#######
      
      2021-01-29, BUY EXECUTED, Price: 32041.32, Cost: 9999.16, Comm 10.00
      2021-01-29, SELL EXECUTED, Price: 35245.45, Cost: 9999.16, Comm 11.00
      #######2021-01-29 BTCUSDTTF2 price 32041.32 Closed: PnL Gross 999.92, Net 978.92#######
      
      2021-01-29, BUY EXECUTED, Price: 34028.14, Cost: 10097.05, Comm 10.10
      2021-01-31, SELL EXECUTED, Price: 32862.65, Cost: 10097.05, Comm 9.75
      #######2021-01-31 BTCUSDTTF2 price 34028.14 Closed: PnL Gross -345.83, Net -365.68#######
      
      2021-05-19, BUY EXECUTED, Price: 33725.16, Cost: 10060.48, Comm 10.06
      Profit Percent: 10 Stop-loss Percent: 5 Final PnL: 1551.55
      

      Result for 1m and 1h timeframes:
      Total trades: 0

      every time pre_load consume time :50.99492526054382
      Profit Percent: 10 Stop-loss Percent: 5 Final PnL: 0.0
      
      1 Reply Last reply Reply Quote 0
      • H
        hakankaan last edited by

        Start date: 01.01.2019
        End date: 01.06.2021

        Result for 30m and 1h timeframes:
        Total trades: 2

        every time pre_load consume time :17.86236882209778
        2019-01-10, BUY EXECUTED, Price: 3819.86, Cost: 10000.00, Comm 10.00
        2019-01-10, SELL EXECUTED, Price: 3726.32, Cost: 10000.00, Comm 9.76
        #######2019-01-10 BTCUSDTTF2 price 3819.86 Closed: PnL Gross -244.87, Net -264.63#######
        
        2019-01-20, BUY EXECUTED, Price: 3590.40, Cost: 9973.54, Comm 9.97
        2019-01-28, SELL EXECUTED, Price: 3479.01, Cost: 9973.54, Comm 9.66
        #######2019-01-28 BTCUSDTTF2 price 3590.4 Closed: PnL Gross -309.42, Net -329.06#######
        
        Profit Percent: 10 Stop-loss Percent: 5 Final PnL: -593.69
        
        1 Reply Last reply Reply Quote 0
        • 1 / 1
        • First post
          Last post
        Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors