Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4585ec5

Browse files
add websocket example
1 parent 88ee2e2 commit 4585ec5

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

‎websocket.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import alpaca_trade_api as tradeapi
2+
import threading
3+
import time
4+
5+
6+
# authentication and connection details
7+
api_key = 'Insert_your_api_key_here'
8+
api_secret = 'Insert_your_api_secret_here'
9+
base_url = 'https://paper-api.alpaca.markets'
10+
11+
12+
# instantiate REST API
13+
api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')
14+
15+
16+
# init WebSocket
17+
conn = tradeapi.stream2.StreamConn(
18+
api_key, api_secret, base_url=base_url, data_url=ws_url, data_stream='alpacadatav1'
19+
)
20+
21+
22+
@conn.on(r'^trade_updates$')
23+
async def on_account_updates(conn, channel, account):
24+
print('account', account)
25+
26+
27+
@conn.on(r'^status$')
28+
async def on_status(conn, channel, data):
29+
print('status update', data)
30+
31+
32+
@conn.on(r'^T.AAPL$')
33+
async def trade_info(conn, channel, bar):
34+
print('bars', bar)
35+
print(bar._raw)
36+
37+
38+
@conn.on(r'^Q.AAPL$')
39+
async def quote_info(conn, channel, bar):
40+
print('bars', bar)
41+
42+
43+
@conn.on(r'^AM.AAPL$')
44+
async def on_minute_bars(conn, channel, bar):
45+
print('bars', bar)
46+
47+
48+
# start websocket
49+
def ws_start():
50+
conn.run(['account_updates', 'trade_updates', 'AM.AAPL', 'Q.AAPL', 'T.AAPL'])
51+
52+
53+
ws_thread = threading.Thread(target=ws_start, daemon=True)
54+
ws_thread.start()
55+
56+
57+
# Let the websocket run for 30 seconds
58+
time.sleep(30)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /