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/

    Backtrader + ccxt for bitMex online transactions, how to modify

    General Code/Help
    2
    10
    1486
    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.
    • 黄光裕
      黄光裕 last edited by

      from future import (absolute_import, division, print_function,
      unicode_literals)

      from datetime import datetime, timedelta
      import os.path # To manage paths
      import sys # To find out the script name (in argv[0])
      import pandas as pd

      from WindPy import w

      import time
      import backtrader as bt

      def connect_broker():
      config = {'urls': {'api': 'https://api.sandbox.gemini.com'},
      'apiKey': '',
      'secret': '',
      'nonce': lambda: str(int(time.time() * 1000))
      }
      # Create data feeds
      data_ticks = bt.feeds.CCXT(exchange='bitmex', symbol='BTC/USD',
      name="btc_usd_tick",
      timeframe=bt.TimeFrame.Minutes,
      compression=5, config=config)
      cerebro.adddata(data_ticks)

      Create a Stratey

      class TestStrategy(bt.Strategy):
      params = (
      ('sma1', 40),
      ('sma2', 200),
      ('oneplot', True)
      )

      def __init__(self):
          '''
          Create an dictionary of indicators so that we can dynamically add the
          indicators to the strategy using a loop. This mean the strategy will
          work with any numner of data feeds.
          '''
          self.inds = dict()
          for i, d in enumerate(self.datas):
              self.inds[d] = dict()
              self.inds[d]['sma1'] = bt.indicators.SimpleMovingAverage(
                  d.close, period=self.params.sma1)
              self.inds[d]['sma2'] = bt.indicators.SimpleMovingAverage(
                  d.close, period=self.params.sma2)
              self.inds[d]['cross'] = bt.indicators.CrossOver(self.inds[d]['sma1'], self.inds[d]['sma2'])
      
              if i > 0:  # Check we are not on the first loop of data feed:
                  if self.p.oneplot == True:
                      d.plotinfo.plotmaster = self.datas[0]
      
      def next(self):
          for i, d in enumerate(self.datas):
              dt, dn = self.datetime.date(), d._name
              pos = self.getposition(d).size
              if not pos:  # no market / no orders
                  if self.inds[d]['cross'][0] == 1:
                      self.buy(data=d, size=0.01)
      
                  elif self.inds[d]['cross'][0] == -1:
                      self.sell(data=d, size=0.01)
      
              else:
                  if self.inds[d]['cross'][0] == 1:
                      self.close(data=d._name)
                      self.buy(data=d, size=0.01)
      
                  elif self.inds[d]['cross'][0] == -1:
                      self.close(data=d)
                      self.sell(data=d, size=0.01)
      
      
      def notify_trade(self, trade):
          dt = self.data.datetime.date()
          if trade.isclosed:
              print('{} {} Closed: PnL Gross {}, Net {}'.format(
                  dt,
                  trade.data._name,
                  round(trade.pnl, 2),
                  round(trade.pnlcomm, 2)))
      

      if name == 'main':
      # Create a cerebro entity
      cerebro = bt.Cerebro()
      # Variable for our starting cash
      startcash = 0.1
      # Add a strategy
      cerebro.addstrategy(TestStrategy)

      # hist_start_date = datetime.utcnow() - timedelta(minutes=10)
      # data = bt.feeds.CCXT(exchange='bitmex', symbol="BTC/USD", name="btc_usd_min", fromdate=hist_start_date,
      #                      timeframe=bt.TimeFrame.Minutes)
      
      hist_start_date = datetime.utcnow() - timedelta(days=30)
      hist_end_date = datetime.utcnow() - timedelta(days=0)
      
      # data = bt.feeds.CCXT(exchange='bitmex', symbol='BTC/USD',
      #                      timeframe=bt.TimeFrame.Minutes, fromdate=hist_start_date, todate=hist_end_date,
      #                      ohlcv_limit=500)
      
      data = bt.feeds.CCXT(exchange='bitmex', symbol='BTC/USD',
                           timeframe=bt.TimeFrame.Minutes, fromdate=hist_start_date, todate=hist_end_date,
                           ohlcv_limit=500, compression=5)
      cerebro.adddata(data)
      # Set our desired cash start
      cerebro.broker.setcash(startcash)
      
      # Run over everything
      cerebro.run()
      
      # Get final portfolio Value
      portvalue = cerebro.broker.getvalue()
      pnl = portvalue - startcash
      # Add a FixedSize sizer according to the stake
      # cerebro.addsizer(bt.sizers.FixedSize, stake=0.05)
      
      # Set the commission
      cerebro.broker.setcommission(commission=0.001)
      
      # Print out the final result
      print('Final Portfolio Value: ${}'.format(portvalue))
      print('P/L: ${}'.format(pnl))
      
      # Finally plot the end results
      cerebro.plot()
      
      1 Reply Last reply Reply Quote 0
      • 黄光裕
        黄光裕 last edited by

        This strategy test results are very good. I want to use it to verify real transactions. How can I modify the above code?

        1 Reply Last reply Reply Quote 0
        • 黄光裕
          黄光裕 last edited by

          ![0_1552294618518_26e2d77f-dc65-4c04-8de4-9f8ecf8fa8bc-image.png](Uploading 100%)

          黄光裕 1 Reply Last reply Reply Quote 0
          • 黄光裕
            黄光裕 last edited by

            0_1552294911953_微信图片_20190311165651.png

            1 Reply Last reply Reply Quote 0
            • 黄光裕
              黄光裕 @黄光裕 last edited by

              How should this code be modified to enable BitMex real-time online transactions

              1 Reply Last reply Reply Quote 0
              • Robin Dhillon
                Robin Dhillon last edited by

                I am actually a bit confused. First off use those backticks for future reference
                "For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/"
                Coming back to your question, what do you mean by verifying real transactions?

                黄光裕 1 Reply Last reply Reply Quote 0
                • 黄光裕
                  黄光裕 @Robin Dhillon last edited by

                  @robin-dhillon Sorry, I'll pay attention next time.
                  Real transactions means to actually trade in bitMex, not retest.

                  1 Reply Last reply Reply Quote 0
                  • 黄光裕
                    黄光裕 last edited by

                    I hope that after testing through backtrader and ccxt, I will use the strategy directly to the production transaction.
                    Can you tell me how to do it? Thank you

                    1 Reply Last reply Reply Quote 0
                    • 黄光裕
                      黄光裕 last edited by

                      Get rid of this code and just keep executing it?
                      todate=hist_end_date

                      1 Reply Last reply Reply Quote 0
                      • 黄光裕
                        黄光裕 last edited by

                        How to Set Leverage of BitMex Futures Exchange?

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