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/

    Help in implementing an SSL indicator strategy

    Indicators/Strategies/Analyzers
    2
    2
    90
    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.
    • Mariane Rodrigues Costa
      Mariane Rodrigues Costa last edited by

      I'm trying to make a strategy with the SSL indicator but I'm having trouble implementing it. Can anybody help me. That's what I managed to do. I want to make a strategy with the crossing of this indicator.

      from __future__ import (absolute_import, division, print_function, unicode_literals)
      import matplotlib.pyplot as plt
      import backtrader as bt
      import datetime
      
      class TestStrategy(bt.Strategy):
          lines = ('ssld', 'sslu')
          params = (('period', 30), ('max_position',1))
          plotinfo = dict(
              plot=True,
              plotname='SSL Channel',
              subplot=False,
              plotlinelabels=True)
          
          def _plotlabel(self):
              return [self.p.period]
          
          def log(self, txt, dt = None):
              '''Printing function for the complete strategy'''
              dt = dt or self.datas[0].datetime.date(0)
              print('%s %s' % (dt.isoformat(), txt))
          
          def __init__(self):
              self.dataclose = self.datas[0].close
              self.volume = self.datas[0].volume
      
              # Para acompanhar pedidos pendentes e comprar preço/comissão
              self.order = None
              self.buyprice = None
              self.buycomm = None
      
              #Adding SMA indicator
              self.addminperiod(self.p.period)
              self.hma_lo = bt.indicators.SmoothedMovingAverage(self.data.low, period=self.p.period)
              self.hma_hi = bt.indicators.SmoothedMovingAverage(self.data.high, period=self.p.period) 
      
          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(
                          'COMPRA Executada, Preço: %.2f, Custo: %.2f, Comm %.2f' %
                          (order.executed.price,
                           order.executed.value,
                           order.executed.comm)
                      )
      
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  
                  else:
                      self.log('VENDA Executada, Preço: %.2f, Custo: %.2f, Comm: %.2f' %
                               (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 
      
              self.log('LUCRO, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm))
      
          def next(self):
              #self.log('Close, %.2f' % self.dataclose[0])
      
              if self.order:
                  return
      
              hlv = 1 if self.data.close > self.hma_hi[0] else -1
              if hlv == 1:
                  self.lines.ssld[0] = self.hma_lo[0]
                  self.lines.sslu[0] = self.hma_hi[0]
                  if not self.position:
                      self.log('Compra, %.2f' % self.dataclose[0])
                      self.order = self.buy()
                      print(self.volume)
      
              elif hlv == -1:
                  self.lines.ssld[0] = self.hma_hi[0]
                  self.lines.sslu[0] = self.hma_lo[0]
                  if self.position:
                      self.close()
      
      if __name__ == '__main__':
          cerebro = bt.Cerebro()
          cerebro.addstrategy(TestStrategy)
          cerebro.broker.setcash(1000000.0)
          # Add a FixedSize sizer according to the stake
          cerebro.addsizer(bt.sizers.FixedSize, stake=100)
          # Set the commission
          cerebro.broker.setcommission(commission=0.0)
      
          #Adding data feed
          data = bt.feeds.YahooFinanceData(
              dataname = 'BTC-USD.csv', 
              fromdate = datetime.datetime(2015, 1, 1),
              todate = datetime.datetime(2020, 1, 1),
              reverse = False
          )
          cerebro.adddata(data)
      
          print('Valor Inicial: %.2f' % cerebro.broker.getvalue())
          cerebro.run()
          print('Valor Final: %.2f' % cerebro.broker.getvalue())
          cerebro.plot(iplot = False)
      
      run-out 1 Reply Last reply Reply Quote 0
      • run-out
        run-out @Mariane Rodrigues Costa last edited by

        @mariane-rodrigues-costa Have a look here for a solution

        RunBacktest.com

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