Skip to content

Commit 377d2cb

Browse files
authored
Create PriceStream.py
1 parent 5d6ed61 commit 377d2cb

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

crypto/PriceStream.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
'''
2+
PriceStream.py
3+
Example websocket connection for price data
4+
Author: Dan Wallace
5+
Date: 6/5/2021
6+
7+
Notes:
8+
-> This example script shows how to subscribe to binance websockets for multiple tickers
9+
-> The script handles each push from the websocket and prints out the price for each coin subscribed too
10+
11+
Example: response from Binance /@miniTicker websocket
12+
{
13+
"e": "24hrMiniTicker", // Event type
14+
"E": 123456789, // Event time
15+
"s": "BNBBTC", // Symbol
16+
"c": "0.0025", // Close price
17+
"o": "0.0010", // Open price
18+
"h": "0.0025", // High price
19+
"l": "0.0010", // Low price
20+
"v": "10000", // Total traded base asset volume
21+
"q": "18" // Total traded quote asset volume
22+
}
23+
'''
24+
import json
25+
from websocket import create_connection
26+
27+
# Set coins to subscribe to and create appropriate websocket url
28+
coins = ['btcusdt','ethusdt','dogeusdt']
29+
url = 'wss://stream.binance.com:9443/ws'
30+
for x in coins:
31+
url += '/'+x+'@miniTicker'
32+
33+
# Parse websocket results
34+
def parse_ws(result):
35+
msg = json.loads(result)
36+
print(msg['s']+' :: {:.2f}'.format(float(msg['c'])))
37+
38+
# Create connection
39+
ws = create_connection(url)
40+
41+
# Main loop
42+
while True:
43+
try:
44+
result = ws.recv()
45+
parse_ws(result)
46+
except Exception as e:
47+
print(e)
48+
break

0 commit comments

Comments
 (0)