# Buggy code
def check_handle_timedout(self) -> None:
    """
    Check if any orders are timed out and cancel if neccessary
    :param timeoutvalue: Number of minutes until order is considered timed out
    :return: None
    """
    buy_timeout = self.config["unfilledtimeout"]["buy"]
    sell_timeout = self.config["unfilledtimeout"]["sell"]
    buy_timeout_threshold = arrow.utcnow().shift(minutes=-buy_timeout).datetime
    sell_timeout_threshold = arrow.utcnow().shift(minutes=-sell_timeout).datetime

    for trade in Trade.query.filter(Trade.open_order_id.isnot(None)).all():
        try:
            # FIXME: Somehow the query above returns results
            # where the open_order_id is in fact None.
            # This is probably because the record got
            # updated via /forcesell in a different thread.
            if not trade.open_order_id:
                continue
            order = self.exchange.get_order(trade.open_order_id, trade.pair)
        except (RequestException, DependencyException, InvalidOrderException):
            logger.info(
                "Cannot query order for %s due to %s", trade, traceback.format_exc()
            )
            continue
        ordertime = arrow.get(order["datetime"]).datetime

        # Check if trade is still actually open
        if float(order["remaining"]) == 0.0:
            self.wallets.update()
            continue

        if (order["side"] == "buy" and order["status"] == "canceled") or (
            order["status"] == "open"
            and order["side"] == "buy"
            and ordertime < buy_timeout_threshold
        ):
            self.handle_timedout_limit_buy(trade, order)
            self.wallets.update()

        elif (order["side"] == "sell" and order["status"] == "canceled") or (
            order["status"] == "open"
            and order["side"] == "sell"
            and ordertime < sell_timeout_threshold
        ):
            self.handle_timedout_limit_sell(trade, order)
            self.wallets.update()


# Traceback (sqlalchemy.exc.InvalidRequestError)
2019-06-30 03:51:36,539 - freqtrade.rpc.telegram - INFO - Executing handler: _forcebuy for chat_id: 146554112
2019-06-30 03:51:36,545 - freqtrade.freqtradebot - INFO - Using Last Ask / Last Price
2019-06-30 03:51:37,260 - freqtrade.rpc.rpc_manager - INFO - Sending rpc message: {'type': buy, 'exchange': 'Binance', 'pair': 'ALGO/USDT', 'limit': 1.5642505330623224, 'order_type': 'market', 'stake_amount': 13811.040136000001, 'stake_currency': 'USDT', 'fiat_currency': 'USD'}
2019-06-30 03:51:37,612 - freqtrade.freqtradebot - INFO - Found open order for Trade(id=None, pair=ALGO/USDT, amount=8829.17400000, open_rate=1.56425053, open_since=closed)
2019-06-30 03:51:37,758 - freqtrade.freqtradebot - WARNING - Amount 8829.173999999999 does not match amount 8829.174
2019-06-30 03:51:37,760 - freqtrade.freqtradebot - WARNING - Could not update trade amount: Half bought? Amounts don't match
2019-06-30 03:51:37,760 - freqtrade.persistence - INFO - Updating trade (id=None) ...
2019-06-30 03:51:37,760 - freqtrade.persistence - INFO - MARKET_BUY has been fulfilled for Trade(id=None, pair=ALGO/USDT, amount=8829.17400000, open_rate=1.56425053, open_since=closed).
2019-06-30 03:51:37,761 - freqtrade.rpc.telegram - ERROR - Exception occurred within Telegram module
Traceback (most recent call last):
File "/home/dante/freqtrade/freqtrade/rpc/telegram.py", line 52, in wrapper
return command_handler(self, *args, **kwargs)
File "/home/dante/freqtrade/freqtrade/rpc/telegram.py", line 433, in _forcebuy
self._rpc_forcebuy(pair, price)
File "/home/dante/freqtrade/freqtrade/rpc/rpc.py", line 432, in _rpc_forcebuy
if self._freqtrade.execute_buy(pair, stakeamount, price):
File "/home/dante/freqtrade/freqtrade/freqtradebot.py", line 416, in execute_buy
self.update_trade_state(trade, order)
File "/home/dante/freqtrade/freqtrade/freqtradebot.py", line 539, in update_trade_state
trade.update(order)
File "/home/dante/freqtrade/freqtrade/persistence.py", line 317, in update
cleanup()
File "/home/dante/freqtrade/freqtrade/persistence.py", line 155, in cleanup
Trade.session.flush()
File "/home/dante/.local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2445, in flush
raise sa_exc.InvalidRequestError("Session is already flushing")
sqlalchemy.exc.InvalidRequestError: Session is already flushing

# Fixed code
def check_handle_timedout(self) -> None:
    """
    Check if any orders are timed out and cancel if neccessary
    :param timeoutvalue: Number of minutes until order is considered timed out
    :return: None
    """
    buy_timeout = self.config["unfilledtimeout"]["buy"]
    sell_timeout = self.config["unfilledtimeout"]["sell"]
    buy_timeout_threshold = arrow.utcnow().shift(minutes=-buy_timeout).datetime
    sell_timeout_threshold = arrow.utcnow().shift(minutes=-sell_timeout).datetime

    for trade in Trade.get_open_order_trades():
        try:
            # FIXME: Somehow the query above returns results
            # where the open_order_id is in fact None.
            # This is probably because the record got
            # updated via /forcesell in a different thread.
            if not trade.open_order_id:
                continue
            order = self.exchange.get_order(trade.open_order_id, trade.pair)
        except (RequestException, DependencyException, InvalidOrderException):
            logger.info(
                "Cannot query order for %s due to %s", trade, traceback.format_exc()
            )
            continue
        ordertime = arrow.get(order["datetime"]).datetime

        # Check if trade is still actually open
        if float(order["remaining"]) == 0.0:
            self.wallets.update()
            continue

        if (order["side"] == "buy" and order["status"] == "canceled") or (
            order["status"] == "open"
            and order["side"] == "buy"
            and ordertime < buy_timeout_threshold
        ):
            self.handle_timedout_limit_buy(trade, order)
            self.wallets.update()

        elif (order["side"] == "sell" and order["status"] == "canceled") or (
            order["status"] == "open"
            and order["side"] == "sell"
            and ordertime < sell_timeout_threshold
        ):
            self.handle_timedout_limit_sell(trade, order)
            self.wallets.update()