I've been playing around with the API from alpaca.markets here https://github.com/alpacahq/alpaca-trade-api-python and I'm trying stream data but also let the user close the connection with an input however I'm not entirely sure how to go about this. I've included an attempt to exit with a keyboard interrupt which doesn't seem to work. Looking for someone to point me in the right direction.
EDIT: I've tried to do this with threading however I'm not sure if this is the right way to go about it as the endstream() doesn't seem to run.
What the code looks like.
import alpaca_trade_api as tradeapi
import threading
conn = tradeapi.StreamConn(xxx,xxx,xxx)
def streamorders(conn):
t1 = threading.Thread(target = startstream(conn))
t2 = threading.Thread(target = endstream(conn))
t1.start()
t2.start()
t1.join()
t2.join()
return
def startstream(conn):
@conn.on(r'trade_updates')
async def on_msg(conn, data, symbols):
print('Order completed')
conn.run(['trade_updates'])
def endstream(conn):
time.sleep(0.2)
userAction = int(input('Press 0 to stop streaming: '))
if userAction == 0:
conn.close()
return
streamorders(conn)
Ideally I want it to behave like this
order completed
order completed
order completed
Press 0 to exit:
from Closing StreamConn with user input
No comments:
Post a Comment