コード例 #1
0
def test_setup_hyperopt_configuration_without_arguments(
        mocker, default_conf, caplog) -> None:
    mocker.patch('freqtrade.configuration.open',
                 mocker.mock_open(read_data=json.dumps(default_conf)))

    args = ['--config', 'config.json', 'hyperopt']

    config = setup_configuration(get_args(args), RunMode.HYPEROPT)
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert log_has('Using data folder: {} ...'.format(config['datadir']),
                   caplog.record_tuples)
    assert 'ticker_interval' in config
    assert not log_has_re('Parameter -i/--ticker-interval detected .*',
                          caplog.record_tuples)

    assert 'live' not in config
    assert not log_has('Parameter -l/--live detected ...',
                       caplog.record_tuples)

    assert 'position_stacking' not in config
    assert not log_has('Parameter --enable-position-stacking detected ...',
                       caplog.record_tuples)

    assert 'refresh_pairs' not in config
    assert not log_has('Parameter -r/--refresh-pairs-cached detected ...',
                       caplog.record_tuples)

    assert 'timerange' not in config
    assert 'runmode' in config
    assert config['runmode'] == RunMode.HYPEROPT
コード例 #2
0
def test_setup_edge_configuration_with_arguments(mocker, edge_conf,
                                                 caplog) -> None:
    mocker.patch('freqtrade.configuration.open',
                 mocker.mock_open(read_data=json.dumps(edge_conf)))
    mocker.patch('freqtrade.configuration.Configuration._create_datadir',
                 lambda s, c, x: x)

    args = [
        '--config', 'config.json', '--strategy', 'DefaultStrategy',
        '--datadir', '/foo/bar', 'edge', '--ticker-interval', '1m',
        '--refresh-pairs-cached', '--timerange', ':100',
        '--stoplosses=-0.01,-0.10,-0.001'
    ]

    config = setup_configuration(get_args(args))
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert log_has('Using data folder: {} ...'.format(config['datadir']),
                   caplog.record_tuples)
    assert 'ticker_interval' in config
    assert log_has('Parameter -i/--ticker-interval detected ...',
                   caplog.record_tuples)
    assert log_has('Using ticker_interval: 1m ...', caplog.record_tuples)

    assert 'refresh_pairs' in config
    assert log_has('Parameter -r/--refresh-pairs-cached detected ...',
                   caplog.record_tuples)
    assert 'timerange' in config
    assert log_has(
        'Parameter --timerange detected: {} ...'.format(config['timerange']),
        caplog.record_tuples)
コード例 #3
0
def test_show_info(default_conf, mocker, caplog) -> None:
    """
    Test Configuration.show_info()
    """
    mocker.patch('freqtrade.configuration.open',
                 mocker.mock_open(read_data=json.dumps(default_conf)))

    args = [
        '--dynamic-whitelist', '10', '--strategy', 'TestStrategy',
        '--dry-run-db'
    ]
    args = Arguments(args, '').get_parsed_arg()

    configuration = Configuration(args)
    configuration.get_config()

    assert log_has(
        'Parameter --dynamic-whitelist detected. '
        'Using dynamically generated whitelist. '
        '(not applicable with Backtesting and Hyperopt)', caplog.record_tuples)

    assert log_has('Parameter --dry-run-db detected ...', caplog.record_tuples)

    assert log_has('Dry_run will use the DB file: "tradesv3.dry_run.sqlite"',
                   caplog.record_tuples)

    # Test the Dry run condition
    configuration.config.update({'dry_run': False})
    configuration._load_common_config(configuration.config)
    assert log_has('Dry run is disabled. (--dry_run_db ignored)',
                   caplog.record_tuples)
コード例 #4
0
def test_download_data(mocker, markets, caplog):
    dl_mock = mocker.patch('freqtrade.utils.download_pair_history',
                           MagicMock())
    patch_exchange(mocker)
    mocker.patch('freqtrade.exchange.Exchange.markets',
                 PropertyMock(return_value=markets))
    mocker.patch.object(Path, "exists", MagicMock(return_value=True))
    mocker.patch.object(Path, "unlink", MagicMock())

    args = [
        "download-data",
        "--exchange",
        "binance",
        "--pairs",
        "ETH/BTC",
        "XRP/BTC",
        "--erase",
    ]
    start_download_data(get_args(args))

    assert dl_mock.call_count == 4
    assert dl_mock.call_args[1]['timerange'].starttype is None
    assert dl_mock.call_args[1]['timerange'].stoptype is None
    assert log_has("Deleting existing data for pair ETH/BTC, interval 1m.",
                   caplog)
    assert log_has("Downloading pair ETH/BTC, interval 1m.", caplog)
コード例 #5
0
ファイル: test_edge_cli.py プロジェクト: ychaim/freqtrade
def test_setup_edge_configuration_with_arguments(mocker, edge_conf,
                                                 caplog) -> None:
    patched_configuration_load_config_file(mocker, edge_conf)
    mocker.patch('freqtrade.configuration.configuration.create_datadir',
                 lambda c, x: x)

    args = [
        '--config', 'config.json', '--strategy', 'DefaultStrategy',
        '--datadir', '/foo/bar', 'edge', '--ticker-interval', '1m',
        '--refresh-pairs-cached', '--timerange', ':100',
        '--stoplosses=-0.01,-0.10,-0.001'
    ]

    config = setup_configuration(get_args(args), RunMode.EDGE)
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert config['runmode'] == RunMode.EDGE
    assert log_has('Using data directory: {} ...'.format(config['datadir']),
                   caplog)
    assert 'ticker_interval' in config
    assert log_has(
        'Parameter -i/--ticker-interval detected ... Using ticker_interval: 1m ...',
        caplog)

    assert 'refresh_pairs' in config
    assert log_has('Parameter -r/--refresh-pairs-cached detected ...', caplog)
    assert 'timerange' in config
    assert log_has(
        'Parameter --timerange detected: {} ...'.format(config['timerange']),
        caplog)
コード例 #6
0
def test_hyperopt_with_arguments(mocker, default_conf, caplog) -> None:
    patched_configuration_load_config_file(mocker, default_conf)

    arglist = [
        'hyperopt',
        '--epochs',
        '10',
        '--spaces',
        'all',
    ]
    args = Arguments(arglist, '').get_parsed_arg()

    configuration = Configuration(args, RunMode.HYPEROPT)
    config = configuration.get_config()

    assert 'epochs' in config
    assert int(config['epochs']) == 10
    assert log_has(
        'Parameter --epochs detected ... Will run Hyperopt with for 10 epochs ...',
        caplog)

    assert 'spaces' in config
    assert config['spaces'] == ['all']
    assert log_has('Parameter -s/--spaces detected: [\'all\']', caplog)
    assert "runmode" in config
    assert config['runmode'] == RunMode.HYPEROPT
コード例 #7
0
def test_authorized_only(default_conf, mocker, caplog) -> None:
    patch_coinmarketcap(mocker)
    patch_exchange(mocker, None)

    chat = Chat(0, 0)
    update = Update(randint(1, 100))
    update.message = Message(randint(1, 100), 0, datetime.utcnow(), chat)

    default_conf['telegram']['enabled'] = False
    bot = FreqtradeBot(default_conf)
    patch_get_signal(bot, (True, False))
    dummy = DummyCls(bot)
    dummy.dummy_handler(bot=MagicMock(), update=update)
    assert dummy.state['called'] is True
    assert log_has(
        'Executing handler: dummy_handler for chat_id: 0',
        caplog.record_tuples
    )
    assert not log_has(
        'Rejected unauthorized message from: 0',
        caplog.record_tuples
    )
    assert not log_has(
        'Exception occurred within Telegram module',
        caplog.record_tuples
    )
コード例 #8
0
def test_migrate_mid_state(mocker, default_conf, fee, caplog):
    """
    Test Database migration (starting with new pairformat)
    """
    caplog.set_level(logging.DEBUG)
    amount = 103.223
    create_table_old = """CREATE TABLE IF NOT EXISTS "trades" (
                                id INTEGER NOT NULL,
                                exchange VARCHAR NOT NULL,
                                pair VARCHAR NOT NULL,
                                is_open BOOLEAN NOT NULL,
                                fee_open FLOAT NOT NULL,
                                fee_close FLOAT NOT NULL,
                                open_rate FLOAT,
                                close_rate FLOAT,
                                close_profit FLOAT,
                                stake_amount FLOAT NOT NULL,
                                amount FLOAT,
                                open_date DATETIME NOT NULL,
                                close_date DATETIME,
                                open_order_id VARCHAR,
                                PRIMARY KEY (id),
                                CHECK (is_open IN (0, 1))
                                );"""
    insert_table_old = """INSERT INTO trades (exchange, pair, is_open, fee_open, fee_close,
                          open_rate, stake_amount, amount, open_date)
                          VALUES ('binance', 'ETC/BTC', 1, {fee}, {fee},
                          0.00258580, {stake}, {amount},
                          '2019-11-28 12:44:24.000000')
                          """.format(fee=fee.return_value,
                                     stake=default_conf.get("stake_amount"),
                                     amount=amount)
    engine = create_engine('sqlite://')
    mocker.patch('freqtrade.persistence.create_engine',
                 lambda *args, **kwargs: engine)

    # Create table using the old format
    engine.execute(create_table_old)
    engine.execute(insert_table_old)

    # Run init to test migration
    init(default_conf['db_url'], default_conf['dry_run'])

    assert len(Trade.query.filter(Trade.id == 1).all()) == 1
    trade = Trade.query.filter(Trade.id == 1).first()
    assert trade.fee_open == fee.return_value
    assert trade.fee_close == fee.return_value
    assert trade.open_rate_requested is None
    assert trade.close_rate_requested is None
    assert trade.is_open == 1
    assert trade.amount == amount
    assert trade.stake_amount == default_conf.get("stake_amount")
    assert trade.pair == "ETC/BTC"
    assert trade.exchange == "binance"
    assert trade.max_rate == 0.0
    assert trade.stop_loss == 0.0
    assert trade.initial_stop_loss == 0.0
    assert log_has("trying trades_bak0", caplog)
    assert log_has(
        "Running database migration - backup available as trades_bak0", caplog)
コード例 #9
0
def test_setup_configuration_without_arguments(mocker, default_conf,
                                               caplog) -> None:
    patched_configuration_load_config_file(mocker, default_conf)

    args = [
        '--config', 'config.json', '--strategy', 'DefaultStrategy',
        'backtesting'
    ]

    config = setup_configuration(get_args(args), RunMode.BACKTEST)
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert log_has('Using data directory: {} ...'.format(config['datadir']),
                   caplog)
    assert 'ticker_interval' in config
    assert not log_has_re('Parameter -i/--ticker-interval detected .*', caplog)

    assert 'position_stacking' not in config
    assert not log_has('Parameter --enable-position-stacking detected ...',
                       caplog)

    assert 'refresh_pairs' not in config
    assert not log_has('Parameter -r/--refresh-pairs-cached detected ...',
                       caplog)

    assert 'timerange' not in config
    assert 'export' not in config
    assert 'runmode' in config
    assert config['runmode'] == RunMode.BACKTEST
コード例 #10
0
def test_show_info(default_conf, mocker, caplog) -> None:
    """
    Test Configuration.show_info()
    """
    mocker.patch('freqtrade.configuration.open',
                 mocker.mock_open(read_data=json.dumps(default_conf)))

    arglist = [
        '--dynamic-whitelist',
        '10',
        '--strategy',
        'TestStrategy',
        '--db-url',
        'sqlite:///tmp/testdb',
    ]
    args = Arguments(arglist, '').get_parsed_arg()

    configuration = Configuration(args)
    configuration.get_config()

    assert log_has(
        'Parameter --dynamic-whitelist detected. '
        'Using dynamically generated whitelist. '
        '(not applicable with Backtesting and Hyperopt)', caplog.record_tuples)

    assert log_has('Using DB: "sqlite:///tmp/testdb"', caplog.record_tuples)
    assert log_has('Dry run is enabled', caplog.record_tuples)
コード例 #11
0
def test_setup_configuration_without_arguments(mocker, default_conf,
                                               caplog) -> None:
    mocker.patch('freqtrade.configuration.open',
                 mocker.mock_open(read_data=json.dumps(default_conf)))

    args = ['--config', 'config.json', '--strategy', 'DefaultStrategy', 'edge']

    config = setup_configuration(get_args(args))
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert log_has('Using data folder: {} ...'.format(config['datadir']),
                   caplog.record_tuples)
    assert 'ticker_interval' in config
    assert not log_has('Parameter -i/--ticker-interval detected ...',
                       caplog.record_tuples)

    assert 'refresh_pairs' not in config
    assert not log_has('Parameter -r/--refresh-pairs-cached detected ...',
                       caplog.record_tuples)

    assert 'timerange' not in config
    assert 'stoploss_range' not in config
コード例 #12
0
def test_update_market_order(market_buy_order, market_sell_order, fee, caplog):
    trade = Trade(
        id=1,
        pair='ETH/BTC',
        stake_amount=0.001,
        fee_open=fee.return_value,
        fee_close=fee.return_value,
        exchange='bittrex',
    )

    trade.open_order_id = 'something'
    trade.update(market_buy_order)
    assert trade.open_order_id is None
    assert trade.open_rate == 0.00004099
    assert trade.close_profit is None
    assert trade.close_date is None
    assert log_has(
        "MARKET_BUY has been fulfilled for Trade(id=1, "
        "pair=ETH/BTC, amount=91.99181073, open_rate=0.00004099, open_since=closed).",
        caplog)

    caplog.clear()
    trade.open_order_id = 'something'
    trade.update(market_sell_order)
    assert trade.open_order_id is None
    assert trade.close_rate == 0.00004173
    assert trade.close_profit == 0.01297561
    assert trade.close_date is not None
    assert log_has(
        "MARKET_SELL has been fulfilled for Trade(id=1, "
        "pair=ETH/BTC, amount=91.99181073, open_rate=0.00004099, open_since=closed).",
        caplog)
コード例 #13
0
def test_main_keyboard_interrupt(mocker, default_conf, caplog) -> None:
    """
    Test main() function
    In this test we are skipping the while True loop by throwing an exception.
    """
    patch_exchange(mocker)
    mocker.patch.multiple(
        'freqtrade.freqtradebot.FreqtradeBot',
        _init_modules=MagicMock(),
        worker=MagicMock(side_effect=KeyboardInterrupt),
        cleanup=MagicMock(),
    )
    mocker.patch('freqtrade.configuration.Configuration._load_config_file',
                 lambda *args, **kwargs: default_conf)
    mocker.patch('freqtrade.freqtradebot.CryptoToFiatConverter', MagicMock())
    mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock())

    args = ['-c', 'config.json.example']

    # Test Main + the KeyboardInterrupt exception
    with pytest.raises(SystemExit):
        main(args)
    assert log_has('Using config: config.json.example ...',
                   caplog.record_tuples)
    assert log_has('SIGINT received, aborting ...', caplog.record_tuples)
コード例 #14
0
def test_load_data_with_new_pair_1min(ticker_history, mocker, caplog,
                                      default_conf) -> None:
    """
    Test load_data() with 1 min ticker
    """
    mocker.patch('freqtrade.exchange.Exchange.get_history',
                 return_value=ticker_history)
    exchange = get_patched_exchange(mocker, default_conf)
    file = os.path.join(os.path.dirname(__file__), '..', 'testdata',
                        'MEME_BTC-1m.json')

    _backup_file(file)
    # do not download a new pair if refresh_pairs isn't set
    optimize.load_data(None,
                       ticker_interval='1m',
                       refresh_pairs=False,
                       pairs=['MEME/BTC'])
    assert os.path.isfile(file) is False
    assert log_has(
        'No data for pair: "MEME/BTC", Interval: 1m. '
        'Use --refresh-pairs-cached to download the data',
        caplog.record_tuples)

    # download a new pair if refresh_pairs is set
    optimize.load_data(None,
                       ticker_interval='1m',
                       refresh_pairs=True,
                       exchange=exchange,
                       pairs=['MEME/BTC'])
    assert os.path.isfile(file) is True
    assert log_has('Download the pair: "MEME/BTC", Interval: 1m',
                   caplog.record_tuples)
    _clean_test_file(file)
コード例 #15
0
def test_load_data_with_new_pair_1min(ticker_history_list, mocker, caplog, default_conf) -> None:
    """
    Test load_pair_history() with 1 min ticker
    """
    mocker.patch('freqtrade.exchange.Exchange.get_history', return_value=ticker_history_list)
    exchange = get_patched_exchange(mocker, default_conf)
    file = os.path.join(os.path.dirname(__file__), '..', 'testdata', 'MEME_BTC-1m.json')

    _backup_file(file)
    # do not download a new pair if refresh_pairs isn't set
    history.load_pair_history(datadir=None,
                              ticker_interval='1m',
                              refresh_pairs=False,
                              pair='MEME/BTC')
    assert os.path.isfile(file) is False
    assert log_has('No data for pair: "MEME/BTC", Interval: 1m. '
                   'Use --refresh-pairs-cached to download the data',
                   caplog.record_tuples)

    # download a new pair if refresh_pairs is set
    history.load_pair_history(datadir=None,
                              ticker_interval='1m',
                              refresh_pairs=True,
                              exchange=exchange,
                              pair='MEME/BTC')
    assert os.path.isfile(file) is True
    assert log_has('Download the pair: "MEME/BTC", Interval: 1m', caplog.record_tuples)
    with pytest.raises(OperationalException, match=r'Exchange needs to be initialized when.*'):
        history.load_pair_history(datadir=None,
                                  ticker_interval='1m',
                                  refresh_pairs=True,
                                  exchange=None,
                                  pair='MEME/BTC')
    _clean_test_file(file)
コード例 #16
0
def test_load_partial_missing(caplog) -> None:
    # Make sure we start fresh - test missing data at start
    start = arrow.get('2018-01-01T00:00:00')
    end = arrow.get('2018-01-11T00:00:00')
    tickerdata = history.load_data(None, '5m', ['UNITTEST/BTC'],
                                   refresh_pairs=False,
                                   timerange=TimeRange('date', 'date',
                                                       start.timestamp, end.timestamp))
    # timedifference in 5 minutes
    td = ((end - start).total_seconds() // 60 // 5) + 1
    assert td != len(tickerdata['UNITTEST/BTC'])
    start_real = tickerdata['UNITTEST/BTC'].iloc[0, 0]
    assert log_has(f'Missing data at start for pair '
                   f'UNITTEST/BTC, data starts at {start_real.strftime("%Y-%m-%d %H:%M:%S")}',
                   caplog.record_tuples)
    # Make sure we start fresh - test missing data at end
    caplog.clear()
    start = arrow.get('2018-01-10T00:00:00')
    end = arrow.get('2018-02-20T00:00:00')
    tickerdata = history.load_data(datadir=None, ticker_interval='5m',
                                   pairs=['UNITTEST/BTC'], refresh_pairs=False,
                                   timerange=TimeRange('date', 'date',
                                                       start.timestamp, end.timestamp))
    # timedifference in 5 minutes
    td = ((end - start).total_seconds() // 60 // 5) + 1
    assert td != len(tickerdata['UNITTEST/BTC'])
    # Shift endtime with +5 - as last candle is dropped (partial candle)
    end_real = arrow.get(tickerdata['UNITTEST/BTC'].iloc[-1, 0]).shift(minutes=5)
    assert log_has(f'Missing data at end for pair '
                   f'UNITTEST/BTC, data ends at {end_real.strftime("%Y-%m-%d %H:%M:%S")}',
                   caplog.record_tuples)
コード例 #17
0
def test_authorized_only_exception(default_conf, mocker, caplog) -> None:
    """
    Test authorized_only() method when an exception is thrown
    """
    patch_get_signal(mocker, (True, False))
    patch_coinmarketcap(mocker)
    mocker.patch('freqtrade.freqtradebot.exchange.init', MagicMock())

    update = Update(randint(1, 100))
    update.message = Message(randint(1, 100), 0, datetime.utcnow(), Chat(0, 0))

    conf = deepcopy(default_conf)
    conf['telegram']['enabled'] = False
    dummy = DummyCls(FreqtradeBot(conf, create_engine('sqlite://')))
    dummy.dummy_exception(bot=MagicMock(), update=update)
    assert dummy.state['called'] is False
    assert not log_has(
        'Executing handler: dummy_handler for chat_id: 0',
        caplog.record_tuples
    )
    assert not log_has(
        'Rejected unauthorized message from: 0',
        caplog.record_tuples
    )
    assert log_has(
        'Exception occurred within Telegram module',
        caplog.record_tuples
    )
コード例 #18
0
def test__args_to_config(caplog):

    arg_list = ['--strategy-path', 'TestTest']
    args = Arguments(arg_list, '').get_parsed_arg()
    configuration = Configuration(args)
    config = {}
    with warnings.catch_warnings(record=True) as w:
        # No warnings ...
        configuration._args_to_config(config,
                                      argname="strategy_path",
                                      logstring="DeadBeef")
        assert len(w) == 0
        assert log_has("DeadBeef", caplog)
        assert config['strategy_path'] == "TestTest"

    configuration = Configuration(args)
    config = {}
    with warnings.catch_warnings(record=True) as w:
        # Deprecation warnings!
        configuration._args_to_config(config,
                                      argname="strategy_path",
                                      logstring="DeadBeef",
                                      deprecated_msg="Going away soon!")
        assert len(w) == 1
        assert issubclass(w[-1].category, DeprecationWarning)
        assert "DEPRECATED: Going away soon!" in str(w[-1].message)
        assert log_has("DeadBeef", caplog)
        assert config['strategy_path'] == "TestTest"
コード例 #19
0
def test_analyze_ticker_default(ticker_history, mocker, caplog) -> None:
    caplog.set_level(logging.DEBUG)
    ind_mock = MagicMock(side_effect=lambda x, meta: x)
    buy_mock = MagicMock(side_effect=lambda x, meta: x)
    sell_mock = MagicMock(side_effect=lambda x, meta: x)
    mocker.patch.multiple(
        'freqtrade.strategy.interface.IStrategy',
        advise_indicators=ind_mock,
        advise_buy=buy_mock,
        advise_sell=sell_mock,
    )
    strategy = DefaultStrategy({})
    strategy.analyze_ticker(ticker_history, {'pair': 'ETH/BTC'})
    assert ind_mock.call_count == 1
    assert buy_mock.call_count == 1
    assert buy_mock.call_count == 1

    assert log_has('TA Analysis Launched', caplog.record_tuples)
    assert not log_has('Skippinig TA Analysis for already analyzed candle',
                       caplog.record_tuples)
    caplog.clear()

    strategy.analyze_ticker(ticker_history, {'pair': 'ETH/BTC'})
    # No analysis happens as process_only_new_candles is true
    assert ind_mock.call_count == 2
    assert buy_mock.call_count == 2
    assert buy_mock.call_count == 2
    assert log_has('TA Analysis Launched', caplog.record_tuples)
    assert not log_has('Skippinig TA Analysis for already analyzed candle',
                       caplog.record_tuples)
コード例 #20
0
def test_hyperopt_with_arguments(mocker, default_conf, caplog) -> None:
    mocker.patch('freqtrade.configuration.open',
                 mocker.mock_open(read_data=json.dumps(default_conf)))
    arglist = [
        'hyperopt',
        '--epochs',
        '10',
        '--spaces',
        'all',
    ]
    args = Arguments(arglist, '').get_parsed_arg()

    configuration = Configuration(args)
    config = configuration.get_config()

    assert 'epochs' in config
    assert int(config['epochs']) == 10
    assert log_has('Parameter --epochs detected ...', caplog.record_tuples)
    assert log_has('Will run Hyperopt with for 10 epochs ...',
                   caplog.record_tuples)

    assert 'spaces' in config
    assert config['spaces'] == ['all']
    assert log_has('Parameter -s/--spaces detected: [\'all\']',
                   caplog.record_tuples)
コード例 #21
0
ファイル: test_plotting.py プロジェクト: ychaim/freqtrade
def test_generate_candlestick_graph_no_signals_no_trades(default_conf, mocker, caplog):
    row_mock = mocker.patch('freqtrade.plot.plotting.add_indicators',
                            MagicMock(side_effect=fig_generating_mock))
    trades_mock = mocker.patch('freqtrade.plot.plotting.plot_trades',
                               MagicMock(side_effect=fig_generating_mock))

    pair = "UNITTEST/BTC"
    timerange = TimeRange(None, 'line', 0, -1000)
    data = history.load_pair_history(pair=pair, ticker_interval='1m',
                                     datadir=None, timerange=timerange)
    data['buy'] = 0
    data['sell'] = 0

    indicators1 = []
    indicators2 = []
    fig = generate_candlestick_graph(pair=pair, data=data, trades=None,
                                     indicators1=indicators1, indicators2=indicators2)
    assert isinstance(fig, go.Figure)
    assert fig.layout.title.text == pair
    figure = fig.layout.figure

    assert len(figure.data) == 2
    # Candlesticks are plotted first
    candles = find_trace_in_fig_data(figure.data, "Price")
    assert isinstance(candles, go.Candlestick)

    volume = find_trace_in_fig_data(figure.data, "Volume")
    assert isinstance(volume, go.Bar)

    assert row_mock.call_count == 2
    assert trades_mock.call_count == 1

    assert log_has("No buy-signals found.", caplog)
    assert log_has("No sell-signals found.", caplog)
コード例 #22
0
def test_setup_configuration_with_arguments(mocker, default_conf,
                                            caplog) -> None:
    mocker.patch('freqtrade.configuration.open',
                 mocker.mock_open(read_data=json.dumps(default_conf)))
    mocker.patch('freqtrade.configuration.Configuration._create_datadir',
                 lambda s, c, x: x)

    arglist = [
        '--config', 'config.json', '--strategy', 'DefaultStrategy',
        '--datadir', '/foo/bar', 'backtesting', '--ticker-interval', '1m',
        '--live', '--enable-position-stacking',
        '--disable-max-market-positions', '--refresh-pairs-cached',
        '--timerange', ':100', '--export', '/bar/foo'
    ]

    args = Arguments(arglist, '').get_parsed_arg()

    configuration = Configuration(args)
    config = configuration.get_config()
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert log_has('Using data folder: {} ...'.format(config['datadir']),
                   caplog.record_tuples)
    assert 'ticker_interval' in config
    assert log_has('Parameter -i/--ticker-interval detected ...',
                   caplog.record_tuples)
    assert log_has('Using ticker_interval: 1m ...', caplog.record_tuples)

    assert 'live' in config
    assert log_has('Parameter -l/--live detected ...', caplog.record_tuples)

    assert 'position_stacking' in config
    assert log_has('Parameter --enable-position-stacking detected ...',
                   caplog.record_tuples)

    assert 'use_max_market_positions' in config
    assert log_has('Parameter --disable-max-market-positions detected ...',
                   caplog.record_tuples)
    assert log_has('max_open_trades set to unlimited ...',
                   caplog.record_tuples)

    assert 'refresh_pairs' in config
    assert log_has('Parameter -r/--refresh-pairs-cached detected ...',
                   caplog.record_tuples)
    assert 'timerange' in config
    assert log_has(
        'Parameter --timerange detected: {} ...'.format(config['timerange']),
        caplog.record_tuples)

    assert 'export' in config
    assert log_has(
        'Parameter --export detected: {} ...'.format(config['export']),
        caplog.record_tuples)
コード例 #23
0
def test_get_signal_empty(default_conf, mocker, caplog):
    assert (False, False) == _STRATEGY.get_signal('foo', default_conf['ticker_interval'],
                                                  DataFrame())
    assert log_has('Empty ticker history for pair foo', caplog.record_tuples)
    caplog.clear()

    assert (False, False) == _STRATEGY.get_signal('bar', default_conf['ticker_interval'],
                                                  [])
    assert log_has('Empty ticker history for pair bar', caplog.record_tuples)
コード例 #24
0
def test_setup_hyperopt_configuration_with_arguments(mocker, default_conf,
                                                     caplog) -> None:
    patched_configuration_load_config_file(mocker, default_conf)
    mocker.patch('freqtrade.configuration.configuration.create_datadir',
                 lambda c, x: x)

    args = [
        '--config', 'config.json', '--datadir', '/foo/bar', 'hyperopt',
        '--ticker-interval', '1m', '--timerange', ':100',
        '--refresh-pairs-cached', '--enable-position-stacking',
        '--disable-max-market-positions', '--epochs', '1000', '--spaces',
        'all', '--print-all'
    ]

    config = setup_configuration(get_args(args), RunMode.HYPEROPT)
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert config['runmode'] == RunMode.HYPEROPT

    assert log_has('Using data directory: {} ...'.format(config['datadir']),
                   caplog)
    assert 'ticker_interval' in config
    assert log_has(
        'Parameter -i/--ticker-interval detected ... Using ticker_interval: 1m ...',
        caplog)

    assert 'position_stacking' in config
    assert log_has('Parameter --enable-position-stacking detected ...', caplog)

    assert 'use_max_market_positions' in config
    assert log_has('Parameter --disable-max-market-positions detected ...',
                   caplog)
    assert log_has('max_open_trades set to unlimited ...', caplog)

    assert 'refresh_pairs' in config
    assert log_has('Parameter -r/--refresh-pairs-cached detected ...', caplog)

    assert 'timerange' in config
    assert log_has(
        'Parameter --timerange detected: {} ...'.format(config['timerange']),
        caplog)

    assert 'epochs' in config
    assert log_has(
        'Parameter --epochs detected ... Will run Hyperopt with for 1000 epochs ...',
        caplog)

    assert 'spaces' in config
    assert log_has(
        'Parameter -s/--spaces detected: {}'.format(config['spaces']), caplog)
    assert 'print_all' in config
    assert log_has('Parameter --print-all detected ...', caplog)
コード例 #25
0
def test_ohlcv_drop_incomplete(caplog):
    ticker_interval = '1d'
    ticks = [
        [
            1559750400000,  # 2019-06-04
            8.794e-05,  # open
            8.948e-05,  # high
            8.794e-05,  # low
            8.88e-05,  # close
            2255,  # volume (in quote currency)
        ],
        [
            1559836800000,  # 2019-06-05
            8.88e-05,
            8.942e-05,
            8.88e-05,
            8.893e-05,
            9911,
        ],
        [
            1559923200000,  # 2019-06-06
            8.891e-05,
            8.893e-05,
            8.875e-05,
            8.877e-05,
            2251
        ],
        [
            1560009600000,  # 2019-06-07
            8.877e-05,
            8.883e-05,
            8.895e-05,
            8.817e-05,
            123551
        ]
    ]
    caplog.set_level(logging.DEBUG)
    data = parse_ticker_dataframe(ticks,
                                  ticker_interval,
                                  pair="UNITTEST/BTC",
                                  fill_missing=False,
                                  drop_incomplete=False)
    assert len(data) == 4
    assert not log_has("Dropping last candle", caplog.record_tuples)

    # Drop last candle
    data = parse_ticker_dataframe(ticks,
                                  ticker_interval,
                                  pair="UNITTEST/BTC",
                                  fill_missing=False,
                                  drop_incomplete=True)
    assert len(data) == 3

    assert log_has("Dropping last candle", caplog.record_tuples)
コード例 #26
0
def test_process_maybe_execute_buy_exception(mocker, default_conf,
                                             caplog) -> None:
    """
    Test exception on process_maybe_execute_buy() method
    """
    freqtrade = get_patched_freqtradebot(mocker, default_conf)

    mocker.patch('freqtrade.freqtradebot.FreqtradeBot.create_trade',
                 MagicMock(side_effect=DependencyException))
    freqtrade.process_maybe_execute_buy()
    log_has('Unable to create trade:', caplog.record_tuples)
コード例 #27
0
def test_setup_configuration_with_arguments(mocker, default_conf,
                                            caplog) -> None:
    """
    Test setup_configuration() function
    """
    mocker.patch('freqtrade.configuration.open',
                 mocker.mock_open(read_data=json.dumps(default_conf)))

    args = [
        '--config', 'config.json', '--strategy', 'DefaultStrategy',
        '--datadir', '/foo/bar', 'backtesting', '--ticker-interval', '1m',
        '--live', '--realistic-simulation', '--refresh-pairs-cached',
        '--timerange', ':100', '--export', '/bar/foo', '--export-filename',
        'foo_bar.json'
    ]

    config = setup_configuration(get_args(args))
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert log_has('Using data folder: {} ...'.format(config['datadir']),
                   caplog.record_tuples)
    assert 'ticker_interval' in config
    assert log_has('Parameter -i/--ticker-interval detected ...',
                   caplog.record_tuples)
    assert log_has('Using ticker_interval: 1m ...', caplog.record_tuples)

    assert 'live' in config
    assert log_has('Parameter -l/--live detected ...', caplog.record_tuples)

    assert 'realistic_simulation' in config
    assert log_has('Parameter --realistic-simulation detected ...',
                   caplog.record_tuples)
    assert log_has('Using max_open_trades: 1 ...', caplog.record_tuples)

    assert 'refresh_pairs' in config
    assert log_has('Parameter -r/--refresh-pairs-cached detected ...',
                   caplog.record_tuples)
    assert 'timerange' in config
    assert log_has(
        'Parameter --timerange detected: {} ...'.format(config['timerange']),
        caplog.record_tuples)

    assert 'export' in config
    assert log_has(
        'Parameter --export detected: {} ...'.format(config['export']),
        caplog.record_tuples)
    assert 'exportfilename' in config
    assert log_has(
        'Storing backtest results to {} ...'.format(config['exportfilename']),
        caplog.record_tuples)
コード例 #28
0
def test_setup_configuration_with_stratlist(mocker, default_conf, caplog) -> None:
    """
    Test setup_configuration() function
    """
    mocker.patch('freqtrade.configuration.open', mocker.mock_open(
        read_data=json.dumps(default_conf)
    ))

    arglist = [
        '--config', 'config.json',
        'backtesting',
        '--ticker-interval', '1m',
        '--export', '/bar/foo',
        '--strategy-list',
        'DefaultStrategy',
        'TestStrategy'
    ]

    args = Arguments(arglist, '').get_parsed_arg()

    configuration = Configuration(args)
    config = configuration.get_config()
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert log_has(
        'Using data folder: {} ...'.format(config['datadir']),
        caplog.record_tuples
    )
    assert 'ticker_interval' in config
    assert log_has('Parameter -i/--ticker-interval detected ...', caplog.record_tuples)
    assert log_has(
        'Using ticker_interval: 1m ...',
        caplog.record_tuples
    )

    assert 'strategy_list' in config
    assert log_has('Using strategy list of 2 Strategies', caplog.record_tuples)

    assert 'position_stacking' not in config

    assert 'use_max_market_positions' not in config

    assert 'timerange' not in config

    assert 'export' in config
    assert log_has(
        'Parameter --export detected: {} ...'.format(config['export']),
        caplog.record_tuples
    )
コード例 #29
0
def test_show_info(default_conf, mocker, caplog) -> None:
    patched_configuration_load_config_file(mocker, default_conf)

    arglist = [
        '--strategy', 'TestStrategy',
        '--db-url', 'sqlite:///tmp/testdb',
    ]
    args = Arguments(arglist, '').get_parsed_arg()

    configuration = Configuration(args)
    configuration.get_config()

    assert log_has('Using DB: "sqlite:///tmp/testdb"', caplog.record_tuples)
    assert log_has('Dry run is enabled', caplog.record_tuples)
コード例 #30
0
def test_setup_bt_configuration_with_arguments(mocker, default_conf,
                                               caplog) -> None:
    patched_configuration_load_config_file(mocker, default_conf)
    mocker.patch('freqtrade.configuration.configuration.create_datadir',
                 lambda c, x: x)

    args = [
        '--config', 'config.json', '--strategy', 'DefaultStrategy',
        '--datadir', '/foo/bar', 'backtesting', '--ticker-interval', '1m',
        '--enable-position-stacking', '--disable-max-market-positions',
        '--refresh-pairs-cached', '--timerange', ':100', '--export',
        '/bar/foo', '--export-filename', 'foo_bar.json'
    ]

    config = setup_configuration(get_args(args), RunMode.BACKTEST)
    assert 'max_open_trades' in config
    assert 'stake_currency' in config
    assert 'stake_amount' in config
    assert 'exchange' in config
    assert 'pair_whitelist' in config['exchange']
    assert 'datadir' in config
    assert config['runmode'] == RunMode.BACKTEST

    assert log_has('Using data directory: {} ...'.format(config['datadir']),
                   caplog)
    assert 'ticker_interval' in config
    assert log_has(
        'Parameter -i/--ticker-interval detected ... Using ticker_interval: 1m ...',
        caplog)

    assert 'position_stacking' in config
    assert log_has('Parameter --enable-position-stacking detected ...', caplog)

    assert 'use_max_market_positions' in config
    assert log_has('Parameter --disable-max-market-positions detected ...',
                   caplog)
    assert log_has('max_open_trades set to unlimited ...', caplog)

    assert 'refresh_pairs' in config
    assert log_has('Parameter -r/--refresh-pairs-cached detected ...', caplog)

    assert 'timerange' in config
    assert log_has(
        'Parameter --timerange detected: {} ...'.format(config['timerange']),
        caplog)

    assert 'export' in config
    assert log_has(
        'Parameter --export detected: {} ...'.format(config['export']), caplog)
    assert 'exportfilename' in config
    assert log_has(
        'Storing backtest results to {} ...'.format(config['exportfilename']),
        caplog)