prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Telegram Balance not updating correctly after sell
  ## Describe your environment
  
    * Operating system: Ubuntu 18.04
    * Python Version:  2.7.17
    * CCXT version: 1.34.7
    * Freqtrade Version: develop-4c349342
    
  ## Describe the problem:
  
  Balance is not updated after sell on Bittrex live. All positions ever bought, but where sold, are shown in Telegram via /balance, as if they where actually held and in the wallet and are summed up in the estimated value too. The stake currency is updated correctly and the bot trades with correct values.
  
  ### Steps to reproduce:
  
    1. Live trade on Bittrex and have a successful buy and sell on the same position by the bot.
    2. Call /balance in Telegram.
    3. In the response all successfully sold positions show up as not pending, held and available.
    
  ### Observed Results:
  
    * What happened?
       Calling  /balance in Telegram shows all ever bought assets (tested for 3 Days) although they where successfully sold.
    * What did you expect to happen?
        /balance shows actual held positions/wallet. For instance, If no positions are held, the stake currency only would be shown.
  
  ### Relevant code exceptions or logs
  
  2020-09-22 11:42:52 freqtrade.worker: INFO - Bot heartbeat. PID=25032, version='develop-4c349342', state='RUNNING'
  2020-09-22 11:43:13 freqtrade.rpc.telegram: INFO - Executing handler: _balance for chat_id: XXX
  2020-09-22 11:43:15 freqtrade.wallets: INFO - Wallets synced.
  2020-09-22 11:43:15 freqtrade.rpc.rpc: WARNING -  Could not get rate for pair BTXCRD.
  2020-09-22 11:43:52 freqtrade.worker: INFO - Bot heartbeat. PID=25032, version='develop-4c349342', state='RUNNING'
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `freqtrade/wallets.py`
  Content:
  ```
  1 # pragma pylint: disable=W0603
  2 """ Wallet """
  3 
  4 import logging
  5 from typing import Any, Dict, NamedTuple
  6 
  7 import arrow
  8 
  9 from freqtrade.exchange import Exchange
  10 from freqtrade.persistence import Trade
  11 
  12 logger = logging.getLogger(__name__)
  13 
  14 
  15 # wallet data structure
  16 class Wallet(NamedTuple):
  17     currency: str
  18     free: float = 0
  19     used: float = 0
  20     total: float = 0
  21 
  22 
  23 class Wallets:
  24 
  25     def __init__(self, config: dict, exchange: Exchange) -> None:
  26         self._config = config
  27         self._exchange = exchange
  28         self._wallets: Dict[str, Wallet] = {}
  29         self.start_cap = config['dry_run_wallet']
  30         self._last_wallet_refresh = 0
  31         self.update()
  32 
  33     def get_free(self, currency: str) -> float:
  34         balance = self._wallets.get(currency)
  35         if balance and balance.free:
  36             return balance.free
  37         else:
  38             return 0
  39 
  40     def get_used(self, currency: str) -> float:
  41         balance = self._wallets.get(currency)
  42         if balance and balance.used:
  43             return balance.used
  44         else:
  45             return 0
  46 
  47     def get_total(self, currency: str) -> float:
  48         balance = self._wallets.get(currency)
  49         if balance and balance.total:
  50             return balance.total
  51         else:
  52             return 0
  53 
  54     def _update_dry(self) -> None:
  55         """
  56         Update from database in dry-run mode
  57         - Apply apply profits of closed trades on top of stake amount
  58         - Subtract currently tied up stake_amount in open trades
  59         - update balances for currencies currently in trades
  60         """
  61         # Recreate _wallets to reset closed trade balances
  62         _wallets = {}
  63         closed_trades = Trade.get_trades(Trade.is_open.is_(False)).all()
  64         open_trades = Trade.get_trades(Trade.is_open.is_(True)).all()
  65         tot_profit = sum([trade.calc_profit() for trade in closed_trades])
  66         tot_in_trades = sum([trade.stake_amount for trade in open_trades])
  67 
  68         current_stake = self.start_cap + tot_profit - tot_in_trades
  69         _wallets[self._config['stake_currency']] = Wallet(
  70             self._config['stake_currency'],
  71             current_stake,
  72             0,
  73             current_stake
  74         )
  75 
  76         for trade in open_trades:
  77             curr = self._exchange.get_pair_base_currency(trade.pair)
  78             _wallets[curr] = Wallet(
  79                 curr,
  80                 trade.amount,
  81                 0,
  82                 trade.amount
  83             )
  84         self._wallets = _wallets
  85 
  86     def _update_live(self) -> None:
  87         balances = self._exchange.get_balances()
  88 
  89         for currency in balances:
  90             self._wallets[currency] = Wallet(
  91                 currency,
  92                 balances[currency].get('free', None),
  93                 balances[currency].get('used', None),
  94                 balances[currency].get('total', None)
  95             )
  96 
  97     def update(self, require_update: bool = True) -> None:
  98         """
  99         Updates wallets from the configured version.
  100         By default, updates from the exchange.
  101         Update-skipping should only be used for user-invoked /balance calls, since
  102         for trading operations, the latest balance is needed.
  103         :param require_update: Allow skipping an update if balances were recently refreshed
  104         """
  105         if (require_update or (self._last_wallet_refresh + 3600 < arrow.utcnow().timestamp)):
  106             if self._config['dry_run']:
  107                 self._update_dry()
  108             else:
  109                 self._update_live()
  110             logger.info('Wallets synced.')
  111             self._last_wallet_refresh = arrow.utcnow().timestamp
  112 
  113     def get_all_balances(self) -> Dict[str, Any]:
  114         return self._wallets
  115
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/freqtrade/wallets.py b/freqtrade/wallets.py
  --- a/freqtrade/wallets.py
  +++ b/freqtrade/wallets.py
  @@ -2,6 +2,7 @@
   """ Wallet """
   
   import logging
  +from copy import deepcopy
   from typing import Any, Dict, NamedTuple
   
   import arrow
  @@ -93,6 +94,10 @@
                   balances[currency].get('used', None),
                   balances[currency].get('total', None)
               )
  +        # Remove currencies no longer in get_balances output
  +        for currency in deepcopy(self._wallets):
  +            if currency not in balances:
  +                del self._wallets[currency]
   
       def update(self, require_update: bool = True) -> None:
           """
  
verification_info: {"golden_diff": "diff --git a/freqtrade/wallets.py b/freqtrade/wallets.py\n--- a/freqtrade/wallets.py\n+++ b/freqtrade/wallets.py\n@@ -2,6 +2,7 @@\n \"\"\" Wallet \"\"\"\n \n import logging\n+from copy import deepcopy\n from typing import Any, Dict, NamedTuple\n \n import arrow\n@@ -93,6 +94,10 @@\n                 balances[currency].get('used', None),\n                 balances[currency].get('total', None)\n             )\n+        # Remove currencies no longer in get_balances output\n+        for currency in deepcopy(self._wallets):\n+            if currency not in balances:\n+                del self._wallets[currency]\n \n     def update(self, require_update: bool = True) -> None:\n         \"\"\"\n", "issue": "Telegram Balance not updating correctly after sell\n## Describe your environment\r\n\r\n  * Operating system: Ubuntu 18.04\r\n  * Python Version:  2.7.17\r\n  * CCXT version: 1.34.7\r\n  * Freqtrade Version: develop-4c349342\r\n  \r\n## Describe the problem:\r\n\r\nBalance is not updated after sell on Bittrex live. All positions ever bought, but where sold, are shown in Telegram via /balance, as if they where actually held and in the wallet and are summed up in the estimated value too. The stake currency is updated correctly and the bot trades with correct values.\r\n\r\n### Steps to reproduce:\r\n\r\n  1. Live trade on Bittrex and have a successful buy and sell on the same position by the bot.\r\n  2. Call /balance in Telegram.\r\n  3. In the response all successfully sold positions show up as not pending, held and available.\r\n  \r\n### Observed Results:\r\n\r\n  * What happened?\r\n     Calling  /balance in Telegram shows all ever bought assets (tested for 3 Days) although they where successfully sold.\r\n  * What did you expect to happen?\r\n      /balance shows actual held positions/wallet. For instance, If no positions are held, the stake currency only would be shown.\r\n\r\n### Relevant code exceptions or logs\r\n\r\n2020-09-22 11:42:52 freqtrade.worker: INFO - Bot heartbeat. PID=25032, version='develop-4c349342', state='RUNNING'\r\n2020-09-22 11:43:13 freqtrade.rpc.telegram: INFO - Executing handler: _balance for chat_id: XXX\r\n2020-09-22 11:43:15 freqtrade.wallets: INFO - Wallets synced.\r\n2020-09-22 11:43:15 freqtrade.rpc.rpc: WARNING -  Could not get rate for pair BTXCRD.\r\n2020-09-22 11:43:52 freqtrade.worker: INFO - Bot heartbeat. PID=25032, version='develop-4c349342', state='RUNNING'\r\n\n", "before_files": [{"content": "# pragma pylint: disable=W0603\n\"\"\" Wallet \"\"\"\n\nimport logging\nfrom typing import Any, Dict, NamedTuple\n\nimport arrow\n\nfrom freqtrade.exchange import Exchange\nfrom freqtrade.persistence import Trade\n\nlogger = logging.getLogger(__name__)\n\n\n# wallet data structure\nclass Wallet(NamedTuple):\n    currency: str\n    free: float = 0\n    used: float = 0\n    total: float = 0\n\n\nclass Wallets:\n\n    def __init__(self, config: dict, exchange: Exchange) -> None:\n        self._config = config\n        self._exchange = exchange\n        self._wallets: Dict[str, Wallet] = {}\n        self.start_cap = config['dry_run_wallet']\n        self._last_wallet_refresh = 0\n        self.update()\n\n    def get_free(self, currency: str) -> float:\n        balance = self._wallets.get(currency)\n        if balance and balance.free:\n            return balance.free\n        else:\n            return 0\n\n    def get_used(self, currency: str) -> float:\n        balance = self._wallets.get(currency)\n        if balance and balance.used:\n            return balance.used\n        else:\n            return 0\n\n    def get_total(self, currency: str) -> float:\n        balance = self._wallets.get(currency)\n        if balance and balance.total:\n            return balance.total\n        else:\n            return 0\n\n    def _update_dry(self) -> None:\n        \"\"\"\n        Update from database in dry-run mode\n        - Apply apply profits of closed trades on top of stake amount\n        - Subtract currently tied up stake_amount in open trades\n        - update balances for currencies currently in trades\n        \"\"\"\n        # Recreate _wallets to reset closed trade balances\n        _wallets = {}\n        closed_trades = Trade.get_trades(Trade.is_open.is_(False)).all()\n        open_trades = Trade.get_trades(Trade.is_open.is_(True)).all()\n        tot_profit = sum([trade.calc_profit() for trade in closed_trades])\n        tot_in_trades = sum([trade.stake_amount for trade in open_trades])\n\n        current_stake = self.start_cap + tot_profit - tot_in_trades\n        _wallets[self._config['stake_currency']] = Wallet(\n            self._config['stake_currency'],\n            current_stake,\n            0,\n            current_stake\n        )\n\n        for trade in open_trades:\n            curr = self._exchange.get_pair_base_currency(trade.pair)\n            _wallets[curr] = Wallet(\n                curr,\n                trade.amount,\n                0,\n                trade.amount\n            )\n        self._wallets = _wallets\n\n    def _update_live(self) -> None:\n        balances = self._exchange.get_balances()\n\n        for currency in balances:\n            self._wallets[currency] = Wallet(\n                currency,\n                balances[currency].get('free', None),\n                balances[currency].get('used', None),\n                balances[currency].get('total', None)\n            )\n\n    def update(self, require_update: bool = True) -> None:\n        \"\"\"\n        Updates wallets from the configured version.\n        By default, updates from the exchange.\n        Update-skipping should only be used for user-invoked /balance calls, since\n        for trading operations, the latest balance is needed.\n        :param require_update: Allow skipping an update if balances were recently refreshed\n        \"\"\"\n        if (require_update or (self._last_wallet_refresh + 3600 < arrow.utcnow().timestamp)):\n            if self._config['dry_run']:\n                self._update_dry()\n            else:\n                self._update_live()\n            logger.info('Wallets synced.')\n            self._last_wallet_refresh = arrow.utcnow().timestamp\n\n    def get_all_balances(self) -> Dict[str, Any]:\n        return self._wallets\n", "path": "freqtrade/wallets.py"}], "after_files": [{"content": "# pragma pylint: disable=W0603\n\"\"\" Wallet \"\"\"\n\nimport logging\nfrom copy import deepcopy\nfrom typing import Any, Dict, NamedTuple\n\nimport arrow\n\nfrom freqtrade.exchange import Exchange\nfrom freqtrade.persistence import Trade\n\nlogger = logging.getLogger(__name__)\n\n\n# wallet data structure\nclass Wallet(NamedTuple):\n    currency: str\n    free: float = 0\n    used: float = 0\n    total: float = 0\n\n\nclass Wallets:\n\n    def __init__(self, config: dict, exchange: Exchange) -> None:\n        self._config = config\n        self._exchange = exchange\n        self._wallets: Dict[str, Wallet] = {}\n        self.start_cap = config['dry_run_wallet']\n        self._last_wallet_refresh = 0\n        self.update()\n\n    def get_free(self, currency: str) -> float:\n        balance = self._wallets.get(currency)\n        if balance and balance.free:\n            return balance.free\n        else:\n            return 0\n\n    def get_used(self, currency: str) -> float:\n        balance = self._wallets.get(currency)\n        if balance and balance.used:\n            return balance.used\n        else:\n            return 0\n\n    def get_total(self, currency: str) -> float:\n        balance = self._wallets.get(currency)\n        if balance and balance.total:\n            return balance.total\n        else:\n            return 0\n\n    def _update_dry(self) -> None:\n        \"\"\"\n        Update from database in dry-run mode\n        - Apply apply profits of closed trades on top of stake amount\n        - Subtract currently tied up stake_amount in open trades\n        - update balances for currencies currently in trades\n        \"\"\"\n        # Recreate _wallets to reset closed trade balances\n        _wallets = {}\n        closed_trades = Trade.get_trades(Trade.is_open.is_(False)).all()\n        open_trades = Trade.get_trades(Trade.is_open.is_(True)).all()\n        tot_profit = sum([trade.calc_profit() for trade in closed_trades])\n        tot_in_trades = sum([trade.stake_amount for trade in open_trades])\n\n        current_stake = self.start_cap + tot_profit - tot_in_trades\n        _wallets[self._config['stake_currency']] = Wallet(\n            self._config['stake_currency'],\n            current_stake,\n            0,\n            current_stake\n        )\n\n        for trade in open_trades:\n            curr = self._exchange.get_pair_base_currency(trade.pair)\n            _wallets[curr] = Wallet(\n                curr,\n                trade.amount,\n                0,\n                trade.amount\n            )\n        self._wallets = _wallets\n\n    def _update_live(self) -> None:\n        balances = self._exchange.get_balances()\n\n        for currency in balances:\n            self._wallets[currency] = Wallet(\n                currency,\n                balances[currency].get('free', None),\n                balances[currency].get('used', None),\n                balances[currency].get('total', None)\n            )\n        # Remove currencies no longer in get_balances output\n        for currency in deepcopy(self._wallets):\n            if currency not in balances:\n                del self._wallets[currency]\n\n    def update(self, require_update: bool = True) -> None:\n        \"\"\"\n        Updates wallets from the configured version.\n        By default, updates from the exchange.\n        Update-skipping should only be used for user-invoked /balance calls, since\n        for trading operations, the latest balance is needed.\n        :param require_update: Allow skipping an update if balances were recently refreshed\n        \"\"\"\n        if (require_update or (self._last_wallet_refresh + 3600 < arrow.utcnow().timestamp)):\n            if self._config['dry_run']:\n                self._update_dry()\n            else:\n                self._update_live()\n            logger.info('Wallets synced.')\n            self._last_wallet_refresh = arrow.utcnow().timestamp\n\n    def get_all_balances(self) -> Dict[str, Any]:\n        return self._wallets\n", "path": "freqtrade/wallets.py"}]}