alpacahq / Alpaca-API

The Alpaca API is a developer interface for trading operations and market data reception through the Alpaca platform.
https://alpaca.markets/
142 stars 13 forks source link

Close streaming connection in Python #60

Closed Meinerzhagen closed 5 years ago

Meinerzhagen commented 5 years ago

What is the correct way to deregister channels and eventually close a streaming connection in Python? I did not find any documentation on this.

Meinerzhagen commented 5 years ago

Providing some more context: I am using a cron job to start my trading script every weekday at 09:29AM New York time, and I want to stop/exit my script every day after market close to save some GCP VM compute resources.

Below is some sample Python code:

def run_ws(): conn = tradeapi.StreamConn(key_id=api_key_id, secret_key=api_secret) tickers = get_tickers() symbols = [ticker.ticker for ticker in tickers]

@conn.on(r'A\..*')
async def handle_second_bar(conn, channel, data):
    # Trading here

    now = pd.Timestamp.now(tz=NY)
    my_close = '16:00'
    if (now.time() > pd.Timestamp(my_close, tz=NY).time()):
        print('NYSE is closed for the day at {}'.format(now))
        # Goal: Close websocket and exit run_ws() procedure
        # conn.close does not seem to close the connection...

channels = ['trade_updates']
for symbol in symbols:
    symbol_channels = ['A.{}'.format(symbol), 'AM.{}'.format(symbol)]
    channels += symbol_channels
print('Watching {} symbols.'.format(len(symbols)))
print('This code is executed before async procs, right?')
run_ws(conn, channels)

def run_ws(conn, channels): try: conn.run(channels) except Exception as e: print(e) conn.close run_ws(conn, channels)

if name == "main": run_ws()

Goal: exit script after market close!

ttt733 commented 5 years ago

As you can see in the code you quoted, there is a close() method on the connection object. You can use that to close the connection. You can also individually deregister channels in the Python SDK by calling deregister(), but closing the channels all at once is fine as well. For detecting market close, please take a look at the clock and calendar API endpoints.