# 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 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


# 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 _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:
        logger.warning("Got %s in _process(), retrying in 30 seconds...", error)
        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