如何在 Bloomberg Python API 订阅中检查订阅状态是否错误?

How to check if the subscription status is bad in Bloomberg Python API subscription?

我正在编写一个程序,使用 Python API 的订阅方法进行 Bloomberg 数据馈送检查。我快要完成它了,我现在正在尝试涵盖边缘情况,例如订阅失败。 我想检查订阅是否失败。如果失败,我会把它写入一个名为BadSubscription.txt.

的文件中

Bloomberg API 软件包 SimpleSubcriptionExample.py 附带的示例程序之一只有 1 行用于订阅状态的代码,所以它没有给我一个清晰的概念。

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)

当订阅不存在的 security/equity 订阅失败时,上面的代码打印以下内容:

SubscriptionFailure = {
    reason = {
        errorCode = 2
        description = "Invalid security, rcode = -11"
        category = "BAD_SEC"
        source = " [nid:3924]:bbdbm10"
    }
}

订阅成功后会打印:

SubscriptionStarted = {
    exceptions[] = {
    }
    streamIds[] = {
        "1"
    }
    receivedFrom = {
        address = "localhost:8194"
    }
    reason = "Subscriber made a subscription"
}

我想做的是为我的程序编写一个 if 语句来捕获 SubscriptionFailure 并将消息写入文件:

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)

我正在寻找要在我的 if 语句中使用的条件。

我尝试阅读以下存储库,但它也没有解释太多。 https://bloomberg.github.io/blpapi-docs/python/3.13/_autosummary/blpapi.Session.html?highlight=subscription%20status

我第一次尝试

msg.correlationIds()[0].value().find("SubscriptionFailure")!=-1

作为条件,但这没有用。

感谢@assylias,我找到了解决方案。

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)

以上代码将以下内容写入我的文件:

SubscriptionFailure = {
    reason = {
        errorCode = 2
        description = "Invalid security, rcode = -11"
        category = "BAD_SEC"
        source = " [nid:235]:bbdbm10"
    }
}