gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, exchange_name: str, config: dict) -> None:
    """
    Load the custom class from config parameter
    :param config: configuration dictionary
    """
    exchange_name = exchange_name.title()
    try:
        self.exchange = self._load_exchange(exchange_name, kwargs={"config": config})
    except ImportError:
        logger.info(
            f"No {exchange_name} specific subclass found. Using the generic class instead."
        )
        self.exchange = Exchange(config)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/opt/Projects/freqtrade/freqtrade/main.py", line 51, in main
worker = Worker(args)
File "/opt/Projects/freqtrade/freqtrade/worker.py", line 35, in __init__
self._init(False)
File "/opt/Projects/freqtrade/freqtrade/worker.py", line 51, in _init
self.freqtrade = FreqtradeBot(self._config)
File "/opt/Projects/freqtrade/freqtrade/freqtradebot.py", line 56, in __init__
self.exchange = ExchangeResolver(self.config['exchange']['name'], self.config).exchange
File "/opt/Projects/freqtrade/freqtrade/resolvers/exchange_resolver.py", line 31, in __init__
self.exchange = Exchange(config)
File "/opt/Projects/freqtrade/freqtrade/exchange/exchange.py", line 140, in __init__
self.validate_timeframes(config['ticker_interval'])
File "/opt/Projects/freqtrade/freqtrade/exchange/exchange.py", line 272, in validate_timeframes
timeframes = self._api.timeframes
AttributeError: 'bitstamp' object has no attribute 'timeframes'

# Fixed code
def __init__(self, exchange_name: str, config: dict) -> None:
    """
    Load the custom class from config parameter
    :param config: configuration dictionary
    """
    exchange_name = exchange_name.title()
    try:
        self.exchange = self._load_exchange(exchange_name, kwargs={"config": config})
    except ImportError:
        logger.info(
            f"No {exchange_name} specific subclass found. Using the generic class instead."
        )
    if not hasattr(self, "exchange"):
        self.exchange = Exchange(config)
# Buggy code
def is_exchange_bad(exchange: str) -> bool:
    return exchange in ["bitmex"]


# Traceback (AttributeError)
Traceback (most recent call last):
File "/opt/Projects/freqtrade/freqtrade/main.py", line 51, in main
worker = Worker(args)
File "/opt/Projects/freqtrade/freqtrade/worker.py", line 35, in __init__
self._init(False)
File "/opt/Projects/freqtrade/freqtrade/worker.py", line 51, in _init
self.freqtrade = FreqtradeBot(self._config)
File "/opt/Projects/freqtrade/freqtrade/freqtradebot.py", line 56, in __init__
self.exchange = ExchangeResolver(self.config['exchange']['name'], self.config).exchange
File "/opt/Projects/freqtrade/freqtrade/resolvers/exchange_resolver.py", line 31, in __init__
self.exchange = Exchange(config)
File "/opt/Projects/freqtrade/freqtrade/exchange/exchange.py", line 140, in __init__
self.validate_timeframes(config['ticker_interval'])
File "/opt/Projects/freqtrade/freqtrade/exchange/exchange.py", line 272, in validate_timeframes
timeframes = self._api.timeframes
AttributeError: 'bitstamp' object has no attribute 'timeframes'

# Fixed code
def is_exchange_bad(exchange: str) -> bool:
    return exchange in ["bitmex", "bitstamp"]
# Buggy code
def min_roi_reached(
    self, trade: Trade, current_profit: float, current_time: datetime
) -> bool:
    """
    Based an earlier trade and current price and ROI configuration, decides whether bot should
    sell. Requires current_profit to be in percent!!
    :return: True if bot should sell at current rate
    """

    # Check if time matches and current rate is above threshold
    trade_dur = (current_time.timestamp() - trade.open_date.timestamp()) / 60

    # Get highest entry in ROI dict where key >= trade-duration
    roi_entry = max(list(filter(lambda x: trade_dur >= x, self.minimal_roi.keys())))
    threshold = self.minimal_roi[roi_entry]
    if current_profit > threshold:
        return True

    return False


# Traceback (ValueError)
2019-06-19 11:07:12,301 - freqtrade - ERROR - Fatal exception!
Traceback (most recent call last):
File "/home/user/Github/freqtrade/freqtrade/main.py", line 46, in main
args.func(args)
File "/home/user/Github/freqtrade/freqtrade/optimize/__init__.py", line 61, in start_backtesting
backtesting.start()
File "/home/user/Github/freqtrade/freqtrade/optimize/backtesting.py", line 449, in start
'end_date': max_date,
File "/home/user/Github/freqtrade/freqtrade/optimize/backtesting.py", line 378, in backtest
max_open_trades)
File "/home/user/Github/freqtrade/freqtrade/optimize/backtesting.py", line 254, in _get_sell_trade_entry
sell_row.sell, low=sell_row.low, high=sell_row.high)
File "/home/user/Github/freqtrade/freqtrade/strategy/interface.py", line 280, in should_sell
if self.min_roi_reached(trade=trade, current_profit=current_profit, current_time=date):
File "/home/user/Github/freqtrade/freqtrade/strategy/interface.py", line 359, in min_roi_reached
roi_entry = max(list(filter(lambda x: trade_dur >= x, self.minimal_roi.keys())))
ValueError: max() arg is an empty sequence

# Fixed code
def min_roi_reached(
    self, trade: Trade, current_profit: float, current_time: datetime
) -> bool:
    """
    Based on trade duration, current price and ROI configuration, decides whether bot should
    sell. Requires current_profit to be in percent!!
    :return: True if bot should sell at current rate
    """
    # Check if time matches and current rate is above threshold
    trade_dur = int((current_time.timestamp() - trade.open_date.timestamp()) // 60)
    roi = self.min_roi_reached_entry(trade_dur)
    if roi is None:
        return False
    else:
        return current_profit > roi
# Buggy code
def min_roi_reached(
    self, trade: Trade, current_profit: float, current_time: datetime
) -> bool:
    """
    Based an earlier trade and current price and ROI configuration, decides whether bot should
    sell. Requires current_profit to be in percent!!
    :return True if bot should sell at current rate
    """

    # Check if time matches and current rate is above threshold
    trade_dur = (current_time.timestamp() - trade.open_date.timestamp()) / 60

    # Get highest entry in ROI dict where key >= trade-duration
    roi_entry = max(list(filter(lambda x: trade_dur >= x, self.minimal_roi.keys())))
    threshold = self.minimal_roi[roi_entry]
    if current_profit > threshold:
        return True

    return False


# Traceback (ValueError)
2019-06-19 11:07:12,301 - freqtrade - ERROR - Fatal exception!
Traceback (most recent call last):
File "/home/user/Github/freqtrade/freqtrade/main.py", line 46, in main
args.func(args)
File "/home/user/Github/freqtrade/freqtrade/optimize/__init__.py", line 61, in start_backtesting
backtesting.start()
File "/home/user/Github/freqtrade/freqtrade/optimize/backtesting.py", line 449, in start
'end_date': max_date,
File "/home/user/Github/freqtrade/freqtrade/optimize/backtesting.py", line 378, in backtest
max_open_trades)
File "/home/user/Github/freqtrade/freqtrade/optimize/backtesting.py", line 254, in _get_sell_trade_entry
sell_row.sell, low=sell_row.low, high=sell_row.high)
File "/home/user/Github/freqtrade/freqtrade/strategy/interface.py", line 280, in should_sell
if self.min_roi_reached(trade=trade, current_profit=current_profit, current_time=date):
File "/home/user/Github/freqtrade/freqtrade/strategy/interface.py", line 359, in min_roi_reached
roi_entry = max(list(filter(lambda x: trade_dur >= x, self.minimal_roi.keys())))
ValueError: max() arg is an empty sequence

# Fixed code
def min_roi_reached(
    self, trade: Trade, current_profit: float, current_time: datetime
) -> bool:
    """
    Based an earlier trade and current price and ROI configuration, decides whether bot should
    sell. Requires current_profit to be in percent!!
    :return True if bot should sell at current rate
    """

    # Check if time matches and current rate is above threshold
    trade_dur = (current_time.timestamp() - trade.open_date.timestamp()) / 60

    # Get highest entry in ROI dict where key <= trade-duration
    roi_list = list(filter(lambda x: x <= trade_dur, self.minimal_roi.keys()))
    if not roi_list:
        return False
    roi_entry = max(roi_list)
    threshold = self.minimal_roi[roi_entry]
    return current_profit > threshold
# Buggy code
def _validate_config(self, conf: Dict[str, Any]) -> Dict[str, Any]:
    """
    Validate the configuration follow the Config Schema
    :param conf: Config in JSON format
    :return: Returns the config if valid, otherwise throw an exception
    """
    try:
        validate(conf, constants.CONF_SCHEMA)
        return conf
    except ValidationError as exception:
        logger.critical(
            "Invalid configuration. See config.json.example. Reason: %s", exception
        )
        raise ValidationError(
            best_match(Draft4Validator(constants.CONF_SCHEMA).iter_errors(conf)).message
        )


# Traceback (jsonschema.exceptions.SchemaError)
root@ghost# freqtrade
/usr/local/lib/python3.6/dist-packages/scikit_learn-0.20rc1-py3.6-linux-x86_64.egg/sklearn/externals/joblib/externals/cloudpickle/cloudpickle.py:47: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
import imp
Fatal exception!
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/freqtrade-0.17.2-py3.6.egg/freqtrade/main.py", line 42, in main
config = Configuration(args).get_config()
File "/usr/local/lib/python3.6/dist-packages/freqtrade-0.17.2-py3.6.egg/freqtrade/configuration.py", line 252, in get_config
self.config = self.load_config()
File "/usr/local/lib/python3.6/dist-packages/freqtrade-0.17.2-py3.6.egg/freqtrade/configuration.py", line 46, in load_config
config = self._load_config_file(self.args.config)
File "/usr/local/lib/python3.6/dist-packages/freqtrade-0.17.2-py3.6.egg/freqtrade/configuration.py", line 84, in _load_config_file
return self._validate_config(conf)
File "/usr/local/lib/python3.6/dist-packages/freqtrade-0.17.2-py3.6.egg/freqtrade/configuration.py", line 235, in _validate_config
validate(conf, constants.CONF_SCHEMA)
File "/usr/local/lib/python3.6/dist-packages/jsonschema-3.0.0a2-py3.6.egg/jsonschema/validators.py", line 822, in validate
cls.check_schema(schema)
File "/usr/local/lib/python3.6/dist-packages/jsonschema-3.0.0a2-py3.6.egg/jsonschema/validators.py", line 244, in check_schema
raise SchemaError.create_from(error)
jsonschema.exceptions.SchemaError: True is not of type 'number'

Failed validating 'type' in metaschema['properties']['properties']['additionalProperties']['properties']['exclusiveMaximum']:
{'type': 'number'}

On schema['properties']['stoploss']['exclusiveMaximum']:
True

# Fixed code
def _validate_config(self, conf: Dict[str, Any]) -> Dict[str, Any]:
    """
    Validate the configuration follow the Config Schema
    :param conf: Config in JSON format
    :return: Returns the config if valid, otherwise throw an exception
    """
    try:
        validate(conf, constants.CONF_SCHEMA, Draft4Validator)
        return conf
    except ValidationError as exception:
        logger.critical(
            "Invalid configuration. See config.json.example. Reason: %s", exception
        )
        raise ValidationError(
            best_match(Draft4Validator(constants.CONF_SCHEMA).iter_errors(conf)).message
        )
# Buggy code
def _load_cryptomap(self) -> None:
    try:
        coinlistings = self._coinmarketcap.listings()
        self._cryptomap = dict(
            map(lambda coin: (coin["symbol"], str(coin["id"])), coinlistings["data"])
        )
    except (ValueError, RequestException) as exception:
        logger.error(
            "Could not load FIAT Cryptocurrency map for the following problem: %s",
            exception,
        )


# Traceback (TypeError)
2018-07-21T09:03:52.460172600Z 2018-07-21 09:03:52,460 - freqtrade.freqtradebot - INFO - Starting freqtrade 0.17.1
2018-07-21T09:03:52.462962628Z 2018-07-21 09:03:52,462 - freqtrade.strategy.resolver - INFO - Using resolved strategy drytest from '/freqtrade/user_data/strategies'
2018-07-21T09:03:52.463336085Z 2018-07-21 09:03:52,463 - freqtrade.strategy.resolver - INFO - Override strategy 'ticker_interval' with value in config file: 5m.
2018-07-21T09:03:52.747250440Z 2018-07-21 09:03:52,745 - freqtrade - ERROR - Fatal exception!
2018-07-21T09:03:52.747315154Z Traceback (most recent call last):
2018-07-21T09:03:52.747334690Z   File "/freqtrade/freqtrade/main.py", line 45, in main
2018-07-21T09:03:52.747353198Z     freqtrade = FreqtradeBot(config)
2018-07-21T09:03:52.747369315Z   File "/freqtrade/freqtrade/freqtradebot.py", line 53, in __init__
2018-07-21T09:03:52.747386269Z     self.fiat_converter = CryptoToFiatConverter()
2018-07-21T09:03:52.747402381Z   File "/freqtrade/freqtrade/fiat_convert.py", line 86, in __init__
2018-07-21T09:03:52.747413407Z     self._load_cryptomap()
2018-07-21T09:03:52.747422809Z   File "/freqtrade/freqtrade/fiat_convert.py", line 92, in _load_cryptomap
2018-07-21T09:03:52.747432702Z     coinlistings["data"]))
2018-07-21T09:03:52.747442715Z TypeError: 'JSONDecodeError' object is not subscriptable
2018-07-21T09:03:52.747336930Z conn is HTTPSConnectionPool(host='api.coinmarketcap.com', port=443)

# Fixed code
def _load_cryptomap(self) -> None:
    try:
        coinlistings = self._coinmarketcap.listings()
        self._cryptomap = dict(
            map(lambda coin: (coin["symbol"], str(coin["id"])), coinlistings["data"])
        )
    except BaseException as exception:
        logger.error(
            "Could not load FIAT Cryptocurrency map for the following problem: %s",
            type(exception).__name__,
        )
# Buggy code
def scripts_options(self) -> None:
    """
    Parses given arguments for plot scripts.
    """
    self.parser.add_argument(
        "-p",
        "--pair",
        help="Show profits for only this pairs. Pairs are comma-separated.",
        dest="pair",
        default=None,
    )


# Traceback (AttributeError)
(.env) [freqtrade] > python3 freqtrade/tests/testdata/download_backtest_data.py
Traceback (most recent call last):
File "freqtrade/tests/testdata/download_backtest_data.py", line 11, in <module>
parser = misc.common_args_parser('download utility')
AttributeError: module 'freqtrade.misc' has no attribute 'common_args_parser'

# Fixed code
def scripts_options(self) -> None:
    """
    Parses given arguments for scripts.
    """
    self.parser.add_argument(
        "-p",
        "--pair",
        help="Show profits for only this pairs. Pairs are comma-separated.",
        dest="pair",
        default=None,
    )
# Buggy code
def init(config: dict) -> None:
    """
    Initializes this module with the given config,
    it does basic validation whether the specified
    exchange and pairs are valid.
    :param config: config to use
    :return: None
    """
    global _CONF, _API

    _CONF.update(config)

    if config["dry_run"]:
        logger.info("Instance is running with dry_run enabled")

    exchange_config = config["exchange"]

    # Find matching class for the given exchange name
    name = exchange_config["name"]

    if name not in ccxt.exchanges:
        raise OperationalException("Exchange {} is not supported".format(name))
    try:
        _API = getattr(ccxt, name.lower())(
            {
                "apiKey": exchange_config.get("key"),
                "secret": exchange_config.get("secret"),
                "password": exchange_config.get("password"),
                "uid": exchange_config.get("uid"),
                "enableRateLimit": True,
            }
        )
    except (KeyError, AttributeError):
        raise OperationalException("Exchange {} is not supported".format(name))

    logger.info('Using Exchange "%s"', get_name())

    # Check if all pairs are available
    validate_pairs(config["exchange"]["pair_whitelist"])


# Traceback (AttributeError)
(.env) [freqtrade] > python3 freqtrade/tests/testdata/download_backtest_data.py
Traceback (most recent call last):
File "freqtrade/tests/testdata/download_backtest_data.py", line 11, in <module>
parser = misc.common_args_parser('download utility')
AttributeError: module 'freqtrade.misc' has no attribute 'common_args_parser'

# Fixed code
def init(config: dict) -> None:
    """
    Initializes this module with the given config,
    it does basic validation whether the specified
    exchange and pairs are valid.
    :param config: config to use
    :return: None
    """
    global _CONF, _API

    _CONF.update(config)

    if config["dry_run"]:
        logger.info("Instance is running with dry_run enabled")

    exchange_config = config["exchange"]
    _API = init_ccxt(exchange_config)

    logger.info('Using Exchange "%s"', get_name())

    # Check if all pairs are available
    validate_pairs(config["exchange"]["pair_whitelist"])
# Buggy code
def file_dump_json(filename, data, is_zip=False) -> None:
    """
    Dump JSON data into a file
    :param filename: file to create
    :param data: JSON Data to save
    :return:
    """
    if is_zip:
        if not filename.endswith(".gz"):
            filename = filename + ".gz"
        with gzip.open(filename, "w") as fp:
            json.dump(data, fp, default=str)
    else:
        with open(filename, "w") as fp:
            json.dump(data, fp, default=str)


# Traceback (AttributeError)
(.env) [freqtrade] > python3 freqtrade/tests/testdata/download_backtest_data.py
Traceback (most recent call last):
File "freqtrade/tests/testdata/download_backtest_data.py", line 11, in <module>
parser = misc.common_args_parser('download utility')
AttributeError: module 'freqtrade.misc' has no attribute 'common_args_parser'

# Fixed code
def file_dump_json(filename, data, is_zip=False) -> None:
    """
    Dump JSON data into a file
    :param filename: file to create
    :param data: JSON Data to save
    :return:
    """
    print(f'dumping json to "{filename}"')

    if is_zip:
        if not filename.endswith(".gz"):
            filename = filename + ".gz"
        with gzip.open(filename, "w") as fp:
            json.dump(data, fp, default=str)
    else:
        with open(filename, "w") as fp:
            json.dump(data, fp, default=str)
# Buggy code
def parse_timerange(text: str) -> Optional[Tuple[List, int, int]]:
    """
    Parse the value of the argument --timerange to determine what is the range desired
    :param text: value from --timerange
    :return: Start and End range period
    """
    if text is None:
        return None
    syntax = [
        (r"^-(\d{8})$", (None, "date")),
        (r"^(\d{8})-$", ("date", None)),
        (r"^(\d{8})-(\d{8})$", ("date", "date")),
        (r"^(-\d+)$", (None, "line")),
        (r"^(\d+)-$", ("line", None)),
        (r"^(\d+)-(\d+)$", ("index", "index")),
    ]
    for rex, stype in syntax:
        # Apply the regular expression to text
        match = re.match(rex, text)
        if match:  # Regex has matched
            rvals = match.groups()
            index = 0
            start = None
            stop = None
            if stype[0]:
                start = rvals[index]
                if stype[0] != "date":
                    start = int(start)
                index += 1
            if stype[1]:
                stop = rvals[index]
                if stype[1] != "date":
                    stop = int(stop)
            return stype, start, stop
    raise Exception('Incorrect syntax for timerange "%s"' % text)


# Traceback (AttributeError)
(.env) [freqtrade] > python3 freqtrade/tests/testdata/download_backtest_data.py
Traceback (most recent call last):
File "freqtrade/tests/testdata/download_backtest_data.py", line 11, in <module>
parser = misc.common_args_parser('download utility')
AttributeError: module 'freqtrade.misc' has no attribute 'common_args_parser'

# Fixed code
def parse_timerange(text: str) -> Optional[Tuple[List, int, int]]:
    """
    Parse the value of the argument --timerange to determine what is the range desired
    :param text: value from --timerange
    :return: Start and End range period
    """
    if text is None:
        return None
    syntax = [
        (r"^-(\d{8})$", (None, "date")),
        (r"^(\d{8})-$", ("date", None)),
        (r"^(\d{8})-(\d{8})$", ("date", "date")),
        (r"^(-\d+)$", (None, "line")),
        (r"^(\d+)-$", ("line", None)),
        (r"^(\d+)-(\d+)$", ("index", "index")),
    ]
    for rex, stype in syntax:
        # Apply the regular expression to text
        match = re.match(rex, text)
        if match:  # Regex has matched
            rvals = match.groups()
            index = 0
            start = None
            stop = None
            if stype[0]:
                start = rvals[index]
                if stype[0] == "date":
                    start = arrow.get(start, "YYYYMMDD").timestamp
                else:
                    start = int(start)
                index += 1
            if stype[1]:
                stop = rvals[index]
                if stype[1] == "date":
                    stop = arrow.get(stop, "YYYYMMDD").timestamp
                else:
                    stop = int(stop)
            return stype, start, stop
    raise Exception('Incorrect syntax for timerange "%s"' % text)
# Buggy code
def get_ticker_history(pair: str, tick_interval: str) -> List[Dict]:
    try:
        return _API.fetch_ohlcv(pair, timeframe=tick_interval)
    except ccxt.NotSupported as e:
        raise OperationalException(
            "Exchange {} does not support fetching historical candlestick data."
            "Message: {}".format(_API.name, e)
        )
    except (ccxt.NetworkError, ccxt.ExchangeError) as e:
        raise TemporaryError(
            "Could not load ticker history due to {}. Message: {}".format(
                e.__class__.__name__, e
            )
        )
    except ccxt.BaseError as e:
        raise OperationalException("Could not fetch ticker data. Msg: {}".format(e))


# Traceback (AttributeError)
(.env) [freqtrade] > python3 freqtrade/tests/testdata/download_backtest_data.py
Traceback (most recent call last):
File "freqtrade/tests/testdata/download_backtest_data.py", line 11, in <module>
parser = misc.common_args_parser('download utility')
AttributeError: module 'freqtrade.misc' has no attribute 'common_args_parser'

# Fixed code
def get_ticker_history(
    pair: str, tick_interval: str, since_ms: Optional[int] = None
) -> List[Dict]:
    try:
        # last item should be in the time interval [now - tick_interval, now]
        till_time_ms = (
            arrow.utcnow()
            .shift(minutes=-constants.TICKER_INTERVAL_MINUTES[tick_interval])
            .timestamp
            * 1000
        )
        # it looks as if some exchanges return cached data
        # and they update it one in several minute, so 10 mins interval
        # is necessary to skeep downloading of an empty array when all
        # chached data was already downloaded
        till_time_ms = min(
            till_time_ms, arrow.utcnow().shift(minutes=-10).timestamp * 1000
        )

        data = []
        while not since_ms or since_ms < till_time_ms:
            data_part = _API.fetch_ohlcv(pair, timeframe=tick_interval, since=since_ms)

            if not data_part:
                break

            logger.info(
                "Downloaded data for time range [%s, %s]",
                arrow.get(data_part[0][0] / 1000).format(),
                arrow.get(data_part[-1][0] / 1000).format(),
            )

            data.extend(data_part)
            since_ms = data[-1][0] + 1

        return data
    except ccxt.NotSupported as e:
        raise OperationalException(
            "Exchange {} does not support fetching historical candlestick data."
            "Message: {}".format(_API.name, e)
        )
    except (ccxt.NetworkError, ccxt.ExchangeError) as e:
        raise TemporaryError(
            "Could not load ticker history due to {}. Message: {}".format(
                e.__class__.__name__, e
            )
        )
    except ccxt.BaseError as e:
        raise OperationalException("Could not fetch ticker data. Msg: {}".format(e))
# Buggy code
def trim_tickerlist(
    tickerlist: List[Dict], timerange: Tuple[Tuple, int, int]
) -> List[Dict]:
    stype, start, stop = timerange
    if stype == (None, "line"):
        return tickerlist[stop:]
    elif stype == ("line", None):
        return tickerlist[0:start]
    elif stype == ("index", "index"):
        return tickerlist[start:stop]

    return tickerlist


# Traceback (AttributeError)
(.env) [freqtrade] > python3 freqtrade/tests/testdata/download_backtest_data.py
Traceback (most recent call last):
File "freqtrade/tests/testdata/download_backtest_data.py", line 11, in <module>
parser = misc.common_args_parser('download utility')
AttributeError: module 'freqtrade.misc' has no attribute 'common_args_parser'

# Fixed code
def trim_tickerlist(
    tickerlist: List[Dict], timerange: Tuple[Tuple, int, int]
) -> List[Dict]:
    if not tickerlist:
        return tickerlist

    stype, start, stop = timerange

    start_index = 0
    stop_index = len(tickerlist)

    if stype[0] == "line":
        stop_index = start
    if stype[0] == "index":
        start_index = start
    elif stype[0] == "date":
        while tickerlist[start_index][0] < start * 1000:
            start_index += 1

    if stype[1] == "line":
        start_index = len(tickerlist) + stop
    if stype[1] == "index":
        stop_index = stop
    elif stype[1] == "date":
        while tickerlist[stop_index - 1][0] > stop * 1000:
            stop_index -= 1

    if start_index > stop_index:
        raise ValueError(f"The timerange [{start},{stop}] is incorrect")

    return tickerlist[start_index:stop_index]
# Buggy code
def load_data(
    datadir: str,
    ticker_interval: str,
    pairs: Optional[List[str]] = None,
    refresh_pairs: Optional[bool] = False,
    timerange: Optional[Tuple[Tuple, int, int]] = None,
) -> Dict[str, List]:
    """
    Loads ticker history data for the given parameters
    :return: dict
    """
    result = {}

    _pairs = pairs or hyperopt_optimize_conf()["exchange"]["pair_whitelist"]

    # If the user force the refresh of pairs
    if refresh_pairs:
        logger.info("Download data for all pairs and store them in %s", datadir)
        download_pairs(datadir, _pairs, ticker_interval)

    for pair in _pairs:
        pairdata = load_tickerdata_file(
            datadir, pair, ticker_interval, timerange=timerange
        )
        if not pairdata:
            # download the tickerdata from exchange
            download_backtesting_testdata(datadir, pair=pair, interval=ticker_interval)
            # and retry reading the pair
            pairdata = load_tickerdata_file(
                datadir, pair, ticker_interval, timerange=timerange
            )
        result[pair] = pairdata
    return result


# Traceback (AttributeError)
(.env) [freqtrade] > python3 freqtrade/tests/testdata/download_backtest_data.py
Traceback (most recent call last):
File "freqtrade/tests/testdata/download_backtest_data.py", line 11, in <module>
parser = misc.common_args_parser('download utility')
AttributeError: module 'freqtrade.misc' has no attribute 'common_args_parser'

# Fixed code
def load_data(
    datadir: str,
    ticker_interval: str,
    pairs: Optional[List[str]] = None,
    refresh_pairs: Optional[bool] = False,
    timerange: Optional[Tuple[Tuple, int, int]] = None,
) -> Dict[str, List]:
    """
    Loads ticker history data for the given parameters
    :return: dict
    """
    result = {}

    _pairs = pairs or hyperopt_optimize_conf()["exchange"]["pair_whitelist"]

    # If the user force the refresh of pairs
    if refresh_pairs:
        logger.info("Download data for all pairs and store them in %s", datadir)
        download_pairs(datadir, _pairs, ticker_interval, timerange=timerange)

    for pair in _pairs:
        pairdata = load_tickerdata_file(
            datadir, pair, ticker_interval, timerange=timerange
        )
        if not pairdata:
            # download the tickerdata from exchange
            download_backtesting_testdata(
                datadir, pair=pair, tick_interval=ticker_interval, timerange=timerange
            )
            # and retry reading the pair
            pairdata = load_tickerdata_file(
                datadir, pair, ticker_interval, timerange=timerange
            )
        result[pair] = pairdata
    return result
# Buggy code
def download_pairs(datadir, pairs: List[str], ticker_interval: str) -> bool:
    """For each pairs passed in parameters, download the ticker intervals"""
    for pair in pairs:
        try:
            download_backtesting_testdata(datadir, pair=pair, interval=ticker_interval)
        except BaseException:
            logger.info(
                'Failed to download the pair: "%s", Interval: %s', pair, ticker_interval
            )
            return False
    return True


# Traceback (AttributeError)
(.env) [freqtrade] > python3 freqtrade/tests/testdata/download_backtest_data.py
Traceback (most recent call last):
File "freqtrade/tests/testdata/download_backtest_data.py", line 11, in <module>
parser = misc.common_args_parser('download utility')
AttributeError: module 'freqtrade.misc' has no attribute 'common_args_parser'

# Fixed code
def download_pairs(
    datadir,
    pairs: List[str],
    ticker_interval: str,
    timerange: Optional[Tuple[Tuple, int, int]] = None,
) -> bool:
    """For each pairs passed in parameters, download the ticker intervals"""
    for pair in pairs:
        try:
            download_backtesting_testdata(
                datadir, pair=pair, tick_interval=ticker_interval, timerange=timerange
            )
        except BaseException:
            logger.info(
                'Failed to download the pair: "%s", Interval: %s', pair, ticker_interval
            )
            return False
    return True
# Buggy code
def _balance(bot: Bot, update: Update) -> None:
    """
    Handler for /balance
    Returns current account balance per crypto
    """
    output = ""
    balances = [
        c
        for c in exchange.get_balances()
        if c["Balance"] or c["Available"] or c["Pending"]
    ]
    if not balances:
        output = "`All balances are zero.`"

    total = 0.0
    for currency in balances:
        coin = currency["Currency"]
        if coin == "BTC":
            currency["Rate"] = 1.0
        else:
            currency["Rate"] = exchange.get_ticker("BTC_" + coin, False)["bid"]
        currency["BTC"] = currency["Rate"] * currency["Balance"]
        total = total + currency["BTC"]
        output += """*Currency*: {Currency}
*Available*: {Available}
*Balance*: {Balance}
*Pending*: {Pending}
*Est. BTC*: {BTC: .8f}

""".format(**currency)

    symbol = _CONF["fiat_display_currency"]
    value = _FIAT_CONVERT.convert_amount(total, "BTC", symbol)
    output += """*Estimated Value*:
*BTC*: {0: .8f}
*{1}*: {2: .2f}
""".format(total, symbol, value)
    send_msg(output)


# Traceback (freqtrade.OperationalException)
2018-01-18 14:45:32,181 - freqtrade.rpc.telegram - INFO - Executing handler: _balance for chat_id: 507292729
2018-01-18 14:45:49,079 - freqtrade.rpc.telegram - ERROR - Exception occurred within Telegram module
Traceback (most recent call last):
File "/home/binh/freqtrade/freqtrade/rpc/telegram.py", line 108, in wrapper
return command_handler(*args, **kwargs)
File "/home/binh/freqtrade/freqtrade/rpc/telegram.py", line 391, in _balance
currency["Rate"] = exchange.get_ticker('BTC_' + coin, False)['bid']
File "/home/binh/freqtrade/freqtrade/exchange/__init__.py", line 138, in get_ticker
return _API.get_ticker(pair, refresh)
File "/home/binh/freqtrade/freqtrade/exchange/bittrex.py", line 124, in get_ticker
pair=pair))
freqtrade.OperationalException: INVALID_MARKET params=(BTC_USDT)

# Fixed code
def _balance(bot: Bot, update: Update) -> None:
    """
    Handler for /balance
    Returns current account balance per crypto
    """
    output = ""
    balances = [
        c
        for c in exchange.get_balances()
        if c["Balance"] or c["Available"] or c["Pending"]
    ]
    if not balances:
        send_msg("`All balances are zero.`")
        return

    total = 0.0
    for currency in balances:
        coin = currency["Currency"]
        if coin == "BTC":
            currency["Rate"] = 1.0
        else:
            if coin == "USDT":
                currency["Rate"] = 1.0 / exchange.get_ticker("USDT_BTC", False)["bid"]
            else:
                currency["Rate"] = exchange.get_ticker("BTC_" + coin, False)["bid"]
        currency["BTC"] = currency["Rate"] * currency["Balance"]
        total = total + currency["BTC"]
        output += """*Currency*: {Currency}
*Available*: {Available}
*Balance*: {Balance}
*Pending*: {Pending}
*Est. BTC*: {BTC: .8f}

""".format(**currency)

    symbol = _CONF["fiat_display_currency"]
    value = _FIAT_CONVERT.convert_amount(total, "BTC", symbol)
    output += """*Estimated Value*:
*BTC*: {0: .8f}
*{1}*: {2: .2f}
""".format(total, symbol, value)
    send_msg(output)
# Buggy code
def init(config: dict, engine: Optional[Engine] = None) -> None:
    """
    Initializes this module with the given config,
    registers all known command handlers
    and starts polling for message updates
    :param config: config to use
    :param engine: database engine for sqlalchemy (Optional)
    :return: None
    """
    _CONF.update(config)
    if not engine:
        if _CONF.get("dry_run", False):
            # the user wants dry run to use a DB
            if _CONF.get("dry_run_db", False):
                engine = create_engine("sqlite:///tradesv3.dry_run.sqlite")
            # Otherwise dry run will store in memory
            else:
                engine = create_engine(
                    "sqlite://",
                    connect_args={"check_same_thread": False},
                    poolclass=StaticPool,
                    echo=False,
                )
        else:
            engine = create_engine("sqlite:///tradesv3.sqlite")

    session = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=True))
    Trade.session = session()
    Trade.query = session.query_property()
    _DECL_BASE.metadata.create_all(engine)


# Traceback (freqtrade.OperationalException)
Traceback (most recent call last):
File "/home/freqtrade/freqtrade/freqtrade/main.py", line 104, in _process
check_handle_timedout(_CONF['unfilledtimeout'])
File "/home/freqtrade/freqtrade/freqtrade/main.py", line 154, in check_handle_timedout
exchange.cancel_order(trade.open_order_id)
File "/home/freqtrade/freqtrade/freqtrade/exchange/__init__.py", line 150, in cancel_order
return _API.cancel_order(order_id)
File "/home/freqtrade/freqtrade/freqtrade/exchange/bittrex.py", line 197, in cancel_order
order_id=order_id))
freqtrade.OperationalException: ORDER_NOT_OPEN params=(03b02exx-adxx-4xx9-xxfc-xx258XXX26xx)

# Fixed code
def init(config: dict, engine: Optional[Engine] = None) -> None:
    """
    Initializes this module with the given config,
    registers all known command handlers
    and starts polling for message updates
    :param config: config to use
    :param engine: database engine for sqlalchemy (Optional)
    :return: None
    """
    _CONF.update(config)
    if not engine:
        if _CONF.get("dry_run", False):
            # the user wants dry run to use a DB
            if _CONF.get("dry_run_db", False):
                engine = create_engine("sqlite:///tradesv3.dry_run.sqlite")
            # Otherwise dry run will store in memory
            else:
                engine = create_engine(
                    "sqlite://",
                    connect_args={"check_same_thread": False},
                    poolclass=StaticPool,
                    echo=False,
                )
        else:
            engine = create_engine("sqlite:///tradesv3.sqlite")

    session = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=True))
    Trade.session = session()
    Trade.query = session.query_property()
    _DECL_BASE.metadata.create_all(engine)

    # Clean dry_run DB
    if _CONF.get("dry_run", False) and _CONF.get("dry_run_db", False):
        clean_dry_run_db()
# Buggy code
def parse_ticker_dataframe(ticker: list) -> DataFrame:
    """
    Analyses the trend for the given ticker history
    :param ticker: See exchange.get_ticker_history
    :return: DataFrame
    """
    columns = {
        "C": "close",
        "V": "volume",
        "O": "open",
        "H": "high",
        "L": "low",
        "T": "date",
    }
    frame = DataFrame(ticker).drop("BV", 1).rename(columns=columns)
    frame["date"] = to_datetime(frame["date"], utc=True, infer_datetime_format=True)
    frame.sort_values("date", inplace=True)
    return frame


# Traceback (ValueError)
2018-01-17 23:26:24,720 - freqtrade.optimize.backtesting - INFO - Using config: config.json ...
2018-01-17 23:26:24,721 - freqtrade.misc - INFO - Validating configuration ...
2018-01-17 23:26:24,724 - freqtrade.optimize.backtesting - INFO - Using ticker_interval: 5 ...
2018-01-17 23:26:24,724 - freqtrade.optimize.backtesting - INFO - Using local backtesting data (using whitelist in given config) ...
2018-01-17 23:26:24,724 - freqtrade.optimize - INFO - Download the pair: "USDT_BTC", Interval: 5 min
2018-01-17 23:26:26,291 - freqtrade.optimize.backtesting - INFO - Using stake_currency: USDT ...
2018-01-17 23:26:26,291 - freqtrade.optimize.backtesting - INFO - Using stake_amount: 10 ...
2018-01-17 23:26:26,291 - freqtrade.optimize.backtesting - INFO - Using max_open_trades: 5 ...
Traceback (most recent call last):
File "bin/freqtrade", line 4, in <module>
main()
File "/data/workspace/freqtrade/freqtrade/main.py", line 412, in main
args.func(args)
File "/data/workspace/freqtrade/freqtrade/optimize/backtesting.py", line 179, in start
preprocessed = preprocess(data)
File "/data/workspace/freqtrade/freqtrade/optimize/__init__.py", line 67, in preprocess
for pair, pair_data in tickerdata.items()}
File "/data/workspace/freqtrade/freqtrade/optimize/__init__.py", line 67, in <dictcomp>
for pair, pair_data in tickerdata.items()}
File "/data/workspace/freqtrade/freqtrade/analyze.py", line 34, in parse_ticker_dataframe
.drop('BV', 1) \
File "/data/workspace/freqtrade/.env/lib/python3.6/site-packages/pandas/core/generic.py", line 2530, in drop
obj = obj._drop_axis(labels, axis, level=level, errors=errors)
File "/data/workspace/freqtrade/.env/lib/python3.6/site-packages/pandas/core/generic.py", line 2562, in _drop_axis
new_axis = axis.drop(labels, errors=errors)
File "/data/workspace/freqtrade/.env/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3744, in drop
labels[mask])
ValueError: labels ['BV'] not contained in axis

# Fixed code
def parse_ticker_dataframe(ticker: list) -> DataFrame:
    """
    Analyses the trend for the given ticker history
    :param ticker: See exchange.get_ticker_history
    :return: DataFrame
    """
    columns = {
        "C": "close",
        "V": "volume",
        "O": "open",
        "H": "high",
        "L": "low",
        "T": "date",
    }
    frame = DataFrame(ticker).rename(columns=columns)
    if "BV" in frame:
        frame.drop("BV", 1, inplace=True)
    frame["date"] = to_datetime(frame["date"], utc=True, infer_datetime_format=True)
    frame.sort_values("date", inplace=True)
    return frame
# Buggy code
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
    if refresh or pair not in self.cached_ticker.keys():
        data = _API.get_ticker(pair.replace("_", "-"))
        if not data["success"]:
            Bittrex._validate_response(data)
            raise OperationalException(
                "{message} params=({pair})".format(message=data["message"], pair=pair)
            )

        if not data.get("result") or not all(
            key in data.get("result", {}) for key in ["Bid", "Ask", "Last"]
        ):
            raise ContentDecodingError(
                "{message} params=({pair})".format(
                    message="Got invalid response from bittrex", pair=pair
                )
            )
        # Update the pair
        self.cached_ticker[pair] = {
            "bid": float(data["result"]["Bid"]),
            "ask": float(data["result"]["Ask"]),
            "last": float(data["result"]["Last"]),
        }
    return self.cached_ticker[pair]


# Traceback (TypeError)
2018-01-19 04:07:38,218 - freqtrade - ERROR - Got fatal exception!
Traceback (most recent call last):
File "/home/binh/freqtrade/freqtrade/main.py", line 474, in main
nb_assets=args.dynamic_whitelist,
File "/home/binh/freqtrade/freqtrade/misc.py", line 82, in throttle
result = func(*args, **kwargs)
File "/home/binh/freqtrade/freqtrade/main.py", line 100, in _process
state_changed = handle_trade(trade) or state_changed
File "/home/binh/freqtrade/freqtrade/main.py", line 262, in handle_trade
current_rate = exchange.get_ticker(trade.pair)['bid']
File "/home/binh/freqtrade/freqtrade/exchange/__init__.py", line 138, in get_ticker
return _API.get_ticker(pair, refresh)
File "/home/binh/freqtrade/freqtrade/exchange/bittrex.py", line 133, in get_ticker
'bid': float(data['result']['Bid']),
TypeError: float() argument must be a string or a number, not 'NoneType'

# Fixed code
def get_ticker(self, pair: str, refresh: Optional[bool] = True) -> dict:
    if refresh or pair not in self.cached_ticker.keys():
        data = _API.get_ticker(pair.replace("_", "-"))
        if not data["success"]:
            Bittrex._validate_response(data)
            raise OperationalException(
                "{message} params=({pair})".format(message=data["message"], pair=pair)
            )
        keys = ["Bid", "Ask", "Last"]
        if (
            not data.get("result")
            or not all(key in data.get("result", {}) for key in keys)
            or not all(data.get("result", {})[key] is not None for key in keys)
        ):
            raise ContentDecodingError(
                "{message} params=({pair})".format(
                    message="Got invalid response from bittrex", pair=pair
                )
            )
        # Update the pair
        self.cached_ticker[pair] = {
            "bid": float(data["result"]["Bid"]),
            "ask": float(data["result"]["Ask"]),
            "last": float(data["result"]["Last"]),
        }
    return self.cached_ticker[pair]
# Buggy code
def plot_parse_args(args):
    parser = common_args_parser(args, "Graph utility")
    parser.add_argument(
        "-p",
        "--pair",
        help="What currency pair",
        dest="pair",
        default="BTC_ETH",
        type=str,
    )
    return parser.parse_args(args)


# Traceback (TypeError)
$ python3  scripts/plot_dataframe.py --pair ETH
Traceback (most recent call last):
File "scripts/plot_dataframe.py", line 69, in <module>
args = plot_parse_args(sys.argv[1:])
File "scripts/plot_dataframe.py", line 13, in plot_parse_args
parser = common_args_parser(args, 'Graph utility')
TypeError: common_args_parser() takes 1 positional argument but 2 were given

# Fixed code
def plot_parse_args(args):
    parser = common_args_parser(description="Graph utility")
    parser.add_argument(
        "-p",
        "--pair",
        help="What currency pair",
        dest="pair",
        default="BTC_ETH",
        type=str,
    )
    return parser.parse_args(args)
# Buggy code
def get_ticker(self, pair: str) -> dict:
    data = _API.get_ticker(pair.replace("_", "-"))
    if not data["success"]:
        raise RuntimeError(
            "{message} params=({pair})".format(message=data["message"], pair=pair)
        )
    if (
        not data["result"]["Bid"]
        or not data["result"]["Ask"]
        or not data["result"]["Last"]
    ):
        raise RuntimeError(
            "{message} params=({pair})".format(message=data["message"], pair=pair)
        )
    return {
        "bid": float(data["result"]["Bid"]),
        "ask": float(data["result"]["Ask"]),
        "last": float(data["result"]["Last"]),
    }


# Traceback (TypeError)
2017-11-15 12:14:48,532 - freqtrade - INFO - Checking buy signals to create a new trade with stake_amount: 0.050000 ...
2017-11-15 12:14:58,986 - freqtrade - INFO - *BITTREX:* Buying [BTC/LUN](https://www.bittrex.com/Market/Index?MarketName=BTC-LUN) with limit `0.00065566`
2017-11-15 12:15:00,378 - freqtrade - INFO - Got open order for Trade(id=5, pair=BTC_LUN, amount=76.06838910410885, open_rate=0.00065566, open_since=just now)
Traceback (most recent call last):
File "./freqtrade/main.py", line 361, in <module>
main()
File "./freqtrade/main.py", line 355, in main
dynamic_whitelist=args.dynamic_whitelist,
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/misc.py", line 52, in throttle
result = func(*args, **kwargs)
File "./freqtrade/main.py", line 91, in _process
state_changed = handle_trade(trade) or state_changed
File "./freqtrade/main.py", line 181, in handle_trade
current_rate = exchange.get_ticker(trade.pair)['bid']
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/exchange/__init__.py", line 128, in get_ticker
return _API.get_ticker(pair)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/exchange/bittrex.py", line 85, in get_ticker
if not data['result']['Bid'] or not data['result']['Ask'] or not data['result']['Last']:
TypeError: 'NoneType' object is not subscriptable
2

# Fixed code
def get_ticker(self, pair: str) -> dict:
    data = _API.get_ticker(pair.replace("_", "-"))
    if not data["success"]:
        raise RuntimeError(
            "{message} params=({pair})".format(message=data["message"], pair=pair)
        )

    if (
        not data.get("result")
        or not data["result"].get("Bid")
        or not data["result"].get("Ask")
        or not data["result"].get("Last")
    ):
        raise ContentDecodingError(
            "{message} params=({pair})".format(
                message="Got invalid response from bittrex", pair=pair
            )
        )
    return {
        "bid": float(data["result"]["Bid"]),
        "ask": float(data["result"]["Ask"]),
        "last": float(data["result"]["Last"]),
    }
# Buggy code
def get_ticker(self, pair: str) -> dict:
    data = _API.get_ticker(pair.replace("_", "-"))
    if not data["success"]:
        raise RuntimeError(
            "{message} params=({pair})".format(message=data["message"], pair=pair)
        )
    return {
        "bid": float(data["result"]["Bid"]),
        "ask": float(data["result"]["Ask"]),
        "last": float(data["result"]["Last"]),
    }


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/bin/freqtrade", line 4, in <module>
main()
File "/usr/lib/python3.6/site-packages/freqtrade/main.py", line 269, in main
app(_CONF)
File "/usr/lib/python3.6/site-packages/freqtrade/main.py", line 249, in app
_process()
File "/usr/lib/python3.6/site-packages/freqtrade/main.py", line 57, in _process
handle_trade(trade)
File "/usr/lib/python3.6/site-packages/freqtrade/main.py", line 137, in handle_trade
current_rate = exchange.get_ticker(trade.pair)['bid']
File "/usr/lib/python3.6/site-packages/freqtrade/exchange.py", line 118, in get_ticker
'bid': float(data['result']['Bid']),
TypeError: float() argument must be a string or a number, not 'NoneType'
2017-10-07 03:55:46,165 - telegram.ext.updater - ERROR - Error while getting Updates: Timed out

# Fixed code
def get_ticker(self, pair: str) -> dict:
    data = _API.get_ticker(pair.replace("_", "-"))
    if not data["success"]:
        raise RuntimeError(
            "{message} params=({pair})".format(message=data["message"], pair=pair)
        )
    if (
        not data["result"]["Bid"]
        or not data["result"]["Ask"]
        or not data["result"]["Last"]
    ):
        raise RuntimeError(
            "{message} params=({pair})".format(message=data["message"], pair=pair)
        )
    return {
        "bid": float(data["result"]["Bid"]),
        "ask": float(data["result"]["Ask"]),
        "last": float(data["result"]["Last"]),
    }