forked from RayCui/py-api-streaming
-
Notifications
You must be signed in to change notification settings - Fork 42
/
streaming.py
83 lines (66 loc) · 2.64 KB
/
streaming.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""
Demonstrates streaming feature in OANDA open api
To execute, run the following command:
python streaming.py [options]
To show heartbeat, replace [options] by -b or --displayHeartBeat
"""
import requests
import json
from optparse import OptionParser
def connect_to_stream():
"""
Environment Description
fxTrade (Live) The live (real money) environment
fxTrade Practice (Demo) The demo (simulated money) environment
"""
domainDict = { 'live' : 'stream-fxtrade.oanda.com',
'demo' : 'stream-fxpractice.oanda.com' }
# Replace the following variables with your personal values
environment = "demo" # Replace this 'live' if you wish to connect to the live environment
domain = domainDict[environment]
access_token = 'REPLACE THIS WITH YOUR ACCESS TOKEN'
account_id = 'REPLACE THIS WITH YOUR ACCOUNT ID, ie 2252344'
instruments = 'REPLACE THIS WITH THE INSTRUMENTS YOU WOULD LIKE TO SUBSCRIBE TO. ie "EUR_USD,USD_JPY,...'
try:
s = requests.Session()
url = "https://" + domain + "/v1/prices"
headers = {'Authorization' : 'Bearer ' + access_token,
# 'X-Accept-Datetime-Format' : 'unix'
}
params = {'instruments' : instruments, 'accountId' : account_id}
req = requests.Request('GET', url, headers = headers, params = params)
pre = req.prepare()
resp = s.send(pre, stream = True, verify = True)
return resp
except Exception as e:
s.close()
print("Caught exception when connecting to stream\n" + str(e))
def demo(displayHeartbeat):
response = connect_to_stream()
if response.status_code != 200:
print(response.text)
return
for line in response.iter_lines(1):
if line:
try:
line = line.decode('utf-8')
msg = json.loads(line)
except Exception as e:
print("Caught exception when converting message into json\n" + str(e))
return
if "instrument" in msg or "tick" in msg or displayHeartbeat:
print(line)
def main():
usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option("-b", "--displayHeartBeat", dest = "verbose", action = "store_true",
help = "Display HeartBeat in streaming data")
displayHeartbeat = False
(options, args) = parser.parse_args()
if len(args) > 1:
parser.error("incorrect number of arguments")
if options.verbose:
displayHeartbeat = True
demo(displayHeartbeat)
if __name__ == "__main__":
main()