# Buggy code
def _rpc_trade_statistics(
    self, stake_currency: str, fiat_display_currency: str
) -> Dict[str, Any]:
    """Returns cumulative profit statistics"""
    trades = Trade.query.order_by(Trade.id).all()

    profit_all_coin = []
    profit_all_perc = []
    profit_closed_coin = []
    profit_closed_perc = []
    durations = []

    for trade in trades:
        current_rate: float = 0.0

        if not trade.open_rate:
            continue
        if trade.close_date:
            durations.append((trade.close_date - trade.open_date).total_seconds())

        if not trade.is_open:
            profit_percent = trade.calc_profit_percent()
            profit_closed_coin.append(trade.calc_profit())
            profit_closed_perc.append(profit_percent)
        else:
            # Get current rate
            try:
                current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
            except DependencyException:
                current_rate = NAN
            profit_percent = trade.calc_profit_percent(rate=current_rate)

        profit_all_coin.append(
            trade.calc_profit(rate=Decimal(trade.close_rate or current_rate))
        )
        profit_all_perc.append(profit_percent)

    best_pair = (
        Trade.session.query(
            Trade.pair, sql.func.sum(Trade.close_profit).label("profit_sum")
        )
        .filter(Trade.is_open.is_(False))
        .group_by(Trade.pair)
        .order_by(sql.text("profit_sum DESC"))
        .first()
    )

    if not best_pair:
        raise RPCException("no closed trade")

    bp_pair, bp_rate = best_pair

    # Prepare data to display
    profit_closed_coin_sum = round(sum(profit_closed_coin), 8)
    profit_closed_percent = (
        round(mean(profit_closed_perc) * 100, 2) if profit_closed_perc else 0.0
    )
    profit_closed_fiat = (
        self._fiat_converter.convert_amount(
            profit_closed_coin_sum, stake_currency, fiat_display_currency
        )
        if self._fiat_converter
        else 0
    )

    profit_all_coin_sum = round(sum(profit_all_coin), 8)
    profit_all_percent = (
        round(mean(profit_all_perc) * 100, 2) if profit_all_perc else 0.0
    )
    profit_all_fiat = (
        self._fiat_converter.convert_amount(
            profit_all_coin_sum, stake_currency, fiat_display_currency
        )
        if self._fiat_converter
        else 0
    )

    num = float(len(durations) or 1)
    return {
        "profit_closed_coin": profit_closed_coin_sum,
        "profit_closed_percent": profit_closed_percent,
        "profit_closed_fiat": profit_closed_fiat,
        "profit_all_coin": profit_all_coin_sum,
        "profit_all_percent": profit_all_percent,
        "profit_all_fiat": profit_all_fiat,
        "trade_count": len(trades),
        "first_trade_date": arrow.get(trades[0].open_date).humanize(),
        "latest_trade_date": arrow.get(trades[-1].open_date).humanize(),
        "avg_duration": str(timedelta(seconds=sum(durations) / num)).split(".")[0],
        "best_pair": bp_pair,
        "best_rate": round(bp_rate * 100, 2),
    }


# 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_trade_statistics(
    self, stake_currency: str, fiat_display_currency: str
) -> Dict[str, Any]:
    """Returns cumulative profit statistics"""
    trades = Trade.get_trades().order_by(Trade.id).all()

    profit_all_coin = []
    profit_all_perc = []
    profit_closed_coin = []
    profit_closed_perc = []
    durations = []

    for trade in trades:
        current_rate: float = 0.0

        if not trade.open_rate:
            continue
        if trade.close_date:
            durations.append((trade.close_date - trade.open_date).total_seconds())

        if not trade.is_open:
            profit_percent = trade.calc_profit_percent()
            profit_closed_coin.append(trade.calc_profit())
            profit_closed_perc.append(profit_percent)
        else:
            # Get current rate
            try:
                current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
            except DependencyException:
                current_rate = NAN
            profit_percent = trade.calc_profit_percent(rate=current_rate)

        profit_all_coin.append(
            trade.calc_profit(rate=Decimal(trade.close_rate or current_rate))
        )
        profit_all_perc.append(profit_percent)

    best_pair = Trade.get_best_pair()

    if not best_pair:
        raise RPCException("no closed trade")

    bp_pair, bp_rate = best_pair

    # Prepare data to display
    profit_closed_coin_sum = round(sum(profit_closed_coin), 8)
    profit_closed_percent = (
        round(mean(profit_closed_perc) * 100, 2) if profit_closed_perc else 0.0
    )
    profit_closed_fiat = (
        self._fiat_converter.convert_amount(
            profit_closed_coin_sum, stake_currency, fiat_display_currency
        )
        if self._fiat_converter
        else 0
    )

    profit_all_coin_sum = round(sum(profit_all_coin), 8)
    profit_all_percent = (
        round(mean(profit_all_perc) * 100, 2) if profit_all_perc else 0.0
    )
    profit_all_fiat = (
        self._fiat_converter.convert_amount(
            profit_all_coin_sum, stake_currency, fiat_display_currency
        )
        if self._fiat_converter
        else 0
    )

    num = float(len(durations) or 1)
    return {
        "profit_closed_coin": profit_closed_coin_sum,
        "profit_closed_percent": profit_closed_percent,
        "profit_closed_fiat": profit_closed_fiat,
        "profit_all_coin": profit_all_coin_sum,
        "profit_all_percent": profit_all_percent,
        "profit_all_fiat": profit_all_fiat,
        "trade_count": len(trades),
        "first_trade_date": arrow.get(trades[0].open_date).humanize(),
        "latest_trade_date": arrow.get(trades[-1].open_date).humanize(),
        "avg_duration": str(timedelta(seconds=sum(durations) / num)).split(".")[0],
        "best_pair": bp_pair,
        "best_rate": round(bp_rate * 100, 2),
    }