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

2024-05-23 21:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个使用Python API的订阅方法进行彭博数据源检查的程序。我即将完成它,我现在正试图涵盖边缘的情况,如失败的订阅。 我想检查订阅是否失败。如果失败,我会将其写入名为BadSubscription.txt的文件中

彭博API包附带的一个示例程序SimpleSubscriptionExample.py只有一行订阅状态代码,所以我不太清楚

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)

当订阅不存在证券/股权而导致订阅失败时,上述代码将打印以下内容:

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


Tags: 文件theto代码程序txteventapi
1条回答
网友
1楼 · 发布于 2024-05-23 21:20:29

我第一次试过

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"
    }
}

相关问题 更多 >