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



  • 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()


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



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



  • 0_1552294911953_微信图片_20190311165651.png



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



  • 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?



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



  • 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



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



  • How to Set Leverage of BitMex Futures Exchange?


Log in to reply
 

});