2

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: 
ThatsNotMyName
  • 572
  • 2
  • 8
  • 24
  • 1
    I noticed https://stackoverflow.com/questions/58454190/python-async-waiting-for-stdin-input-while-doing-other-stuff might be similar, I'm currently trying to get it to work with my code. Looks like I went about it the completely wrong way with threads. – ThatsNotMyName Dec 28 '20 at 14:22
  • 2
    Does the input have to be from the standard input? If you'll only use the input to close the connection and end the program then you can add a SIGINT handler instead. See: https://stackoverflow.com/a/1112350/4180662 – yemre Jan 04 '21 at 21:56
  • 1
    I'll take a look at that when I get home in a few hours, it looks like it could work but this function gets called by another one. This would end the entire program wouldn't it? – ThatsNotMyName Jan 05 '21 at 02:46

0 Answers0