# Buggy code
def create_trade(stake_amount: float) -> Optional[Trade]:
    """
    Checks the implemented trading indicator(s) for a randomly picked pair,
    if one pair triggers the buy_signal a new trade record gets created
    :param stake_amount: amount of btc to spend
    """
    logger.info(
        "Checking buy signals to create a new trade with stake_amount: %f ...",
        stake_amount,
    )
    whitelist = copy.deepcopy(_CONF["exchange"]["pair_whitelist"])
    # Check if stake_amount is fulfilled
    if exchange.get_balance(_CONF["stake_currency"]) < stake_amount:
        raise ValueError(
            "stake amount is not fulfilled (currency={})".format(
                _CONF["stake_currency"]
            )
        )

    # Remove currently opened and latest pairs from whitelist
    for trade in Trade.query.filter(Trade.is_open.is_(True)).all():
        if trade.pair in whitelist:
            whitelist.remove(trade.pair)
            logger.debug("Ignoring %s in pair whitelist", trade.pair)
    if not whitelist:
        raise ValueError("No pair in whitelist")

    # Pick pair based on StochRSI buy signals
    for _pair in whitelist:
        if get_buy_signal(_pair):
            pair = _pair
            break
    else:
        return None

    # Calculate amount and subtract fee
    fee = exchange.get_fee()
    buy_limit = get_target_bid(exchange.get_ticker(pair))
    amount = (1 - fee) * stake_amount / buy_limit

    order_id = exchange.buy(pair, buy_limit, amount)
    # Create trade entity and return
    message = "*{}:* Buying [{}]({}) with limit `{:.8f}`".format(
        exchange.get_name().upper(),
        pair.replace("_", "/"),
        exchange.get_pair_detail_url(pair),
        buy_limit,
    )
    logger.info(message)
    telegram.send_msg(message)
    # Fee is applied twice because we make a LIMIT_BUY and LIMIT_SELL
    return Trade(
        pair=pair,
        stake_amount=stake_amount,
        amount=amount,
        fee=fee * 2,
        open_rate=buy_limit,
        open_date=datetime.utcnow(),
        exchange=exchange.get_name().upper(),
        open_order_id=order_id,
    )


# 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 create_trade(stake_amount: float) -> Optional[Trade]:
    """
    Checks the implemented trading indicator(s) for a randomly picked pair,
    if one pair triggers the buy_signal a new trade record gets created
    :param stake_amount: amount of btc to spend
    """
    logger.info(
        "Checking buy signals to create a new trade with stake_amount: %f ...",
        stake_amount,
    )
    whitelist = copy.deepcopy(_CONF["exchange"]["pair_whitelist"])
    # Check if stake_amount is fulfilled
    if exchange.get_balance(_CONF["stake_currency"]) < stake_amount:
        raise FreqtradeException(
            "stake amount is not fulfilled (currency={})".format(
                _CONF["stake_currency"]
            )
        )

    # Remove currently opened and latest pairs from whitelist
    for trade in Trade.query.filter(Trade.is_open.is_(True)).all():
        if trade.pair in whitelist:
            whitelist.remove(trade.pair)
            logger.debug("Ignoring %s in pair whitelist", trade.pair)
    if not whitelist:
        raise FreqtradeException("No pair in whitelist")

    # Pick pair based on StochRSI buy signals
    for _pair in whitelist:
        if get_buy_signal(_pair):
            pair = _pair
            break
    else:
        return None

    # Calculate amount and subtract fee
    fee = exchange.get_fee()
    buy_limit = get_target_bid(exchange.get_ticker(pair))
    amount = (1 - fee) * stake_amount / buy_limit

    order_id = exchange.buy(pair, buy_limit, amount)
    # Create trade entity and return
    message = "*{}:* Buying [{}]({}) with limit `{:.8f}`".format(
        exchange.get_name().upper(),
        pair.replace("_", "/"),
        exchange.get_pair_detail_url(pair),
        buy_limit,
    )
    logger.info(message)
    telegram.send_msg(message)
    # Fee is applied twice because we make a LIMIT_BUY and LIMIT_SELL
    return Trade(
        pair=pair,
        stake_amount=stake_amount,
        amount=amount,
        fee=fee * 2,
        open_rate=buy_limit,
        open_date=datetime.utcnow(),
        exchange=exchange.get_name().upper(),
        open_order_id=order_id,
    )