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/

    Anyone use backtrader to do live trading on Bitcoin exchange?

    General Discussion
    pairs trading crypto
    79
    325
    143058
    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.
    • Nguyễn Tài Nguyên
      Nguyễn Tài Nguyên last edited by

      from __future__ import (absolute_import, division, print_function,
      						unicode_literals)
      
      import sys
      
      import backtrader as bt
      
      
      class TestStrategy(bt.Strategy):
      	def notify_data(self, data, status, *args, **kwargs):
      		print('*' * 5, 'DATA NOTIF:', data._getstatusname(status))
      
      	def next(self):
      		print('*' * 5, 'NEXT:', bt.num2date(self.data0.datetime[0]), self.data0._name, self.data0.open[0],
      			  bt.TimeFrame.getname(self.data0._timeframe), len(self.data0))
      
      
      def runstrategy(argv):
      	# Create a cerebro
      	cerebro = bt.Cerebro()
      
      	data = bt.feeds.CCXT(exchange='gdax', symbol='BTC/USD', timeframe=bt.TimeFrame.Ticks, compression=1)
      	cerebro.resampledata(data, timeframe=bt.TimeFrame.Seconds)
      	# cerebro.adddata(data)
      
      	# Add the strategy
      	cerebro.addstrategy(TestStrategy)
      
      	# Run the strategy
      	cerebro.run()
      
      
      if __name__ == '__main__':
      	sys.exit(runstrategy(sys.argv))
      

      @Ed-Bartosh . When I run this above code, it shows an error. How to fix it ?

        File "C:/Users/PC/PycharmProjects/trading/scr/test.py", line 34, in <module>
      	sys.exit(runstrategy(sys.argv))
        File "C:/Users/PC/PycharmProjects/trading/scr/test.py", line 30, in runstrategy
      	cerebro.run()
        File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\cerebro.py", line 1127, in run
      	runstrat = self.runstrategies(iterstrat)
        File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\cerebro.py", line 1295, in runstrategies
      	self._runnext(runstrats)
        File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\cerebro.py", line 1538, in _runnext
      	drets.append(d.next(ticks=False))
        File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\feed.py", line 404, in next
      	ret = self.load()
        File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\feed.py", line 476, in load
      	_loadret = self._load()
        File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\feeds\ccxt.py", line 91, in _load
      	self._fetch_ohlcv()
        File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\feeds\ccxt.py", line 110, in _fetch_ohlcv
      	granularity = self.store.get_granularity(self._timeframe, self._compression)
        File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\stores\ccxtstore.py", line 73, in get_granularity
      	(bt.TimeFrame.getname(timeframe), compression))
        File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\dataseries.py", line 45, in getname
      	if compression > 1 or tname == cls.Names[-1]:
      TypeError: unorderable types: NoneType() > int()
      
      E 1 Reply Last reply Reply Quote 0
      • E
        Ed Bartosh @Nguyễn Tài Nguyên last edited by

        @nguyễn-tài-nguyên said in Anyone use backtrader to do live trading on Bitcoin exchange?:

        cerebro.resampledata(data, timeframe=bt.TimeFrame.Seconds)

        You can try to pass compression to resampledata. This should theoreticall fix this.

        cerebro.resampledata(data,
                             timeframe=bt.TimeFrame.Seconds,
                             compression=1)
        
        Nguyễn Tài Nguyên 1 Reply Last reply Reply Quote 1
        • E
          Ed Bartosh @Søren Pallesen last edited by

          @søren-pallesen said in Anyone use backtrader to do live trading on Bitcoin exchange?:

          @Nguyễn-Tài-Nguyên I have the same issue. Its a quedtion for @Ed-Bartosh that I hope can spare some time soon to help us out.

          Sorry for this delay. Vacation time.

          Will look at this today or tomorrow.

          1 Reply Last reply Reply Quote 1
          • S
            Søren Pallesen last edited by

            Thx Ed - really appreciate that :-) ...hope you enjoyed the time off ...

            E 1 Reply Last reply Reply Quote 0
            • Nguyễn Tài Nguyên
              Nguyễn Tài Nguyên @Ed Bartosh last edited by Nguyễn Tài Nguyên

              edited this post

              1 Reply Last reply Reply Quote 0
              • E
                Ed Bartosh @Søren Pallesen last edited by

                @søren-pallesen said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                Thx Ed - really appreciate that :-) ...hope you enjoyed the time off ...

                I started to look at it today. I can see the issue with bitmex, but not with gdax. Can you explain what kind of output you expect? It would be great to show correct behaviour using another data feed (ib, oanda, etc).

                1 Reply Last reply Reply Quote 0
                • S
                  Søren Pallesen last edited by

                  @Ed-Bartosh thx for looking at this.

                  I expect the real time feed to continue so that i can trade against it live.

                  E 1 Reply Last reply Reply Quote 0
                  • E
                    Ed Bartosh @Søren Pallesen last edited by

                    @søren-pallesen said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                    @Ed-Bartosh thx for looking at this.

                    I expect the real time feed to continue so that i can trade against it live.

                    Can you show an example of this using ib or oanda data feed?

                    1 Reply Last reply Reply Quote 0
                    • S
                      Søren Pallesen last edited by Søren Pallesen

                      @Ed-Bartosh That would take some time to setup needing accounts for API etc. and before doing that please answer the if the following use cases are supported NOW by your implementation of CCXT integration:

                      • Use case 1: Live data feed from a CCXT exchange AND trading against a Backtrader broker i.e. simulated trading (I have provided my example of this in previous posts but the live feed stops)

                      • Use case 2: Live data feed from a CCXT exchange AND live trading against a CCXT broker i.e. real live trading

                      If you have either Use case 1 or 2 working could you please share a simple code examples? Also which exchanges have you tested and feel works? (for example you say that Gdax is working for you - please share example and a description of the behavior you are getting)

                      The main reason that I an picking Bitmex as my test exchange is that 1) the API is stable and robust and 2) the have a reliable sandbox (https://testnet.bitmex.com/) which makes testing safe.

                      My current objectives is to first get Use case 1 working with any exchange then in phase 2 get Use case 2 working on https://testnet.bitmex.com/.

                      E 1 Reply Last reply Reply Quote 0
                      • tornadoatc
                        tornadoatc last edited by

                        @Ed-Bartosh Hi, I am interested in your integration efforts with CCXT / backtrader / zipline.. I am wondering if you are familiar with the enigma catalyst effort (https://github.com/enigmampc/catalyst/tree/0.4.3) ?? As of this version, they have integrated the ccxt api. May this open source effort be of assistance?

                        Can you comment on what you strengths and weaknesses between catalyst and backtrader ? I am looking to jump in but wondering which tool to focus on.

                        E 1 Reply Last reply Reply Quote 0
                        • E
                          Ed Bartosh @tornadoatc last edited by

                          @tornadoatc said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                          @Ed-Bartosh Hi, I am interested in your integration efforts with CCXT / backtrader / zipline.. I am wondering if you are familiar with the enigma catalyst effort (https://github.com/enigmampc/catalyst/tree/0.4.3) ?? As of this version, they have integrated the ccxt api. May this open source effort be of assistance?

                          Can you comment on what you strengths and weaknesses between catalyst and backtrader ? I am looking to jump in but wondering which tool to focus on.

                          Hi,

                          Thank you for the info. I didn't know about enigma catalyst before.
                          As enigma is based on zipline I'd suggest you to look at zipline-live project. As one of its owners I can ensure they'll be happy to collaborate.

                          Regards,
                          Ed

                          1 Reply Last reply Reply Quote 0
                          • E
                            Ed Bartosh @Søren Pallesen last edited by

                            @søren-pallesen said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                            @Ed-Bartosh That would take some time to setup needing accounts for API etc. and before doing that please answer the if the following use cases are supported NOW by your implementation of CCXT integration

                            • Use case 1: Live data feed from a CCXT exchange AND trading against a Backtrader broker i.e. simulated trading (I have provided my example of this in previous posts but the live feed stops)

                            This should be fixed by this commit: https://github.com/bartosh/backtrader/commit/d6a82e3ca3b85239770b368c4814b1f138195036

                            here is a test script:

                            #!/usr/bin/env python
                            # -*- coding: utf-8; py-indent-offset:4 -*-
                            ###############################################################################
                            #
                            # Copyright (C) 2017,2018 Ed Bartosh <bartosh@gmail.com>
                            #
                            # This program is free software: you can redistribute it and/or modify
                            # it under the terms of the GNU General Public License as published by
                            # the Free Software Foundation, either version 3 of the License, or
                            # (at your option) any later version.
                            #
                            # This program is distributed in the hope that it will be useful,
                            # but WITHOUT ANY WARRANTY; without even the implied warranty of
                            # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                            # GNU General Public License for more details.
                            #
                            # You should have received a copy of the GNU General Public License
                            # along with this program.  If not, see <http://www.gnu.org/licenses/>.
                            #
                            ###############################################################################
                            from __future__ import (absolute_import, division, print_function,
                                                    unicode_literals)
                            
                            import sys
                            
                            import backtrader as bt
                            
                            class TestStrategy(bt.Strategy):
                                def next(self):
                                    for data in self.datas:
                                        print('*' * 5, 'NEXT:', bt.num2date(data.datetime[0]), data._name, data.open[0],
                                              data.high[0], data.low[0], data.close[0], data.volume[0],
                                              bt.TimeFrame.getname(data._timeframe), len(data))
                                        if not self.getposition(data):
                                            self.buy(data, exectype=bt.Order.Limit, size=10, price=data.close[0])
                            
                                def notify_order(self, order):
                                    print('*' * 5, "NOTIFY ORDER", order)
                            
                            def runstrategy(argv):
                                # Create a cerebro
                                cerebro = bt.Cerebro()
                            
                                # Create data feeds
                                data_ticks = bt.feeds.CCXT(exchange='gdax', symbol='BTC/USD', name="btc_usd_tick",
                                                           timeframe=bt.TimeFrame.Ticks, compression=1)
                                cerebro.adddata(data_ticks)
                            
                                # Add the strategy
                                cerebro.addstrategy(TestStrategy)
                            
                                # Run the strategy
                                cerebro.run()
                            
                            if __name__ == '__main__':
                                sys.exit(runstrategy(sys.argv))
                            

                            and its output:

                            (backtrader-ccxt) backtrader-ccxt (ccxt) $ ./bt-ccxt-no-broker.py 
                            ***** NEXT: 2018-01-07 23:27:02.790004 btc_usd_tick 16319.71 16319.71 16319.71 16319.71 0.42092738 Tick 1
                            ***** NOTIFY ORDER Ref: 1
                            OrdType: 0
                            OrdType: Buy
                            Status: 1
                            Status: Submitted
                            Size: 10
                            Price: 16319.71
                            Price Limit: None
                            TrailAmount: None
                            TrailPercent: None
                            ExecType: 2
                            ExecType: Limit
                            CommInfo: None
                            End of Session: 736702.0
                            Info: AutoOrderedDict()
                            Broker: None
                            Alive: True
                            ***** NOTIFY ORDER Ref: 1
                            OrdType: 0
                            OrdType: Buy
                            Status: 7
                            Status: Margin
                            Size: 10
                            Price: 16319.71
                            Price Limit: None
                            TrailAmount: None
                            TrailPercent: None
                            ExecType: 2
                            ExecType: Limit
                            CommInfo: None
                            End of Session: 736702.0
                            Info: AutoOrderedDict()
                            Broker: None
                            Alive: False
                            ***** NEXT: 2018-01-07 23:27:06.859002 btc_usd_tick 16322.0 16322.0 16322.0 16322.0 0.15175919 Tick 2
                            ***** NOTIFY ORDER Ref: 2
                            OrdType: 0
                            OrdType: Buy
                            Status: 1
                            Status: Submitted
                            Size: 10
                            Price: 16322.0
                            Price Limit: None
                            TrailAmount: None
                            TrailPercent: None
                            ExecType: 2
                            ExecType: Limit
                            CommInfo: None
                            End of Session: 736702.0
                            Info: AutoOrderedDict()
                            Broker: None
                            Alive: True
                            ***** NOTIFY ORDER Ref: 2
                            OrdType: 0
                            OrdType: Buy
                            Status: 7
                            Status: Margin
                            Size: 10
                            Price: 16322.0
                            Price Limit: None
                            TrailAmount: None
                            TrailPercent: None
                            ExecType: 2
                            ExecType: Limit
                            CommInfo: None
                            End of Session: 736702.0
                            Info: AutoOrderedDict()
                            Broker: None
                            Alive: False
                            ***** NEXT: 2018-01-07 23:27:09.158004 btc_usd_tick 16323.79 16323.79 16323.79 16323.79 0.0035 Tick 3
                            ***** NOTIFY ORDER Ref: 3
                            OrdType: 0
                            OrdType: Buy
                            Status: 1
                            Status: Submitted
                            Size: 10
                            Price: 16323.79
                            Price Limit: None
                            TrailAmount: None
                            TrailPercent: None
                            ExecType: 2
                            ExecType: Limit
                            CommInfo: None
                            End of Session: 736702.0
                            Info: AutoOrderedDict()
                            Broker: None
                            Alive: True
                            ***** NOTIFY ORDER Ref: 3
                            OrdType: 0
                            OrdType: Buy
                            Status: 7
                            Status: Margin
                            Size: 10
                            Price: 16323.79
                            Price Limit: None
                            TrailAmount: None
                            TrailPercent: None
                            ExecType: 2
                            ExecType: Limit
                            CommInfo: None
                            End of Session: 736702.0
                            Info: AutoOrderedDict()
                            Broker: None
                            Alive: False
                            ***** NEXT: 2018-01-07 23:27:18.672004 btc_usd_tick 16332.04 16332.04 16332.04 16332.04 0.011213 Tick 4
                            ***** NOTIFY ORDER Ref: 4
                            OrdType: 0
                            OrdType: Buy
                            Status: 1
                            Status: Submitted
                            Size: 10
                            Price: 16332.04
                            Price Limit: None
                            TrailAmount: None
                            TrailPercent: None
                            ExecType: 2
                            ExecType: Limit
                            CommInfo: None
                            End of Session: 736702.0
                            Info: AutoOrderedDict()
                            Broker: None
                            Alive: True
                            ***** NOTIFY ORDER Ref: 4
                            OrdType: 0
                            OrdType: Buy
                            Status: 7
                            Status: Margin
                            Size: 10
                            Price: 16332.04
                            Price Limit: None
                            TrailAmount: None
                            TrailPercent: None
                            ExecType: 2
                            ExecType: Limit
                            CommInfo: None
                            End of Session: 736702.0
                            Info: AutoOrderedDict()
                            Broker: None
                            Alive: False
                            ***** NEXT: 2018-01-07 23:27:18.672004 btc_usd_tick 16338.32 16338.32 16338.32 16338.32 1.19202592 Tick 5
                            ***** NOTIFY ORDER Ref: 5
                            OrdType: 0
                            OrdType: Buy
                            Status: 1
                            Status: Submitted
                            Size: 10
                            Price: 16338.32
                            Price Limit: None
                            TrailAmount: None
                            TrailPercent: None
                            ExecType: 2
                            ExecType: Limit
                            CommInfo: None
                            End of Session: 736702.0
                            Info: AutoOrderedDict()
                            Broker: None
                            Alive: True
                            ...
                            
                            • Use case 2: Live data feed from a CCXT exchange AND live trading against a CCXT broker i.e. real live trading

                            this is not working yet. It stops after getting historical price data and doesn't continue further. I'll look at it when I have time.

                            If you have either Use case 1 or 2 working could you please share a simple code examples? Also which exchanges have you tested and feel works? (for example you say that Gdax is working for you - please share example and a description of the behavior you are getting)

                            I only test it with gdax as a data feed and gemini as a broker.

                            The main reason that I an picking Bitmex as my test exchange is that 1) the API is stable and robust and 2) the have a reliable sandbox (https://testnet.bitmex.com/) which makes testing safe.

                            I'm going to fix bitmex data feed problem. It only produces one bar of historical data for some reason. It's item 1 in my todo list.

                            My current objectives is to first get Use case 1 working with any exchange then in phase 2 get Use case 2 working on https://testnet.bitmex.com/.

                            My current todo list has only 2 items:

                            • fix bitmex historical data issue
                            • make live trading after getting historical data working (issue number 2 in your list)

                            Let me know if you discover anything else. And thank you very much for the help!

                            1 Reply Last reply Reply Quote 0
                            • E
                              Ed Bartosh @Søren Pallesen last edited by

                              @søren-pallesen said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                              That is one bar... i must be missing some thing basic - please help? :-)

                              This should be fixed in the latest code.
                              Here is the example script:

                              from __future__ import (absolute_import, division, print_function,
                                                      unicode_literals)
                              
                              import sys
                              import time
                              
                              from datetime import datetime, timedelta
                              
                              import backtrader as bt
                              
                              class TestStrategy(bt.Strategy):
                                  def next(self):
                                      for data in self.datas:
                                          print('*' * 5, 'NEXT:', bt.num2date(data.datetime[0]), data._name, data.open[0], data.high[0],
                                                data.low[0], data.close[0], data.volume[0],
                                                bt.TimeFrame.getname(data._timeframe), len(data))
                              
                                  def notify_order(self, order):
                                      print('*' * 5, "NOTIFY ORDER", order)
                              
                              def runstrategy(argv):
                                  # Create a cerebro
                                  cerebro = bt.Cerebro()
                              
                                  # Create data feeds
                                  hist_start_date = datetime.utcnow() - timedelta(minutes=30)
                                  data_min = bt.feeds.CCXT(exchange="bitmex", symbol="BTC/USD", name="btc_usd_min",
                                                           timeframe=bt.TimeFrame.Minutes, fromdate=hist_start_date) #, historical=True)
                                  cerebro.adddata(data_min)
                              
                                  # Add the strategy
                                  cerebro.addstrategy(TestStrategy)
                              
                                  # Run the strategy
                                  cerebro.run()
                              
                              if __name__ == '__main__':
                                  sys.exit(runstrategy(sys.argv))
                              

                              And the output:

                              $ ./bt-ccxt-bitmex.py 
                              ***** NEXT: 2018-01-08 00:38:00 btc_usd_min 16195.5 16200.5 16195.5 16200.5 84491.0 Minute 1
                              ***** NEXT: 2018-01-08 00:39:00 btc_usd_min 16217.5 16217.0 16213.0 16213.0 22907.0 Minute 2
                              ***** NEXT: 2018-01-08 00:40:00 btc_usd_min 16217.0 16217.0 16195.5 16195.5 99852.0 Minute 3
                              

                              The issue with backtest on historical + live price data still remains unsolved. I probably messed something up in the feed code. Will try to fix it when I have time.

                              Any help is welcome as always.

                              Nguyễn Tài Nguyên 2 Replies Last reply Reply Quote 0
                              • Nguyễn Tài Nguyên
                                Nguyễn Tài Nguyên @Ed Bartosh last edited by

                                @ed-bartosh said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                                @søren-pallesen said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                                That is one bar... i must be missing some thing basic - please help? :-)

                                This should be fixed in the latest code.
                                Here is the example script:

                                from __future__ import (absolute_import, division, print_function,
                                                        unicode_literals)
                                
                                import sys
                                import time
                                
                                from datetime import datetime, timedelta
                                
                                import backtrader as bt
                                
                                class TestStrategy(bt.Strategy):
                                    def next(self):
                                        for data in self.datas:
                                            print('*' * 5, 'NEXT:', bt.num2date(data.datetime[0]), data._name, data.open[0], data.high[0],
                                                  data.low[0], data.close[0], data.volume[0],
                                                  bt.TimeFrame.getname(data._timeframe), len(data))
                                
                                    def notify_order(self, order):
                                        print('*' * 5, "NOTIFY ORDER", order)
                                
                                def runstrategy(argv):
                                    # Create a cerebro
                                    cerebro = bt.Cerebro()
                                
                                    # Create data feeds
                                    hist_start_date = datetime.utcnow() - timedelta(minutes=30)
                                    data_min = bt.feeds.CCXT(exchange="bitmex", symbol="BTC/USD", name="btc_usd_min",
                                                             timeframe=bt.TimeFrame.Minutes, fromdate=hist_start_date) #, historical=True)
                                    cerebro.adddata(data_min)
                                
                                    # Add the strategy
                                    cerebro.addstrategy(TestStrategy)
                                
                                    # Run the strategy
                                    cerebro.run()
                                
                                if __name__ == '__main__':
                                    sys.exit(runstrategy(sys.argv))
                                

                                And the output:

                                $ ./bt-ccxt-bitmex.py 
                                ***** NEXT: 2018-01-08 00:38:00 btc_usd_min 16195.5 16200.5 16195.5 16200.5 84491.0 Minute 1
                                ***** NEXT: 2018-01-08 00:39:00 btc_usd_min 16217.5 16217.0 16213.0 16213.0 22907.0 Minute 2
                                ***** NEXT: 2018-01-08 00:40:00 btc_usd_min 16217.0 16217.0 16195.5 16195.5 99852.0 Minute 3
                                

                                The issue with backtest on historical + live price data still remains unsolved. I probably messed something up in the feed code. Will try to fix it when I have time.

                                Any help is welcome as always.
                                Thank you very much for your awesome work :)

                                1 Reply Last reply Reply Quote 0
                                • Nguyễn Tài Nguyên
                                  Nguyễn Tài Nguyên @Ed Bartosh last edited by

                                  @ed-bartosh Hi, when I execute your code, it shows an error. How to fix it ? Thank you !

                                    File "C:/Users/PC/PycharmProjects/trading/scr/test.py", line 41, in <module>
                                  	sys.exit(runstrategy(sys.argv))
                                    File "C:/Users/PC/PycharmProjects/trading/scr/test.py", line 37, in runstrategy
                                  	cerebro.run()
                                    File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\cerebro.py", line 1127, in run
                                  	runstrat = self.runstrategies(iterstrat)
                                    File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\cerebro.py", line 1295, in runstrategies
                                  	self._runnext(runstrats)
                                    File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\cerebro.py", line 1626, in _runnext
                                  	strat._next()
                                    File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\strategy.py", line 325, in _next
                                  	super(Strategy, self)._next()
                                    File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\lineiterator.py", line 268, in _next
                                  	self.nextstart()  # only called for the 1st value
                                    File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\lineiterator.py", line 342, in nextstart
                                  	self.next()
                                    File "C:/Users/PC/PycharmProjects/trading/scr/test.py", line 17, in next
                                  	bt.TimeFrame.getname(data._timeframe), len(data))
                                    File "C:\Users\PC\PycharmProjects\trading\venv\lib\site-packages\backtrader\dataseries.py", line 45, in getname
                                  	if compression > 1 or tname == cls.Names[-1]:
                                  TypeError: unorderable types: NoneType() > int()
                                  
                                  E 1 Reply Last reply Reply Quote 0
                                  • E
                                    Ed Bartosh @Nguyễn Tài Nguyên last edited by

                                    @nguyễn-tài-nguyên said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                                    @ed-bartosh Hi, when I execute your code, it shows an error. How to fix it ?

                                    You can try to add 'compression=1' to the parameters:

                                    data_min = bt.feeds.CCXT(exchange="bitmex",
                                                                 symbol="BTC/USD",name="btc_usd_min",
                                                                 timeframe=bt.TimeFrame.Minutes,
                                                                 compression=1,
                                                                 fromdate=hist_start_date)
                                    
                                    Nguyễn Tài Nguyên 1 Reply Last reply Reply Quote 0
                                    • S
                                      Søren Pallesen last edited by

                                      @Ed-Bartosh live feed with Bitmex works (THANKS !!!) however I had to adjust rateLimit (to 15000) and Count (to 100) not get rejected by the API - so maybe you should make these parameters to the bt.feeds.CCXT call.

                                      With Bitmex I can get 1M, 5M, 1H and 1D resolution do you have any ideas how to resample the data for a strategy that needs 2H candles? Is there anyway to manipulate the data feed while running the strategy?

                                      I tried to add the data with cerebro.resampledata but that does not work.

                                      lalas 1 Reply Last reply Reply Quote 0
                                      • S
                                        Søren Pallesen last edited by

                                        @Ed-Bartosh I would be fantastic if you could fix the historical data load with Bitmex as well so the indicators get their warm up data upfront. Thx again for you help.

                                        1 Reply Last reply Reply Quote 0
                                        • Nguyễn Tài Nguyên
                                          Nguyễn Tài Nguyên @Ed Bartosh last edited by

                                          @ed-bartosh said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                                          compression=1'

                                          @ed-bartosh said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                                          @nguyễn-tài-nguyên said in Anyone use backtrader to do live trading on Bitcoin exchange?:

                                          @ed-bartosh Hi, when I execute your code, it shows an error. How to fix it ?

                                          You can try to add 'compression=1' to the parameters:

                                          data_min = bt.feeds.CCXT(exchange="bitmex",
                                                                       symbol="BTC/USD",name="btc_usd_min",
                                                                       timeframe=bt.TimeFrame.Minutes,
                                                                       compression=1,
                                                                       fromdate=hist_start_date)
                                          

                                          I did it but it still show that error

                                          E 1 Reply Last reply Reply Quote 0
                                          • K
                                            kazi @Ed Bartosh last edited by

                                            Hi @ed-bartosh, I have started testing and I have not been able to get more than a few candles without encountering the following error:

                                            Traceback (most recent call last):
                                              File "/usr/local/lib/python3.6/site-packages/ccxt/base/exchange.py", line 344, in fetch_requests
                                                response.raise_for_status()
                                              File "/usr/local/lib/python3.6/site-packages/requests/models.py", line 935, in raise_for_status
                                                raise HTTPError(http_error_msg, response=self)
                                            requests.exceptions.HTTPError: 502 Server Error: Bad Gateway for url: https://api.hitbtc.com/api/2/public/candles/EOSBTC?period=M5&limit=450
                                            
                                            During handling of the above exception, another exception occurred:
                                            
                                            Traceback (most recent call last):
                                              File "hist-test.py", line 143, in <module>
                                                sys.exit(runstrategy(sys.argv))
                                              File "hist-test.py", line 140, in runstrategy
                                                cerebro.run()
                                              File "/usr/local/lib/python3.6/site-packages/backtrader/cerebro.py", line 1127, in run
                                                runstrat = self.runstrategies(iterstrat)
                                              File "/usr/local/lib/python3.6/site-packages/backtrader/cerebro.py", line 1295, in runstrategies
                                                self._runnext(runstrats)
                                              File "/usr/local/lib/python3.6/site-packages/backtrader/cerebro.py", line 1538, in _runnext
                                                drets.append(d.next(ticks=False))
                                              File "/usr/local/lib/python3.6/site-packages/backtrader/feed.py", line 404, in next
                                                ret = self.load()
                                              File "/usr/local/lib/python3.6/site-packages/backtrader/feed.py", line 476, in load
                                                _loadret = self._load()
                                              File "/usr/local/lib/python3.6/site-packages/backtrader/feeds/ccxt.py", line 91, in _load
                                                self._fetch_ohlcv()
                                              File "/usr/local/lib/python3.6/site-packages/backtrader/feeds/ccxt.py", line 125, in _fetch_ohlcv
                                                since=since, limit=limit)[::-1]:
                                              File "/usr/local/lib/python3.6/site-packages/backtrader/stores/ccxtstore.py", line 87, in retry_method
                                                return method(self, *args, **kwargs)
                                              File "/usr/local/lib/python3.6/site-packages/backtrader/stores/ccxtstore.py", line 121, in fetch_ohlcv
                                                return self.exchange.fetch_ohlcv(symbol, timeframe=timeframe, since=since, limit=limit)
                                              File "/usr/local/lib/python3.6/site-packages/ccxt/hitbtc2.py", line 671, in fetch_ohlcv
                                                response = self.publicGetCandlesSymbol(self.extend(request, params))
                                              File "/usr/local/lib/python3.6/site-packages/ccxt/hitbtc2.py", line 1001, in request
                                                response = self.fetch2(path, api, method, params, headers, body)
                                              File "/usr/local/lib/python3.6/site-packages/ccxt/base/exchange.py", line 289, in fetch2
                                                return self.fetch_requests(request['url'], request['method'], request['headers'], request['body'])
                                              File "/usr/local/lib/python3.6/site-packages/ccxt/base/exchange.py", line 357, in fetch_requests
                                                self.handle_rest_errors(e, response.status_code, self.last_http_response, url, method)
                                              File "/usr/local/lib/python3.6/site-packages/ccxt/base/exchange.py", line 436, in handle_rest_errors
                                                self.raise_error(error, url, method, exception if exception else http_status_code, response)
                                              File "/usr/local/lib/python3.6/site-packages/ccxt/base/exchange.py", line 271, in raise_error
                                                details,
                                            ccxt.base.errors.ExchangeNotAvailable: hitbtc2 GET https://api.hitbtc.com/api/2/public/candles/EOSBTC?period=M5&limit=450 502 Server Error: Bad Gateway for url: https://api.hitbtc.com/api/2/public/candles/EOSBTC?period=M5&limit=450 <html>
                                            <head><title>502 Bad Gateway</title></head>
                                            <body bgcolor="white">
                                            <center><h1>502 Bad Gateway</h1></center>
                                            <hr><center>nginx</center>
                                            </body>
                                            </html>
                                            

                                            I have checked whether the site is accessible and found no issue, I am getting roughly 12 ms latency to the api host.

                                            I was wondering how the fromdate= works, is it supposed to get the historical data from eg https://api.hitbtc.com/api/2/public/candles/EOSBTC?period=M5&limit=450 or will it poll for new data? I have noticed that after adding an indicator the script will hang, here is an example:

                                            from datetime import datetime, timedelta
                                            import sys
                                            import backtrader as bt
                                            import backtrader.indicators as btind
                                            import backtrader.feeds as btfeeds
                                            
                                            from pandas import bdate_range
                                            
                                            class TestStrategy(bt.Strategy):
                                                
                                                def __init__(self):
                                                    self.sma = btind.SimpleMovingAverage(self.data, period=10)
                                                    print("initializtion complete")
                                            
                                                def next(self):
                                                    for data in self.datas:
                                                        print('*' * 5, 'NEXT:', bt.num2date(data.datetime[0]), data._name, data.open[0], data.high[0],
                                                              data.low[0], data.close[0], data.volume[0],
                                                              bt.TimeFrame.getname(data._timeframe), len(data))
                                                        if not self.getposition(data) and data.close[0] > self.sma[0]:
                                                            order = self.buy(data, exectype=bt.Order.Market, size=10)
                                                        elif self.getposition(data) and data.close[0] < self.sma[0]:
                                                            order = self.sell(data, exectype=bt.Order.Market, size=10)
                                            
                                                def notify_order(self, order):
                                                    print('*' * 5, "NOTIFY ORDER", order)
                                            
                                            def runstrategy(argv):
                                                # Create a cerebro
                                                cerebro = bt.Cerebro()
                                                
                                                # Create data feeds
                                                hist_start_date = datetime.utcnow() - timedelta(minutes=30)
                                                data = bt.feeds.CCXT(exchange="hitbtc2", symbol="BTC/USD", name="btc_usd_1m", timeframe=bt.TimeFrame.Minutes, compression=1, fromdate=hist_start_date)
                                                cerebro.adddata(data)
                                                print(data[0])
                                                # Add the strategy
                                                cerebro.addstrategy(TestStrategy)
                                            
                                                # Run the strategy
                                                cerebro.run(stdstats=False)
                                            
                                            if __name__ == '__main__':
                                                sys.exit(runstrategy(sys.argv))
                                            

                                            This will start printing data after 10mins.

                                            Thank you in advance!

                                            1 Reply Last reply Reply Quote 0
                                            • 1
                                            • 2
                                            • 5
                                            • 6
                                            • 7
                                            • 8
                                            • 9
                                            • 16
                                            • 17
                                            • 7 / 17
                                            • First post
                                              Last post
                                            Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors