forked from msitt/blpapi-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSubscriptionWithEventHandlerExample.py
More file actions
197 lines (165 loc) · 6.97 KB
/
Copy pathSubscriptionWithEventHandlerExample.py
File metadata and controls
197 lines (165 loc) · 6.97 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# SubscriptionWithEventHandlerExample.py
from __future__ import print_function
from __future__ import absolute_import
import blpapi
from optparse import OptionParser
import time
EXCEPTIONS = blpapi.Name("exceptions")
FIELD_ID = blpapi.Name("fieldId")
REASON = blpapi.Name("reason")
CATEGORY = blpapi.Name("category")
DESCRIPTION = blpapi.Name("description")
ERROR_INFO = blpapi.Name("ErrorInfo")
class SubscriptionEventHandler(object):
def getTimeStamp(self):
return time.strftime("%Y/%m/%d %X")
def processSubscriptionStatus(self, event):
timeStamp = self.getTimeStamp()
print("Processing SUBSCRIPTION_STATUS")
for msg in event:
topic = msg.correlationIds()[0].value()
print("%s: %s - %s" % (timeStamp, topic, msg.messageType()))
if msg.hasElement(REASON):
# This can occur on SubscriptionFailure.
reason = msg.getElement(REASON)
if reason.elementDefinition().name() == ERROR_INFO:
print(" %s: %s" % (
reason.getElement(CATEGORY).getValueAsString(),
reason.getElement(DESCRIPTION).getValueAsString()))
if msg.hasElement(EXCEPTIONS):
# This can occur on SubscriptionStarted if at least
# one field is good while the rest are bad.
exceptions = msg.getElement(EXCEPTIONS)
for exInfo in exceptions.values():
fieldId = exInfo.getElement(FIELD_ID)
reason = exInfo.getElement(REASON)
print(" %s: %s" % (
fieldId.getValueAsString(),
reason.getElement(CATEGORY).getValueAsString()))
def processSubscriptionDataEvent(self, event):
timeStamp = self.getTimeStamp()
print()
print("Processing SUBSCRIPTION_DATA")
for msg in event:
topic = msg.correlationIds()[0].value()
print("%s: %s - %s" % (timeStamp, topic, msg.messageType()))
for field in msg.asElement().elements():
if field.numValues() < 1:
print(" %s is NULL" % field.name())
continue
# Assume all values are scalar.
print(" %s = %s" % (field.name(),
field.getValueAsString()))
def processMiscEvents(self, event):
timeStamp = self.getTimeStamp()
for msg in event:
print("%s: %s" % (timeStamp, msg.messageType()))
def processEvent(self, event, session):
try:
if event.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
return self.processSubscriptionDataEvent(event)
elif event.eventType() == blpapi.Event.SUBSCRIPTION_STATUS:
return self.processSubscriptionStatus(event)
else:
return self.processMiscEvents(event)
except blpapi.Exception as e:
print("Library Exception !!! %s" % e.description())
return False
def parseCmdLine():
parser = OptionParser(description="Retrieve realtime data.")
parser.add_option("-a",
"--ip",
dest="host",
help="server name or IP (default: %default)",
metavar="ipAddress",
default="localhost")
parser.add_option("-p",
dest="port",
type="int",
help="server port (default: %default)",
metavar="tcpPort",
default=8194)
parser.add_option("-t",
dest="topics",
help="topic name (default: IBM US Equity)",
metavar="topic",
action="append",
default=[])
parser.add_option("-f",
dest="fields",
help="field to subscribe to (default: LAST_PRICE)",
metavar="field",
action="append",
default=[])
parser.add_option("-o",
dest="options",
help="subscription options (default: empty)",
metavar="option",
action="append",
default=[])
(options, args) = parser.parse_args()
if not options.topics:
options.topics = ["IBM US Equity"]
if not options.fields:
options.fields = ["LAST_PRICE"]
return options
def main():
options = parseCmdLine()
# Fill SessionOptions
sessionOptions = blpapi.SessionOptions()
sessionOptions.setServerHost(options.host)
sessionOptions.setServerPort(options.port)
print("Connecting to %s:%d" % (options.host, options.port))
eventHandler = SubscriptionEventHandler()
# Create a Session
session = blpapi.Session(sessionOptions, eventHandler.processEvent)
# Start a Session
if not session.start():
print("Failed to start session.")
return
print("Connected successfully")
service = "//blp/mktdata"
if not session.openService(service):
print("Failed to open %s service" % service)
return
subscriptions = blpapi.SubscriptionList()
for t in options.topics:
topic = service
if not t.startswith("/"):
topic += "/"
topic += t
subscriptions.add(topic, options.fields, options.options,
blpapi.CorrelationId(t))
print("Subscribing...")
session.subscribe(subscriptions)
try:
# Wait for enter key to exit application
print("Press ENTER to quit")
input()
finally:
# Stop the session
session.stop()
if __name__ == "__main__":
print("SubscriptionWithEventHandlerExample")
try:
main()
except KeyboardInterrupt:
print("Ctrl+C pressed. Stopping...")
__copyright__ = """
Copyright 2012. Bloomberg Finance L.P.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above
copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""