# Buggy code
def _process(dynamic_whitelist: Optional[bool] = False) -> bool:
    """
    Queries the persistence layer for open trades and handles them,
    otherwise a new trade is created.
    :param: dynamic_whitelist: True is a dynamic whitelist should be generated (optional)
    :return: True if a trade has been created or closed, False otherwise
    """
    state_changed = False
    try:
        # Refresh whitelist based on wallet maintenance
        refresh_whitelist(
            gen_pair_whitelist(_CONF["stake_currency"]) if dynamic_whitelist else None
        )
        # Query trades from persistence layer
        trades = Trade.query.filter(Trade.is_open.is_(True)).all()
        if len(trades) < _CONF["max_open_trades"]:
            try:
                # Create entity and execute trade
                trade = create_trade(float(_CONF["stake_amount"]))
                if trade:
                    Trade.session.add(trade)
                    state_changed = True
                else:
                    logger.info(
                        "Checked all whitelisted currencies. "
                        "Found no suitable entry positions for buying. Will keep looking ..."
                    )
            except ValueError:
                logger.exception("Unable to create trade")

        for trade in trades:
            # Get order details for actual price per unit
            if trade.open_order_id:
                # Update trade with order values
                logger.info("Got open order for %s", trade)
                trade.update(exchange.get_order(trade.open_order_id))

            if not close_trade_if_fulfilled(trade):
                # Check if we can sell our current pair
                state_changed = handle_trade(trade) or state_changed

            Trade.session.flush()
    except (requests.exceptions.RequestException, json.JSONDecodeError) as error:
        msg = "Got {} in _process(), retrying in 30 seconds...".format(
            error.__class__.__name__
        )
        logger.exception(msg)
        time.sleep(30)
    except RuntimeError:
        telegram.send_msg(
            "*Status:* Got RuntimeError:\n```\n{traceback}```{hint}".format(
                traceback=traceback.format_exc(),
                hint="Issue `/start` if you think it is safe to restart.",
            )
        )
        logger.exception("Got RuntimeError. Stopping trader ...")
        update_state(State.STOPPED)
    return state_changed


# Traceback (json.decoder.JSONDecodeError)
2017-11-15 21:24:28,211 - freqtrade - INFO - Checking buy signals to create a new trade with stake_amount: 0.050000 ...
2017-11-15 21:26:16,135 - freqtrade - ERROR - Unable to create trade
Traceback (most recent call last):
File "./freqtrade/main.py", line 70, in _process
trade = create_trade(float(_CONF['stake_amount']))
File "./freqtrade/main.py", line 223, in create_trade
if get_buy_signal(_pair):
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/analyze.py", line 99, in get_buy_signal
dataframe = analyze_ticker(pair)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/analyze.py", line 82, in analyze_ticker
ticker_hist = get_ticker_history(pair)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/lib/python3.6/site-packages/cachetools/__init__.py", line 46, in wrapper
v = func(*args, **kwargs)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/exchange/__init__.py", line 133, in get_ticker_history
return _API.get_ticker_history(pair, tick_interval)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/exchange/bittrex.py", line 103, in get_ticker_history
data = _API_V2.get_candles(pair.replace('_', '-'), interval)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/src/python-bittrex/bittrex/bittrex.py", line 794, in get_candles
}, protection=PROTECTION_PUB)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/src/python-bittrex/bittrex/bittrex.py", line 154, in _api_query
return self.dispatch(request_url, apisign)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/src/python-bittrex/bittrex/bittrex.py", line 77, in using_requests
headers={"apisign": apisign}
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/lib/python3.6/site-packages/requests/models.py", line 892, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
2017-11-15 21:26:16,346 - freqtrade - INFO - Checking buy signals to create a new trade with stake_amount: 0.050000 ...
2017-11-15 21:26:23,034 - freqtrade - INFO - *BITTREX:* Buying [BTC/XRP](https://www.bittrex.com/Market/Index?MarketName=BTC-XRP) with limit `0.00002919`
2017-11-15 21:26:26,300 - freqtrade - INFO - Checking buy signals to create a new trade with stake_amount: 0.050000 ...
2017-11-15 21:26:35,587 - freqtrade - INFO - Checked all whitelisted currencies. Found no suitable entry positions for buying. Will keep looking ...
2017-11-15 21:26:35,588 - freqtrade - INFO - Got open order for Trade(id=2, pair=BTC_XRP, amount=1708.63309352518, open_rate=2.919e-05, open_since=seconds ago)
2017-11-15 21:26:36,344 - freqtrade - INFO - Checking buy signals to create a new trade with stake_amount: 0.050000 ...
2017-11-15 21:26:36,974 - freqtrade - INFO - Checked all whitelisted currencies. Found no suitable entry positions for buying. Will keep looking ...
2017-11-15 21:26:39,015 - freqtrade.rpc.telegram - INFO - Executing handler: _status for chat_id: 497298357
2017-11-15 21:26:46,314 - freqtrade - INFO - Checking buy signals to create a new trade with stake_amount: 0.050000 ...
2017-11-15 21:26:46,969 - freqtrade - INFO - Checked all whitelisted currencies. Found no suitable entry positions for buying. Will keep looking ...
2017-11-15 21:26:56,392 - freqtrade - INFO - Checking buy signals to create a new trade with stake_amount: 0.050000 ...
2017-11-15 21:27:12,990 - freqtrade - ERROR - Unable to create trade
Traceback (most recent call last):
File "./freqtrade/main.py", line 70, in _process
trade = create_trade(float(_CONF['stake_amount']))
File "./freqtrade/main.py", line 223, in create_trade
if get_buy_signal(_pair):
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/analyze.py", line 99, in get_buy_signal
dataframe = analyze_ticker(pair)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/analyze.py", line 82, in analyze_ticker
ticker_hist = get_ticker_history(pair)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/lib/python3.6/site-packages/cachetools/__init__.py", line 46, in wrapper
v = func(*args, **kwargs)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/exchange/__init__.py", line 133, in get_ticker_history
return _API.get_ticker_history(pair, tick_interval)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/freqtrade/exchange/bittrex.py", line 103, in get_ticker_history
data = _API_V2.get_candles(pair.replace('_', '-'), interval)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/src/python-bittrex/bittrex/bittrex.py", line 794, in get_candles
}, protection=PROTECTION_PUB)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/src/python-bittrex/bittrex/bittrex.py", line 154, in _api_query
return self.dispatch(request_url, apisign)
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/src/python-bittrex/bittrex/bittrex.py", line 77, in using_requests
headers={"apisign": apisign}
File "/Users/sgrimm/dev/cryptos/bots/freqtrade/.env/lib/python3.6/site-packages/requests/models.py", line 892, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
2017-11-15 21:27:14,055 - freqtrade - INFO - Checking buy signals to create a new trade with stake_amount: 0.050000 ...

# Fixed code
def _process(dynamic_whitelist: Optional[bool] = False) -> bool:
    """
    Queries the persistence layer for open trades and handles them,
    otherwise a new trade is created.
    :param: dynamic_whitelist: True is a dynamic whitelist should be generated (optional)
    :return: True if a trade has been created or closed, False otherwise
    """
    state_changed = False
    try:
        # Refresh whitelist based on wallet maintenance
        refresh_whitelist(
            gen_pair_whitelist(_CONF["stake_currency"]) if dynamic_whitelist else None
        )
        # Query trades from persistence layer
        trades = Trade.query.filter(Trade.is_open.is_(True)).all()
        if len(trades) < _CONF["max_open_trades"]:
            try:
                # Create entity and execute trade
                trade = create_trade(float(_CONF["stake_amount"]))
                if trade:
                    Trade.session.add(trade)
                    state_changed = True
                else:
                    logger.info(
                        "Checked all whitelisted currencies. "
                        "Found no suitable entry positions for buying. Will keep looking ..."
                    )
            except FreqtradeException as e:
                logger.warning("Unable to create trade: %s", e)

        for trade in trades:
            # Get order details for actual price per unit
            if trade.open_order_id:
                # Update trade with order values
                logger.info("Got open order for %s", trade)
                trade.update(exchange.get_order(trade.open_order_id))

            if not close_trade_if_fulfilled(trade):
                # Check if we can sell our current pair
                state_changed = handle_trade(trade) or state_changed

            Trade.session.flush()
    except (requests.exceptions.RequestException, json.JSONDecodeError) as error:
        msg = "Got {} in _process(), retrying in 30 seconds...".format(
            error.__class__.__name__
        )
        logger.warning(msg)
        time.sleep(30)
    except RuntimeError:
        telegram.send_msg(
            "*Status:* Got RuntimeError:\n```\n{traceback}```{hint}".format(
                traceback=traceback.format_exc(),
                hint="Issue `/start` if you think it is safe to restart.",
            )
        )
        logger.exception("Got RuntimeError. Stopping trader ...")
        update_state(State.STOPPED)
    return state_changed