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/

    Crypto Trading Bot for Kraken

    General Code/Help
    4
    8
    2286
    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.
    • Thomas Fischer
      Thomas Fischer last edited by

      Hello all,

      I am new to Python Coding with Backtrader. I would like to create a Backtrader based Bot for Kraken Crypto exchange, but I ran into an issue with
      plotting the data for example. I have been using some SMA example code and add a CCXT Data Stream to it, it basically compiles, but it doesn't plot any data.
      I wonder if some one could have a look?

      Thank you in advance!

      from __future__ import(absolute_import, division, print_function, unicode_literals)
      from datetime import datetime, timedelta
      import backtrader as bt
      from backtrader import cerebro
      import time
      
      '''
      def connect_broker():
          config = {'urls': {'api': 'https://api.sandbox.gemini.com'},
                               'apiKey': 'XXXXX',
                               'secret': 'XXXXX',
                               'nonce': lambda: str(int(time.time() * 1000))
                              }
          broker = bt.brokers.CCXTBroker(exchange="kraken",
                                         currency="USD", config=config)
          cerebro.setbroker(broker)
      
          # Create data feeds
          data_ticks = bt.feeds.CCXT(exchange="kraken", symbol="BTC/USD",
                                    name="btc_usd_tick",
                                    timeframe=bt.TimeFrame.Ticks,
                                    compression=1, config=config)
          cerebro.adddata(data_ticks)
      '''
      
      class TestStrategy(bt.Strategy):
          #class SmaCross(bt.Strategy):
          # list of parameters which are configurable for the strategy
          params = dict(
              pfast=10,  # period for the fast moving average
              pslow=30   # period for the slow moving average
          )
      
          def __init__(self):
              sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
              sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
              self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal
      
          def next(self):
              if not self.position:  # not in the market
                  if self.crossover > 0:  # if fast crosses slow to the upside
                      self.buy()  # enter long
      
              elif self.crossover < 0:  # in the market & cross to the downside
                  self.close()  # close long position 
         
      if __name__ == '__main__':
          
          # Create Data Stream:
          hist_start_date = datetime.utcnow() - timedelta(minutes=60)
          data_min = bt.feeds.CCXT(exchange="kraken", symbol="BTC/USD", name="btc_usd_min", fromdate=hist_start_date,
                                   timeframe=bt.TimeFrame.Minutes)
          
          # Create Cerebro Entity
          cerebro = bt.Cerebro()
          cerebro.adddata(data_min)
          cerebro.addstrategy(TestStrategy)
          cerebro.run()
          cerebro.plot()
      
      
      B 1 Reply Last reply Reply Quote 0
      • B
        backtrader administrators @Thomas Fischer last edited by

        @Thomas-Fischer said in Crypto Trading Bot for Kraken:

        def next(self):
            if not self.position:  # not in the market
                if self.crossover > 0:  # if fast crosses slow to the upside
                    self.buy()  # enter long
        
            elif self.crossover < 0:  # in the market & cross to the downside
                self.close()  # close long position 
        

        Let me suggest that you add some logging there ... (a couple print statements will suffice). What you will probably see is nothing and that's why there is no plotting. One will then be able to conclude that no data is being downloaded.

        You can easily check if your code plots by switching to, for example, a csv-based data feed.

        Thomas Fischer 1 Reply Last reply Reply Quote 0
        • Thomas Fischer
          Thomas Fischer @backtrader last edited by

          @backtrader Hello, thank you for looking into this.

          If I do something stupid like:

          # Create data feeds
          try:
              hist_start_date = datetime.utcnow() - timedelta(minutes=3)
              data_min = bt.feeds.CCXT(exchange="kraken", symbol="BTC/USD", name="btc_usd_min",
                                   timeframe=bt.TimeFrame.Minutes, fromdate=hist_start_date, compression=1,
                                   config={'rateLimit': 10000, 'enableRateLimit': True}) #, historical=True)
          
          
          # data_min=bt.feeds.YahooFinanceData(dataname='MSFT',fromdate=datetime(2011,1,1),todate=datetime(2012,12,31))
          
              cerebro.adddata(data_min)
              print (data_min)
              cerebro.addstrategy(SmaCross)
              cerebro.run()
              cerebro.plot()
          
          except Exception as e:
              logging.error("Exeption", exc_info=True)
          
          

          I get:

          <backtrader.feeds.ccxt.CCXT object at 0x00000183FB3C3C88>
          

          Even with the Yahoo Feed it is not trading, but it is plotting the chart at least.
          I have the guts feeling the data needs to be formatted.

          B 1 Reply Last reply Reply Quote 0
          • Thomas Fischer
            Thomas Fischer last edited by

            Chart.PNG

            1 Reply Last reply Reply Quote 0
            • B
              backtrader administrators @Thomas Fischer last edited by

              @Thomas-Fischer said in Crypto Trading Bot for Kraken:

              Even with the Yahoo Feed it is not trading, but it is plotting the chart at least.

              Sorry, but the chart you show, has clearly trades on it.

              @Thomas-Fischer said in Crypto Trading Bot for Kraken:

                  print (data_min)
              

              Nobody said you have to print an object.

              @backtrader said in Crypto Trading Bot for Kraken:

              @Thomas-Fischer said in Crypto Trading Bot for Kraken:

              def next(self):
                 if not self.position:  # not in the market
                     if self.crossover > 0:  # if fast crosses slow to the upside
                         self.buy()  # enter long
              
                 elif self.crossover < 0:  # in the market & cross to the downside
                     self.close()  # close long position 
              
              

              Let me suggest that you add some logging there ... (a couple print statements will suffice)

              You put the print statements there in the next method, to log things like the close price (please see the Quickstart Guide Docs - Quickstart - https://www.backtrader.com/docu/quickstart/quickstart/) as in print(self.data.close[0])

              The fact that the Yahoo data feed "plots" is a very clear indication that your attempt with the other feed delivers no data points at all.

              Thomas Fischer 1 Reply Last reply Reply Quote 0
              • Thomas Fischer
                Thomas Fischer @backtrader last edited by

                @backtrader Thank you very much for the advice! I will have a closer look.

                1 Reply Last reply Reply Quote 0
                • Wayne Filkins 0
                  Wayne Filkins 0 last edited by

                  Did you ever finish this? I'm wanting to combine backtrader with Kraken so please let me know if it worked and if it's open source.

                  1 Reply Last reply Reply Quote 0
                  • R
                    rajanprabu last edited by

                    Have a look here..
                    https://github.com/Dave-Vallance/bt-ccxt-store/blob/master/samples/kraken-example.py

                    There is a sample script for kraken.

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