Esempio n. 1
0
def main():
    cerebro = bt.Cerebro(quicknotify=True)
    apikey, secret = read(
        '/home/rick/PycharmProjects/Btc/huobittrade/binance.txt')

    broker_config = {
        'apiKey': apikey,
        'secret': secret,
        'nonce': lambda: str(int(time.time() * 1000)),
        'enableRateLimit': True,
    }
    store = CCXTStore(exchange='binance',
                      currency='BTC',
                      config=broker_config,
                      retries=5,
                      debug=True)
    broker_mapping = {
        'order_types': {
            bt.Order.Market: 'market',
            bt.Order.Limit: 'limit',
            bt.Order.Stop:
            'stop-loss',  # stop-loss for kraken, stop for bitmex
            bt.Order.StopLimit: 'stop limit'
        },
        'mappings': {
            'closed_order': {
                'key': 'status',
                'value': 'closed'
            },
            'canceled_order': {
                'key': 'result',
                'value': 1
            }
        }
    }

    broker = store.getbroker(broker_mapping=broker_mapping)
    cerebro.setbroker(broker)

    hist_start_date = dt.datetime.utcnow() - dt.timedelta(minutes=2)
    data = store.getdata(dataname='BTC/USDT',
                         name="BTC/USDT",
                         timeframe=bt.TimeFrame.Minutes,
                         fromdate=hist_start_date,
                         compression=30,
                         ohlcv_limit=99999)

    cerebro.adddata(data)
    cerebro.addstrategy(CustomStrategy)
    initial_value = cerebro.broker.getvalue()
    print('Starting Portfolio Value: %.2f' % initial_value)
    result = cerebro.run()
    final_value = cerebro.broker.getvalue()
    print('Final Portfolio Value: %.2f' % final_value)
Esempio n. 2
0
def connect_broker():
    apikey = 'siX-NO9IeVWstmn1zA2e904N'
    secret = 'ieEjNwz9TDAzg_B2EVkpgzkchDeNmyy9_UNB03B567Gwh0A_'

    cerebro = bt.Cerebro(quicknotify=True)

    # Add the strategy
    cerebro.addstrategy(TestStrategy)

    # Create our store
    config = {'apiKey': apikey, 'secret': secret, 'enableRateLimit': True}

    # IMPORTANT NOTE - Kraken (and some other exchanges) will not return any values
    # for get cash or value if You have never held any LTC coins in your account.
    # So switch LTC to a coin you have funded previously if you get errors
    store = CCXTStore(exchange='bitmex',
                      currency='BTC',
                      config=config,
                      retries=5,
                      debug=False,
                      testnet=True)

    print("I am here")
    print(store.exchange.urls)

    broker = store.getbroker()
    cerebro.setbroker(broker)

    # Get our data
    # Drop newest will prevent us from loading partial data from incomplete candles
    hist_start_date = datetime.utcnow() - timedelta(minutes=50)
    data = store.getdata(dataname='BTC/USD',
                         name="BTCUSD",
                         timeframe=bt.TimeFrame.Minutes,
                         fromdate=hist_start_date,
                         compression=1,
                         ohlcv_limit=50,
                         drop_newest=True)  #, historical=True)

    # Add the feed
    cerebro.adddata(data)

    # Run the strategy
    cerebro.run()
Esempio n. 3
0
def main():
    cerebro = bt.Cerebro(quicknotify=True)

    if ENV == PRODUCTION:  # Live trading with Binance
        broker_config = {
            'apiKey': os.environ.get('okex_key'),
            'secret': os.environ.get('okex__secret'),
            'nonce': lambda: str(int(time.time() * 1000)),
            'enableRateLimit': True,
        }

        store = CCXTStore(exchange='okex',
                          currency='USDT',
                          config=broker_config,
                          retries=5,
                          debug=DEBUG)

        broker_mapping = {
            'order_types': {
                bt.Order.Market: 'market',
                bt.Order.Limit: 'limit',
                bt.Order.Stop: 'stop-loss',
                bt.Order.StopLimit: 'stop limit'
            },
            'mappings': {
                'closed_order': {
                    'key': 'status',
                    'value': 'closed'
                },
                'canceled_order': {
                    'key': 'status',
                    'value': 'canceled'
                }
            }
        }

        okex = store.getbroker(broker_mapping=broker_mapping)
        print(okex.getcash(), okex.getvalue())

        #cerebro.setbroker(okex)

        broker = cerebro.getbroker()
        broker.setcommission(commission=0.001, name=COIN_TARGET)
        broker.setcash(100000.0)
        cerebro.addsizer(FullMoney)

        initial_value = cerebro.broker.getvalue()
        print('Starting Portfolio Value: %.2f' % initial_value)

        hist_start_date = dt.datetime.utcnow() - dt.timedelta(minutes=30000)
        data = store.getdata(
            dataname='%s/%s' % (COIN_TARGET, COIN_REFER),
            name='%s%s' % (COIN_TARGET, COIN_REFER),
            timeframe=bt.TimeFrame.Minutes,
            #fromdate=hist_start_date,
            fromdate=dt.datetime(2018, 1, 1),
            todate=dt.datetime(2018, 12, 31),
            compression=15,
            ohlcv_limit=None)

        # Add the feed
        #cerebro.adddata(data)
        cerebro.resampledata(data,
                             timeframe=bt.TimeFrame.Minutes,
                             compression=30)

    else:  # Backtesting with CSV file
        data = OneTokenDataset(
            name='btc',
            dataname=
            "dataset/candles_okef_btc.usd.t_2018-11-11_2018-12-12_5m.csv",
            timeframe=bt.TimeFrame.Minutes,
            #fromdate=dt.datetime(2018, 11, 11,11,11),
            #todate=dt.datetime(2018, 11, 10,11,11),
            compression=5,
            nullvalue=0.0,
            dtformat=1,
        )

        cerebro.adddata(data)
        #cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=5)

        broker = cerebro.getbroker()
        broker.setcommission(commission=0.001, name=COIN_TARGET)
        broker.setcash(10000.0)
        cerebro.addsizer(FullMoney)

    # Analyzers to evaluate trades and strategies
    # SQN = Average( profit / risk ) / StdDev( profit / risk ) x SquareRoot( number of trades )
    cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
    cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")

    # Include Strategy
    cerebro.addstrategy(BasicRandom)

    # Print analyzers - results
    initial_value = cerebro.broker.getvalue()
    print('Starting Portfolio Value: %.2f' % initial_value)

    #exit()
    result = cerebro.run()
    final_value = cerebro.broker.getvalue()
    print('Final Portfolio Value: %.2f' % final_value)
    print('Profit %.3f%%' %
          ((final_value - initial_value) / initial_value * 100))

    #exit()
    print_trade_analysis(result[0].analyzers.ta.get_analysis())
    print_sqn(result[0].analyzers.sqn.get_analysis())

    if True:  #DEBUG:
        cerebro.plot()
cerebro.broker.setcash(10.0)

# Add the strategy
cerebro.addstrategy(TestStrategy)

# Create our store
config = {
    'apiKey': params["binance"]["apikey"],
    'secret': params["binance"]["secret"],
    'enableRateLimit': True,
    'nonce': lambda: str(int(time.time() * 1000)),
}

store = CCXTStore(exchange='binance',
                  currency='BNB',
                  config=config,
                  retries=5,
                  debug=True)

# Get the broker and pass any kwargs if needed.
# ----------------------------------------------
# Broker mappings have been added since some exchanges expect different values
# to the defaults. Case in point, Kraken vs Bitmex. NOTE: Broker mappings are not
# required if the broker uses the same values as the defaults in CCXTBroker.
broker_mapping = {
    'order_types': {
        bt.Order.Market: 'market',
        bt.Order.Limit: 'limit',
        bt.Order.Stop: 'stop_loss',  #stop-loss for kraken, stop for bitmex
        bt.Order.StopLimit: 'STOP_LOSS_LIMIT'
    },
Esempio n. 5
0
# Add the data feeds
cerebro.adddata(data)
#cerebro.adddata(data2)

# Set Config
config = {
    'apiKey': apikey,
    'secret': secret,
    'enableRateLimit': True,
    'rateLimit': 3000
}

# Add our strategy
cerebro.addstrategy(TVTest)

print('Getting Store')
# Create data feeds
store = CCXTStore(exchange='bitfinex',
                  currency='USD',
                  config=config,
                  retries=5,
                  debug=False)

print('Getting Broker')
broker = store.getbroker()
cerebro.setbroker(broker)

# Run the strategy
cerebro.run()
Esempio n. 6
0
def main():
    cerebro = bt.Cerebro(quicknotify=True)

    if ENV == PRODUCTION:  # Live trading with Binance
        broker_config = {
            'apiKey': BINANCE.get("key"),
            'secret': BINANCE.get("secret"),
            'nonce': lambda: str(int(time.time() * 1000)),
            'enableRateLimit': True,
        }

        store = CCXTStore(exchange='binance',
                          currency=COIN_REFER,
                          config=broker_config,
                          retries=5,
                          debug=DEBUG)

        broker_mapping = {
            'order_types': {
                bt.Order.Market: 'market',
                bt.Order.Limit: 'limit',
                bt.Order.Stop: 'stop-loss',
                bt.Order.StopLimit: 'stop limit'
            },
            'mappings': {
                'closed_order': {
                    'key': 'status',
                    'value': 'closed'
                },
                'canceled_order': {
                    'key': 'status',
                    'value': 'canceled'
                }
            }
        }

        broker = store.getbroker(broker_mapping=broker_mapping)
        cerebro.setbroker(broker)

        hist_start_date = dt.datetime.utcnow() - dt.timedelta(minutes=30000)
        data = store.getdata(dataname='%s/%s' % (COIN_TARGET, COIN_REFER),
                             name='%s%s' % (COIN_TARGET, COIN_REFER),
                             timeframe=bt.TimeFrame.Minutes,
                             fromdate=hist_start_date,
                             compression=30,
                             ohlcv_limit=99999)

        # Add the feed
        cerebro.adddata(data)

    else:  # Backtesting with CSV file
        data = CustomDataset(name=COIN_TARGET,
                             dataname="dataset/binance_nov_18_mar_19_btc.csv",
                             timeframe=bt.TimeFrame.Minutes,
                             fromdate=dt.datetime(2018, 9, 20),
                             todate=dt.datetime(2019, 3, 13),
                             nullvalue=0.0)

        cerebro.resampledata(data,
                             timeframe=bt.TimeFrame.Minutes,
                             compression=30)

        broker = cerebro.getbroker()
        broker.setcommission(commission=0.001,
                             name=COIN_TARGET)  # Simulating exchange fee
        broker.setcash(100000.0)
        cerebro.addsizer(FullMoney)

    # Analyzers to evaluate trades and strategies
    # SQN = Average( profit / risk ) / StdDev( profit / risk ) x SquareRoot( number of trades )
    cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
    cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")

    # Include Strategy
    cerebro.addstrategy(BasicRSI)

    # Starting backtrader bot
    initial_value = cerebro.broker.getvalue()
    print('Starting Portfolio Value: %.2f' % initial_value)
    result = cerebro.run()

    # Print analyzers - results
    final_value = cerebro.broker.getvalue()
    print('Final Portfolio Value: %.2f' % final_value)
    print('Profit %.3f%%' %
          ((final_value - initial_value) / initial_value * 100))
    print_trade_analysis(result[0].analyzers.ta.get_analysis())
    print_sqn(result[0].analyzers.sqn.get_analysis())

    if DEBUG:
        cerebro.plot()
secret = 'INSERT YOUR SECRET'

cerebro = bt.Cerebro(quicknotify=True)

# Add the strategy
cerebro.addstrategy(TestStrategy)

# Create our store
config = {'apiKey': apikey, 'secret': secret, 'enableRateLimit': True}

# IMPORTANT NOTE - Kraken (and some other exchanges) will not return any values
# for get cash or value if You have never held any LTC coins in your account.
# So switch LTC to a coin you have funded previously if you get errors
store = CCXTStore(exchange='kraken',
                  currency='LTC',
                  config=config,
                  retries=5,
                  debug=False)

# Get the broker and pass any kwargs if needed.
# ----------------------------------------------
# Broker mappings have been added since some exchanges expect different values
# to the defaults. Case in point, Kraken vs Bitmex. NOTE: Broker mappings are not
# required if the broker uses the same values as the defaults in CCXTBroker.
broker_mapping = {
    'order_types': {
        bt.Order.Market: 'market',
        bt.Order.Limit: 'limit',
        bt.Order.Stop: 'stop-loss',  #stop-loss for kraken, stop for bitmex
        bt.Order.StopLimit: 'stop limit'
    },
Esempio n. 8
0
cerebro.broker.setcash(10.0)

# Add the strategy
cerebro.addstrategy(TestStrategy)

# Create our store
config = {
    'apiKey': params["binance"]["apikey"],
    'secret': params["binance"]["secret"],
    'enableRateLimit': True,
    'nonce': lambda: str(int(time.time() * 1000)),
}

store = CCXTStore(exchange='binance',
                  currency='BNB',
                  config=config,
                  retries=5,
                  debug=False)

# Get our data
# Drop newest will prevent us from loading partial data from incomplete candles
hist_start_date = datetime.utcnow() - timedelta(days=20)
to_date = datetime.utcnow() + timedelta(minutes=3)
data = store.getdata(dataname='BNB/USDT',
                     name="BNBUSDT",
                     timeframe=bt.TimeFrame.Minutes,
                     fromdate=hist_start_date,
                     todate=to_date,
                     compression=5,
                     ohlcv_limit=1000,
                     debug=False)  # , historical=True)
Esempio n. 9
0
# Set Config
config = {'apiKey': apikey,
          'secret': secret,
          'enableRateLimit': True
        }



# Add our strategy
cerebro.addstrategy(Kraken)


print('Getting Store')
# Create data feeds
store = CCXTStore(exchange='kraken', currency='USD', config=config, retries=5, debug=False)

print('Getting Broker')
broker_mapping = {
        'order_types': {
            bt.Order.Market: 'market',
            bt.Order.Limit: 'limit',
            bt.Order.Stop: 'stop-loss', #stop-loss for kraken, stop for bitmex
            bt.Order.StopLimit: 'stop limit'
        },
        'mappings':{
            'closed_order':{
                'key': 'status',
                'value':'closed'
                },
            'canceled_order':{
Esempio n. 10
0
def main(path, name, persistence_type=PersistenceType.GOOGLE_FIRESTORE):
    """
    Please provide the parameter file name with a path relative to the project root.
    """
    cerebro = CTCerebro(preload=False)

    try:
        trade_setup_persistence = PersistenceFactory.get_persistance(
            persistence_type, path, name, root_path=ROOT_PATH)
        trade_setup = trade_setup_persistence.get_setup()
    except:
        print('Please provide the parameter file name.')
        sys.exit(1)  # abort

    cs_persistence = get_cs_persistence(trade_setup)

    cerebro.broker.setcash(trade_setup['initial_cash'])

    abs_param_file = os.path.join(ROOT_PATH,
                                  'trade_setups/backtestBNBPsarSL.json')
    cerebro.addstrategy(
        TrailingStopLossV3,
        buy_pos_size=trade_setup['buy_pos_size'],
        slippage=trade_setup['slippage'],
        buy_limit=trade_setup['buy_limit'],
        fallback_stop_loss=trade_setup['fallback_stop_loss'],
        data_status4trading=trade_setup.get('data_status4trading'),
        state_iteration_index=get_candle_state_index(cs_persistence),
        cs_persistence=cs_persistence,
        trade_setup_persistence=trade_setup_persistence,
        # state_bucket_folder=...
        abs_param_file=abs_param_file)

    with open(CONFIG_PATH, 'r') as f:
        runtime_config = json.load(f)

    store_config = {
        'apiKey': runtime_config["keys"]["binance"]["apikey"],
        'secret': runtime_config["keys"]["binance"]["secret"],
        'enableRateLimit': True,
        'nonce': lambda: str(int(time.time() * 1000)),
    }

    tframes = dict(ticks=bt.TimeFrame.Ticks,
                   microseconds=bt.TimeFrame.MicroSeconds,
                   seconds=bt.TimeFrame.Seconds,
                   minutes=bt.TimeFrame.Minutes,
                   daily=bt.TimeFrame.Days,
                   weekly=bt.TimeFrame.Weeks,
                   monthly=bt.TimeFrame.Months)

    store = CCXTStore(exchange=trade_setup['exchange'],
                      currency=trade_setup['currency'],
                      config=store_config,
                      retries=5,
                      debug=True)

    broker = store.getbroker()
    cerebro.setbroker(broker)

    if trade_setup.get('fromdate'):
        fromdate = dt.datetime(trade_setup['fromdate']['year'],
                               trade_setup['fromdate']['month'],
                               trade_setup['fromdate']['day'],
                               trade_setup['fromdate']['hour'],
                               trade_setup['fromdate']['minute'])
    else:
        fromdate = None

    # Get our data
    # Drop newest will prevent us from loading partial data from incomplete candles
    data = store.getdata(
        exchange=trade_setup['exchange'],
        dataname=trade_setup['symbol'],
        timeframe=tframes[trade_setup['timeframe']],
        fromdate=fromdate,
        compression=trade_setup['compression'],
        ohlcv_limit=2,  # required to make calls to binance exchange work
        currency=trade_setup['currency'],
        config=store_config,
        retries=5,
        drop_newest=False,
        # historical=True,
        backfill_start=False,
        backfill=False
        # debug=True,
    )
    # Add the feed
    cerebro.adddata(data)

    # Print out the starting conditions
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    # Run the strategy
    cerebro.run()

    # Print out the final result
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())