-
Notifications
You must be signed in to change notification settings - Fork 534
/
dynamic_subscription_example.py
57 lines (44 loc) · 1.43 KB
/
dynamic_subscription_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
In this example code we will show a pattern that allows a user to change
the websocket subscriptions as they please.
"""
import logging
import threading
import asyncio
import time
from alpaca_trade_api.stream import Stream
from alpaca_trade_api.common import URL
ALPACA_API_KEY = "<YOUR-API-KEY>"
ALPACA_SECRET_KEY = "<YOUR-SECRET-KEY>"
async def print_trade(t):
print('trade', t)
async def print_quote(q):
print('quote', q)
async def print_bar(bar):
print('bar', bar)
PREVIOUS = None
def consumer_thread():
global conn
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')
global PREVIOUS
PREVIOUS = "AAPL"
conn.run()
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO)
threading.Thread(target=consumer_thread).start()
time.sleep(5) # give the initial connection time to be established
subscriptions = {"BABA": print_quote,
"AAPL": print_quote,
"TSLA": print_quote,
}
while 1:
for ticker, handler in subscriptions.items():
conn.unsubscribe_quotes(PREVIOUS)
conn.subscribe_quotes(handler, ticker)
PREVIOUS = ticker
time.sleep(20)