'This event loop is already running'

Hi, I am new to ALPACA. I have tried to run the streaming example on SPYDER but every time it gives me following errror:

“Exception from websocket connection: asyncio.run() cannot be called from a running event loop”

Here is the code:

import logging
import time,os
from alpaca_trade_api.stream import Stream
from alpaca_trade_api.common import URL

logging.basicConfig(format=’%(asctime)s %(message)s’, level=logging.INFO)

ALPACA_API_KEY = os.getenv(‘APCA_API_KEY_ID’)
ALPACA_SECRET_KEY = os.getenv(‘APCA_API_SECRET_KEY’)

def run_connection(conn):
try:
conn.run()
except KeyboardInterrupt:
print(“Interrupted execution by user”)
“”“loop.run_until_complete(conn.stop_ws())”""
exit(0)
except Exception as e:
print(f’Exception from websocket connection: {e}’)
finally:
print(“Trying to re-establish connection”)
time.sleep(3)
run_connection(conn)

async def print_quote(q):
print(‘quote’, q)

if name == ‘main’:
conn = Stream(ALPACA_API_KEY,
ALPACA_SECRET_KEY,
base_url=URL(‘https://paper-api.alpaca.markets’),
data_feed=‘iex’)

conn.subscribe_quotes(print_quote, 'AAPL')

run_connection(conn)
1 Like