I am writing a program for doing Bloomberg data-feed check using the subscription method of Python API. I am close to finishing it and I am now trying to cover edge cases such as a failed subscription. I want to check if a subscription has failed. If it fails, I will write it into a file named BadSubscription.txt.
One of he example programs that come with Bloomberg API package, SimpleSubcriptionExample.py, has just 1 line of code for Subscription Status so it doesn't give me a clear idea.
try:
# Process received events
eventCount = 0
while(True):
# We provide timeout to give the chance to Ctrl+C handling:
event = session.nextEvent(15000)
for msg in event:
if event.eventType() == blpapi.Event.SUBSCRIPTION_STATUS or \
event.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
print("%s - %s" % (msg.correlationIds()[0].value(), msg))
else:
print(msg)
The above code prints the following when a subscription fails for subscribing to a security/equity that doesn't exist:
SubscriptionFailure = {
reason = {
errorCode = 2
description = "Invalid security, rcode = -11"
category = "BAD_SEC"
source = " [nid:3924]:bbdbm10"
}
}
And when a subscription is successful it prints:
SubscriptionStarted = {
exceptions[] = {
}
streamIds[] = {
"1"
}
receivedFrom = {
address = "localhost:8194"
}
reason = "Subscriber made a subscription"
}
What I want to do is write an if statement for my program to catch the SubscriptionFailure and write the message to the file:
for msg in event:
if (event.eventType() == blpapi.Event.SUBSCRIPTION_STATUS
and (**the condition to catch the error**)):
f = open("BadSubscription.txt", "a+")
f.write(msg)
I am looking for a condition to use in my if statement.
I tried reading the following repository but it doesn't explain much, too. https://bloomberg.github.io/blpapi-docs/python/3.13/_autosummary/blpapi.Session.html?highlight=subscription%20status
I first tried
msg.correlationIds()[0].value().find("SubscriptionFailure")!=-1
as the condition but that didn't work.
Thanks to @assylias I found the solution.
for msg in event:
if (event.eventType() == blpapi.Event.SUBSCRIPTION_STATUS
and msg.messageType() == "SubscriptionFailure"):
f = open("BadSubscription.txt", "a+")
s = ""
if msg.getElement("reason").getElement("errorCode").getValueAsInteger() !=12:
s = msg.toString()
f.write(s)
The above code writes the following to my file:
SubscriptionFailure = {
reason = {
errorCode = 2
description = "Invalid security, rcode = -11"
category = "BAD_SEC"
source = " [nid:235]:bbdbm10"
}
}