Stream close() complains "This event loop is already running"

Hi, I am new to Alpaca and have a problem while trying to close StreamConn properly.

I created a thread to wrap the StreamConn. I do the following while try to close the conn.

“”"
def stop(self, renew=False):
asyncio.get_event_loop().run_until_complete(
self.__conn.close(renew=renew)
)
“”"

The error message is:

Blockquote
2021-01-27 13:05:01,654 streamclient [ERROR] Error stopping websocket client: This event loop is already running.
Exception in thread Thread-1:
Traceback (most recent call last):
File “/usr/lib/python3.8/threading.py”, line 932, in _bootstrap_inner
self.run()
File /pyalgotrade/user_strategies/alpaca_trade/stream_client.py", line 151, in run
self.__client.run()
File “/pyalgotrade/user_strategies/alpaca_trade/stream_client.py”, line 111, in run
self.__conn.run(
File “/pyalgotrade/env/lib/python3.8/site-packages/alpaca_trade_api/stream2.py”, line 335, in run
loop.run_until_complete(self.consume())
File “/usr/lib/python3.8/asyncio/base_events.py”, line 608, in run_until_complete
return future.result()
asyncio.exceptions.CancelledError

Thank you for the help

I tried a much simpler case but still have the issue. Here is the full code.

conn = StreamConn()
print(“Create a thread for the conn”)
conn_thread = threading.Thread(target=conn.run)
print(“Before thread start”)
conn_thread.start()
print(“After thread start”)

print(“Sleep for 1second”)
time.sleep(1)

loop = conn.loop
loop.run_until_complete(conn.close(renew=False))

The print out is:
“”
Create a thread for the client
Before thread start
After thread start
Sleep for 1second
Traceback (most recent call last):
File “/usr/lib/python3.8/runpy.py”, line 192, in _run_module_as_main
2021-02-03 21:42:45,786 root [ERROR] error while consuming ws messages: ‘NoneType’ object has no attribute ‘consume’
return _run_code(code, main_globals, None,
File “/usr/lib/python3.8/runpy.py”, line 85, in _run_code
exec(code, run_globals)
File “/home/USER/pyalgotrade/user_strategies/test/test_stream_client.py”, line 168, in
loop.run_until_complete(client.close(renew=False))
File “/usr/lib/python3.8/asyncio/base_events.py”, line 595, in run_until_complete
self.run_forever()
File “/usr/lib/python3.8/asyncio/base_events.py”, line 550, in run_forever
raise RuntimeError(‘This event loop is already running’)
RuntimeError: This event loop is already running
“”