prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Running asyncio.get_event_loop() in some thread other than the main thread – however, asyncio only generates an event loop for the main thread.
  OS: Ubuntu 21.04
  Branch: develop
  Command: freqtrade trade --config config.json --strategy SampleStrategy
  ....
  Error Message: 
  Exception in thread Thread-1:
  Traceback (most recent call last):
    File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
      self.run()
    File "/usr/lib/python3.9/threading.py", line 892, in run
      self._target(*self._args, **self._kwargs)
    File "/fredtrade/develop/freqtrade/freqtrade/rpc/api_server/uvicorn_threaded.py", line 36, in run
      loop = asyncio.get_event_loop()
    File "/usr/lib/python3.9/asyncio/events.py", line 642, in get_event_loop
      raise RuntimeError('There is no current event loop in thread %r.'
  RuntimeError: There is no current event loop in thread 'Thread-1'.
  
  Solution: 
  File - ./freqtrade/rpc/api_server/uvicorn_threaded.py
  Line - 36
  
  Change:
  ```
          loop = asyncio.get_event_loop()
  ```
  To:
  ```
          try:
              loop = asyncio.get_event_loop()
          except RuntimeError as ex:
              if "There is no current event loop in thread" in str(ex):
                  asyncio.set_event_loop(asyncio.new_event_loop())
                  loop = asyncio.get_event_loop()                
  ```        
  
  --- 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/rpc/api_server/uvicorn_threaded.py`
  Content:
  ```
  1 import contextlib
  2 import threading
  3 import time
  4 
  5 import uvicorn
  6 
  7 
  8 class UvicornServer(uvicorn.Server):
  9     """
  10     Multithreaded server - as found in https://github.com/encode/uvicorn/issues/742
  11 
  12     Removed install_signal_handlers() override based on changes from this commit:
  13         https://github.com/encode/uvicorn/commit/ce2ef45a9109df8eae038c0ec323eb63d644cbc6
  14 
  15     Cannot rely on asyncio.get_event_loop() to create new event loop because of this check:
  16         https://github.com/python/cpython/blob/4d7f11e05731f67fd2c07ec2972c6cb9861d52be/Lib/asyncio/events.py#L638
  17 
  18     Fix by overriding run() and forcing creation of new event loop if uvloop is available
  19     """
  20 
  21     def run(self, sockets=None):
  22         import asyncio
  23 
  24         """
  25         Parent implementation calls self.config.setup_event_loop(),
  26             but we need to create uvloop event loop manually
  27         """
  28         try:
  29             import uvloop  # noqa
  30         except ImportError:  # pragma: no cover
  31             from uvicorn.loops.asyncio import asyncio_setup
  32             asyncio_setup()
  33         else:
  34             asyncio.set_event_loop(uvloop.new_event_loop())
  35 
  36         loop = asyncio.get_event_loop()
  37         loop.run_until_complete(self.serve(sockets=sockets))
  38 
  39     @contextlib.contextmanager
  40     def run_in_thread(self):
  41         self.thread = threading.Thread(target=self.run)
  42         self.thread.start()
  43         while not self.started:
  44             time.sleep(1e-3)
  45 
  46     def cleanup(self):
  47         self.should_exit = True
  48         self.thread.join()
  49
  ```
  --- 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/rpc/api_server/uvicorn_threaded.py b/freqtrade/rpc/api_server/uvicorn_threaded.py
  --- a/freqtrade/rpc/api_server/uvicorn_threaded.py
  +++ b/freqtrade/rpc/api_server/uvicorn_threaded.py
  @@ -32,8 +32,11 @@
               asyncio_setup()
           else:
               asyncio.set_event_loop(uvloop.new_event_loop())
  -
  -        loop = asyncio.get_event_loop()
  +        try:
  +            loop = asyncio.get_event_loop()
  +        except RuntimeError:
  +            # When running in a thread, we'll not have an eventloop yet.
  +            loop = asyncio.new_event_loop()
           loop.run_until_complete(self.serve(sockets=sockets))
   
       @contextlib.contextmanager
  
verification_info: {"golden_diff": "diff --git a/freqtrade/rpc/api_server/uvicorn_threaded.py b/freqtrade/rpc/api_server/uvicorn_threaded.py\n--- a/freqtrade/rpc/api_server/uvicorn_threaded.py\n+++ b/freqtrade/rpc/api_server/uvicorn_threaded.py\n@@ -32,8 +32,11 @@\n             asyncio_setup()\n         else:\n             asyncio.set_event_loop(uvloop.new_event_loop())\n-\n-        loop = asyncio.get_event_loop()\n+        try:\n+            loop = asyncio.get_event_loop()\n+        except RuntimeError:\n+            # When running in a thread, we'll not have an eventloop yet.\n+            loop = asyncio.new_event_loop()\n         loop.run_until_complete(self.serve(sockets=sockets))\n \n     @contextlib.contextmanager\n", "issue": "Running asyncio.get_event_loop() in some thread other than the main thread \u2013 however, asyncio only generates an event loop for the main thread.\nOS: Ubuntu 21.04\r\nBranch: develop\r\nCommand: freqtrade trade --config config.json --strategy SampleStrategy\r\n....\r\nError Message: \r\nException in thread Thread-1:\r\nTraceback (most recent call last):\r\n  File \"/usr/lib/python3.9/threading.py\", line 954, in _bootstrap_inner\r\n    self.run()\r\n  File \"/usr/lib/python3.9/threading.py\", line 892, in run\r\n    self._target(*self._args, **self._kwargs)\r\n  File \"/fredtrade/develop/freqtrade/freqtrade/rpc/api_server/uvicorn_threaded.py\", line 36, in run\r\n    loop = asyncio.get_event_loop()\r\n  File \"/usr/lib/python3.9/asyncio/events.py\", line 642, in get_event_loop\r\n    raise RuntimeError('There is no current event loop in thread %r.'\r\nRuntimeError: There is no current event loop in thread 'Thread-1'.\r\n\r\nSolution: \r\nFile - ./freqtrade/rpc/api_server/uvicorn_threaded.py\r\nLine - 36\r\n\r\nChange:\r\n```\r\n        loop = asyncio.get_event_loop()\r\n```\r\nTo:\r\n```\r\n        try:\r\n            loop = asyncio.get_event_loop()\r\n        except RuntimeError as ex:\r\n            if \"There is no current event loop in thread\" in str(ex):\r\n                asyncio.set_event_loop(asyncio.new_event_loop())\r\n                loop = asyncio.get_event_loop()                \r\n```        \n", "before_files": [{"content": "import contextlib\nimport threading\nimport time\n\nimport uvicorn\n\n\nclass UvicornServer(uvicorn.Server):\n    \"\"\"\n    Multithreaded server - as found in https://github.com/encode/uvicorn/issues/742\n\n    Removed install_signal_handlers() override based on changes from this commit:\n        https://github.com/encode/uvicorn/commit/ce2ef45a9109df8eae038c0ec323eb63d644cbc6\n\n    Cannot rely on asyncio.get_event_loop() to create new event loop because of this check:\n        https://github.com/python/cpython/blob/4d7f11e05731f67fd2c07ec2972c6cb9861d52be/Lib/asyncio/events.py#L638\n\n    Fix by overriding run() and forcing creation of new event loop if uvloop is available\n    \"\"\"\n\n    def run(self, sockets=None):\n        import asyncio\n\n        \"\"\"\n        Parent implementation calls self.config.setup_event_loop(),\n            but we need to create uvloop event loop manually\n        \"\"\"\n        try:\n            import uvloop  # noqa\n        except ImportError:  # pragma: no cover\n            from uvicorn.loops.asyncio import asyncio_setup\n            asyncio_setup()\n        else:\n            asyncio.set_event_loop(uvloop.new_event_loop())\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(self.serve(sockets=sockets))\n\n    @contextlib.contextmanager\n    def run_in_thread(self):\n        self.thread = threading.Thread(target=self.run)\n        self.thread.start()\n        while not self.started:\n            time.sleep(1e-3)\n\n    def cleanup(self):\n        self.should_exit = True\n        self.thread.join()\n", "path": "freqtrade/rpc/api_server/uvicorn_threaded.py"}], "after_files": [{"content": "import contextlib\nimport threading\nimport time\n\nimport uvicorn\n\n\nclass UvicornServer(uvicorn.Server):\n    \"\"\"\n    Multithreaded server - as found in https://github.com/encode/uvicorn/issues/742\n\n    Removed install_signal_handlers() override based on changes from this commit:\n        https://github.com/encode/uvicorn/commit/ce2ef45a9109df8eae038c0ec323eb63d644cbc6\n\n    Cannot rely on asyncio.get_event_loop() to create new event loop because of this check:\n        https://github.com/python/cpython/blob/4d7f11e05731f67fd2c07ec2972c6cb9861d52be/Lib/asyncio/events.py#L638\n\n    Fix by overriding run() and forcing creation of new event loop if uvloop is available\n    \"\"\"\n\n    def run(self, sockets=None):\n        import asyncio\n\n        \"\"\"\n        Parent implementation calls self.config.setup_event_loop(),\n            but we need to create uvloop event loop manually\n        \"\"\"\n        try:\n            import uvloop  # noqa\n        except ImportError:  # pragma: no cover\n            from uvicorn.loops.asyncio import asyncio_setup\n            asyncio_setup()\n        else:\n            asyncio.set_event_loop(uvloop.new_event_loop())\n        try:\n            loop = asyncio.get_event_loop()\n        except RuntimeError:\n            # When running in a thread, we'll not have an eventloop yet.\n            loop = asyncio.new_event_loop()\n        loop.run_until_complete(self.serve(sockets=sockets))\n\n    @contextlib.contextmanager\n    def run_in_thread(self):\n        self.thread = threading.Thread(target=self.run)\n        self.thread.start()\n        while not self.started:\n            time.sleep(1e-3)\n\n    def cleanup(self):\n        self.should_exit = True\n        self.thread.join()\n", "path": "freqtrade/rpc/api_server/uvicorn_threaded.py"}]}