# Buggy code
def _rpc_forcesell(self, trade_id) -> Dict[str, str]:
    """
    Handler for forcesell <id>.
    Sells the given trade at current price
    """

    def _exec_forcesell(trade: Trade) -> None:
        # Check if there is there is an open order
        if trade.open_order_id:
            order = self._freqtrade.exchange.get_order(trade.open_order_id, trade.pair)

            # Cancel open LIMIT_BUY orders and close trade
            if (
                order
                and order["status"] == "open"
                and order["type"] == "limit"
                and order["side"] == "buy"
            ):
                self._freqtrade.exchange.cancel_order(trade.open_order_id, trade.pair)
                trade.close(order.get("price") or trade.open_rate)
                # Do the best effort, if we don't know 'filled' amount, don't try selling
                if order["filled"] is None:
                    return
                trade.amount = order["filled"]

            # Ignore trades with an attached LIMIT_SELL order
            if (
                order
                and order["status"] == "open"
                and order["type"] == "limit"
                and order["side"] == "sell"
            ):
                return

        # Get current rate and execute sell
        current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
        self._freqtrade.execute_sell(trade, current_rate, SellType.FORCE_SELL)

    # ---- EOF def _exec_forcesell ----

    if self._freqtrade.state != State.RUNNING:
        raise RPCException("trader is not running")

    if trade_id == "all":
        # Execute sell for all open orders
        for trade in Trade.get_open_trades():
            _exec_forcesell(trade)
        Trade.session.flush()
        return {"result": "Created sell orders for all open trades."}

    # Query for trade
    trade = Trade.query.filter(
        sql.and_(Trade.id == trade_id, Trade.is_open.is_(True))
    ).first()
    if not trade:
        logger.warning("forcesell: Invalid argument received")
        raise RPCException("invalid argument")

    _exec_forcesell(trade)
    Trade.session.flush()
    return {"result": f"Created sell order for trade {trade_id}."}


# 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 _rpc_forcesell(self, trade_id) -> Dict[str, str]:
    """
    Handler for forcesell <id>.
    Sells the given trade at current price
    """

    def _exec_forcesell(trade: Trade) -> None:
        # Check if there is there is an open order
        if trade.open_order_id:
            order = self._freqtrade.exchange.get_order(trade.open_order_id, trade.pair)

            # Cancel open LIMIT_BUY orders and close trade
            if (
                order
                and order["status"] == "open"
                and order["type"] == "limit"
                and order["side"] == "buy"
            ):
                self._freqtrade.exchange.cancel_order(trade.open_order_id, trade.pair)
                trade.close(order.get("price") or trade.open_rate)
                # Do the best effort, if we don't know 'filled' amount, don't try selling
                if order["filled"] is None:
                    return
                trade.amount = order["filled"]

            # Ignore trades with an attached LIMIT_SELL order
            if (
                order
                and order["status"] == "open"
                and order["type"] == "limit"
                and order["side"] == "sell"
            ):
                return

        # Get current rate and execute sell
        current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
        self._freqtrade.execute_sell(trade, current_rate, SellType.FORCE_SELL)

    # ---- EOF def _exec_forcesell ----

    if self._freqtrade.state != State.RUNNING:
        raise RPCException("trader is not running")

    if trade_id == "all":
        # Execute sell for all open orders
        for trade in Trade.get_open_trades():
            _exec_forcesell(trade)
        Trade.session.flush()
        return {"result": "Created sell orders for all open trades."}

    # Query for trade
    trade = Trade.get_trades(
        trade_filter=[
            Trade.id == trade_id,
            Trade.is_open.is_(True),
        ]
    ).first()
    if not trade:
        logger.warning("forcesell: Invalid argument received")
        raise RPCException("invalid argument")

    _exec_forcesell(trade)
    Trade.session.flush()
    return {"result": f"Created sell order for trade {trade_id}."}