Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. mr kite
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    • Profile
    • Following 0
    • Followers 0
    • Topics 0
    • Posts 2
    • Best 0
    • Controversial 0
    • Groups 0

    mr kite

    @mr kite

    0
    Reputation
    47
    Profile views
    2
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    mr kite Unfollow Follow

    Latest posts made by mr kite

    • RE: Anyone use backtrader to do live trading on Bitcoin exchange?

      @ThisMustBeTrue Thanks for your debugging. It works flawlessly. But for better and true logging, user must call order data manually in "notify_order()" function. This is my custom function for multiple coins either for backtesting and live production. I added these lines:

          def notify_order(self, order, *args, **kwargs):
              dict = order.__dict__
              target = self.data._name.replace('/USDT', '')
              if ENV == PRODUCTION:
                  exec_time = dict['ccxt_order']['datetime']
                  exec_price = dict['ccxt_order']['average']
                  pair = dict['ccxt_order']['symbol']
                  cost = dict['ccxt_order']['cost']
                  size = dict['ccxt_order']['filled']
                  target = pair.replace('/USDT', '')
              else:
                  pass
      ....#continues as same.
      
      posted in General Discussion
      mr kite
      mr kite
    • RE: Anyone use backtrader to do live trading on Bitcoin exchange?

      Hello everyone,

      I am trying to test @Rodrigo-Brito 's repo on Binance live.
      https://github.com/rodrigo-brito/backtrader-binance-bot

      Here is the base code class for strategy.

      class StrategyBase(bt.Strategy):
          def __init__(self):
              self.order = None
              self.last_operation = "SELL"
              self.status = "DISCONNECTED"
              self.bar_executed = 0
              self.buy_price_close = None
              self.soft_sell = False
              self.hard_sell = False
              self.log("Base strategy initialized")
      
          def reset_sell_indicators(self):
              self.soft_sell = False
              self.hard_sell = False
              self.buy_price_close = None
      
          def notify_data(self, data, status, *args, **kwargs):
              self.status = data._getstatusname(status)
              print(self.status)
              if status == data.LIVE:
                  self.log("LIVE DATA - Ready to trade")
      
          def short(self):
              if self.last_operation == "SELL":
                  return
      
              if config.ENV == config.DEVELOPMENT:
                  self.log("Sell ordered: $%.2f" % self.data0.close[0])
                  return self.sell()
      
              cash, value = self.broker.get_wallet_balance(config.COIN_TARGET)
              amount = value*0.99
              self.log("Sell ordered: $%.2f. Amount %.6f %s - $%.2f USDT" % (self.data0.close[0],
                                                                             amount, config.COIN_TARGET, value), True)
              return self.sell(size=amount)
      
          def long(self):
              if self.last_operation == "BUY":
                  return
      
              self.log("Buy ordered: $%.2f" % self.data0.close[0], True)
              self.buy_price_close = self.data0.close[0]
              price = self.data0.close[0]
      
              if config.ENV == config.DEVELOPMENT:
                  return self.buy()
      
              cash, value = self.broker.get_wallet_balance(config.COIN_REFER)
              amount = (value / price) * 0.99  # Workaround to avoid precision issues
              self.log("Buy ordered: $%.2f. Amount %.6f %s. Ballance $%.2f USDT" % (self.data0.close[0],
                                                                                    amount, config.COIN_TARGET, value), True)
              return self.buy(size=amount)
      
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted]:
                  # Buy/Sell order submitted/accepted to/by broker - Nothing to do
                  self.log('ORDER ACCEPTED/SUBMITTED')
                  self.order = order
                  return
      
              if order.status in [order.Expired]:
                  self.log('BUY EXPIRED', True)
      
              elif order.status in [order.Completed]:
                  if order.isbuy():
                      self.last_operation = "BUY"
                      self.log(
                          'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                          (order.executed.price,
                           order.executed.value,
                           order.executed.comm), True)
                      if config.ENV == config.PRODUCTION:
                          print(order.__dict__)
                          print(
                              'BUY EXECUTED, Price: %.8f, Cost: %.8f, Comm %.8f' %
                              (order.executed.price,
                               order.executed.value,
                               order.executed.comm), True)
      
                  else:  # Sell
                      self.last_operation = "SELL"
                      self.reset_sell_indicators()
                      self.log('SELL EXECUTED, Price: %.8f, Cost: %.8f, Comm %.8f' %
                               (order.executed.price,
                                order.executed.value,
                                order.executed.comm), True)
                      print(
                          'SELL EXECUTED, Price: %.8f, Cost: %.8f, Comm %.8f' %
                          (order.executed.price,
                           order.executed.value,
                           order.executed.comm), True)
      
                  # Sentinel to None: new orders allowed
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log('Order Canceled/Margin/Rejected: Status %s - %s' % (order.Status[order.status],
                                                                               self.last_operation), True)
      
              self.order = None
      

      It works for a while then crashes. I couldn't figure out why. Also order.executed.XXX returns zero and gets unsupported operand type for backtrader/position.py

      What am i missing?

      Here is the output:

      ENV =  production
      Starting Portfolio Value: 0.00045425
      DELAYED
      LIVE
      {'dteos': 737246.9999999999, 'exectype': 0, 'ordtype': 0, 'size': 0.017, 'position': 0, 'p': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffaced6b940>, 'ref': 1, 'status': 4, 'data': <ccxtbt.ccxtfeed.CCXTFeed object at 0x7ffad7e55f28>, 'executed': <backtrader.order.OrderData object at 0x7ffae95f9438>, 'params': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffaced6b940>, 'broker': None, '_active': True, 'ccxt_order': {'price': 0.02231764705882353, 'datetime': '2019-07-26T19:53:19.784Z', 'symbol': 'ETH/BTC', 'lastTradeTimestamp': None, 'amount': 0.017, 'remaining': 0.0, 'average': 0.02231764705882353, 'fee': None, 'side': 'buy', 'type': 'market', 'id': '441732094', 'cost': 0.0003794, 'timestamp': 1564170799784, 'status': 'closed', 'info': {'price': '0.00000000', 'icebergQty': '0.00000000', 'type': 'MARKET', 'cummulativeQuoteQty': '0.00037940', 'orderId': 441732094, 'executedQty': '0.01700000', 'side': 'BUY', 'isWorking': True, 'stopPrice': '0.00000000', 'time': 1564170799784, 'origQty': '0.01700000', 'symbol': 'ETHBTC', 'updateTime': 1564170799784, 'clientOrderId': 'Ma4x8A2WqBudmPuOtdVEPB', 'timeInForce': 'GTC', 'status': 'FILLED'}, 'filled': 0.017, 'trades': None}, 'owner': <live_strategy.bt_bandtrader_v3_trend.Strategy object at 0x7ffad7e55cc0>, 'info': AutoOrderedDict(), 'created': <backtrader.order.OrderData object at 0x7ffad7e77828>, '_limitoffset': 0.0, '_plimit': None, 'comminfo': None, 'triggered': False}
      BUY EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      {'dteos': 737246.9999999999, 'exectype': 0, 'ordtype': 0, 'size': 0.017, 'position': 0, 'p': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffaced6b940>, 'ref': 1, 'status': 4, 'data': <ccxtbt.ccxtfeed.CCXTFeed object at 0x7ffad7e55f28>, 'executed': <backtrader.order.OrderData object at 0x7ffae95f9438>, 'params': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffaced6b940>, 'broker': None, '_active': True, 'ccxt_order': {'price': 0.02231764705882353, 'datetime': '2019-07-26T19:53:19.784Z', 'symbol': 'ETH/BTC', 'lastTradeTimestamp': None, 'amount': 0.017, 'remaining': 0.0, 'average': 0.02231764705882353, 'fee': None, 'side': 'buy', 'type': 'market', 'id': '441732094', 'cost': 0.0003794, 'timestamp': 1564170799784, 'status': 'closed', 'info': {'price': '0.00000000', 'icebergQty': '0.00000000', 'type': 'MARKET', 'cummulativeQuoteQty': '0.00037940', 'orderId': 441732094, 'executedQty': '0.01700000', 'side': 'BUY', 'isWorking': True, 'stopPrice': '0.00000000', 'time': 1564170799784, 'origQty': '0.01700000', 'symbol': 'ETHBTC', 'updateTime': 1564170799784, 'clientOrderId': 'Ma4x8A2WqBudmPuOtdVEPB', 'timeInForce': 'GTC', 'status': 'FILLED'}, 'filled': 0.017, 'trades': None}, 'owner': <live_strategy.bt_bandtrader_v3_trend.Strategy object at 0x7ffad7e55cc0>, 'info': AutoOrderedDict(), 'created': <backtrader.order.OrderData object at 0x7ffad7e77828>, '_limitoffset': 0.0, '_plimit': None, 'comminfo': None, 'triggered': False}
      BUY EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      SELL EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      SELL EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      {'dteos': 737246.9999999999, 'exectype': 0, 'ordtype': 0, 'size': 0.127, 'position': 0, 'p': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffacef8a3c8>, 'ref': 3, 'status': 4, 'data': <ccxtbt.ccxtfeed.CCXTFeed object at 0x7ffad7e55f28>, 'executed': <backtrader.order.OrderData object at 0x7ffacef46518>, 'params': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffacef8a3c8>, 'broker': None, '_active': True, 'ccxt_order': {'price': 0.022296929133858265, 'datetime': '2019-07-26T19:55:23.200Z', 'symbol': 'ETH/BTC', 'lastTradeTimestamp': None, 'amount': 0.127, 'remaining': 0.0, 'average': 0.022296929133858265, 'fee': None, 'side': 'buy', 'type': 'market', 'id': '441732983', 'cost': 0.00283171, 'timestamp': 1564170923200, 'status': 'closed', 'info': {'price': '0.00000000', 'icebergQty': '0.00000000', 'type': 'MARKET', 'cummulativeQuoteQty': '0.00283171', 'orderId': 441732983, 'executedQty': '0.12700000', 'side': 'BUY', 'isWorking': True, 'stopPrice': '0.00000000', 'time': 1564170923200, 'origQty': '0.12700000', 'symbol': 'ETHBTC', 'updateTime': 1564170923200, 'clientOrderId': '2ZWJFmhksnBVwpql2Ur0C4', 'timeInForce': 'GTC', 'status': 'FILLED'}, 'filled': 0.127, 'trades': None}, 'owner': <live_strategy.bt_bandtrader_v3_trend.Strategy object at 0x7ffad7e55cc0>, 'info': AutoOrderedDict(), 'created': <backtrader.order.OrderData object at 0x7ffacef465f8>, '_limitoffset': 0.0, '_plimit': None, 'comminfo': None, 'triggered': False}
      BUY EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      {'dteos': 737246.9999999999, 'exectype': 0, 'ordtype': 0, 'size': 0.127, 'position': 0, 'p': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffacef8a3c8>, 'ref': 3, 'status': 4, 'data': <ccxtbt.ccxtfeed.CCXTFeed object at 0x7ffad7e55f28>, 'executed': <backtrader.order.OrderData object at 0x7ffacef46518>, 'params': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffacef8a3c8>, 'broker': None, '_active': True, 'ccxt_order': {'price': 0.022296929133858265, 'datetime': '2019-07-26T19:55:23.200Z', 'symbol': 'ETH/BTC', 'lastTradeTimestamp': None, 'amount': 0.127, 'remaining': 0.0, 'average': 0.022296929133858265, 'fee': None, 'side': 'buy', 'type': 'market', 'id': '441732983', 'cost': 0.00283171, 'timestamp': 1564170923200, 'status': 'closed', 'info': {'price': '0.00000000', 'icebergQty': '0.00000000', 'type': 'MARKET', 'cummulativeQuoteQty': '0.00283171', 'orderId': 441732983, 'executedQty': '0.12700000', 'side': 'BUY', 'isWorking': True, 'stopPrice': '0.00000000', 'time': 1564170923200, 'origQty': '0.12700000', 'symbol': 'ETHBTC', 'updateTime': 1564170923200, 'clientOrderId': '2ZWJFmhksnBVwpql2Ur0C4', 'timeInForce': 'GTC', 'status': 'FILLED'}, 'filled': 0.127, 'trades': None}, 'owner': <live_strategy.bt_bandtrader_v3_trend.Strategy object at 0x7ffad7e55cc0>, 'info': AutoOrderedDict(), 'created': <backtrader.order.OrderData object at 0x7ffacef465f8>, '_limitoffset': 0.0, '_plimit': None, 'comminfo': None, 'triggered': False}
      BUY EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      SELL EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      SELL EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      {'dteos': 737246.9999999999, 'exectype': 0, 'ordtype': 0, 'size': 0.126, 'position': 0, 'p': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffacef46d68>, 'ref': 5, 'status': 4, 'data': <ccxtbt.ccxtfeed.CCXTFeed object at 0x7ffad7e55f28>, 'executed': <backtrader.order.OrderData object at 0x7ffacef464a8>, 'params': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffacef46d68>, 'broker': None, '_active': True, 'ccxt_order': {'price': 0.022314285714285714, 'datetime': '2019-07-26T19:56:20.376Z', 'symbol': 'ETH/BTC', 'lastTradeTimestamp': None, 'amount': 0.126, 'remaining': 0.0, 'average': 0.022314285714285714, 'fee': None, 'side': 'buy', 'type': 'market', 'id': '441733466', 'cost': 0.0028116, 'timestamp': 1564170980376, 'status': 'closed', 'info': {'price': '0.00000000', 'icebergQty': '0.00000000', 'type': 'MARKET', 'cummulativeQuoteQty': '0.00281160', 'orderId': 441733466, 'executedQty': '0.12600000', 'side': 'BUY', 'isWorking': True, 'stopPrice': '0.00000000', 'time': 1564170980376, 'origQty': '0.12600000', 'symbol': 'ETHBTC', 'updateTime': 1564170980376, 'clientOrderId': 'TwXVKXWuXd1MRZ7Fcmjruk', 'timeInForce': 'GTC', 'status': 'FILLED'}, 'filled': 0.126, 'trades': None}, 'owner': <live_strategy.bt_bandtrader_v3_trend.Strategy object at 0x7ffad7e55cc0>, 'info': AutoOrderedDict(), 'created': <backtrader.order.OrderData object at 0x7ffacef46eb8>, '_limitoffset': 0.0, '_plimit': None, 'comminfo': None, 'triggered': False}
      BUY EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      {'dteos': 737246.9999999999, 'exectype': 0, 'ordtype': 0, 'size': 0.126, 'position': 0, 'p': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffacef46d68>, 'ref': 5, 'status': 4, 'data': <ccxtbt.ccxtfeed.CCXTFeed object at 0x7ffad7e55f28>, 'executed': <backtrader.order.OrderData object at 0x7ffacef464a8>, 'params': <backtrader.metabase.AutoInfoClass_OrderBase_CCXTOrder object at 0x7ffacef46d68>, 'broker': None, '_active': True, 'ccxt_order': {'price': 0.022314285714285714, 'datetime': '2019-07-26T19:56:20.376Z', 'symbol': 'ETH/BTC', 'lastTradeTimestamp': None, 'amount': 0.126, 'remaining': 0.0, 'average': 0.022314285714285714, 'fee': None, 'side': 'buy', 'type': 'market', 'id': '441733466', 'cost': 0.0028116, 'timestamp': 1564170980376, 'status': 'closed', 'info': {'price': '0.00000000', 'icebergQty': '0.00000000', 'type': 'MARKET', 'cummulativeQuoteQty': '0.00281160', 'orderId': 441733466, 'executedQty': '0.12600000', 'side': 'BUY', 'isWorking': True, 'stopPrice': '0.00000000', 'time': 1564170980376, 'origQty': '0.12600000', 'symbol': 'ETHBTC', 'updateTime': 1564170980376, 'clientOrderId': 'TwXVKXWuXd1MRZ7Fcmjruk', 'timeInForce': 'GTC', 'status': 'FILLED'}, 'filled': 0.126, 'trades': None}, 'owner': <live_strategy.bt_bandtrader_v3_trend.Strategy object at 0x7ffad7e55cc0>, 'info': AutoOrderedDict(), 'created': <backtrader.order.OrderData object at 0x7ffacef46eb8>, '_limitoffset': 0.0, '_plimit': None, 'comminfo': None, 'triggered': False}
      BUY EXECUTED, Price: 0.00000000, Cost: 0.00000000, Comm 0.00000000 True
      Finished with error:  unsupported operand type(s) for *: 'NoneType' and 'float'
      Traceback (most recent call last):
        File "/home/tunc/PycharmProjects/backtesting/main.py", line 109, in <module>
          except KeyboardInterrupt:
        File "/home/tunc/PycharmProjects/backtesting/main.py", line 94, in main
          
        File "/home/tunc/PycharmProjects/backtesting/venv/lib/python3.5/site-packages/backtrader/cerebro.py", line 1127, in run
          runstrat = self.runstrategies(iterstrat)
        File "/home/tunc/PycharmProjects/backtesting/venv/lib/python3.5/site-packages/backtrader/cerebro.py", line 1298, in runstrategies
          self._runnext(runstrats)
        File "/home/tunc/PycharmProjects/backtesting/venv/lib/python3.5/site-packages/backtrader/cerebro.py", line 1623, in _runnext
          self._brokernotify()
        File "/home/tunc/PycharmProjects/backtesting/venv/lib/python3.5/site-packages/backtrader/cerebro.py", line 1360, in _brokernotify
          self._broker.next()
        File "/home/tunc/PycharmProjects/backtesting/venv/lib/python3.5/site-packages/ccxtbt/ccxtbroker.py", line 203, in next
          pos.update(o_order.size, o_order.price)
        File "/home/tunc/PycharmProjects/backtesting/venv/lib/python3.5/site-packages/backtrader/position.py", line 193, in update
          self.price = (self.price * oldsize + size * price) / self.size
      TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'
      
      posted in General Discussion
      mr kite
      mr kite