python - 如何使用 python sdk 连接 bloomberg 终端?

标签 python c++ bloomberg

我正在尝试在我的机器上运行 Bloomberg 示例代码。我已经为安装了 Bloomberg Terminal 的机器创建了 teamviewer VPN。我还为两台机器禁用了防火墙。

彭博终端已启动并登录。

代码:

# import blpapi
# options = blpapi.SessionOptions()
# options.setServerHost('7.220.156.135')
# options.setServerPort(8194)
# session = blpapi.Session(options)
#
# session.start()

# ContributionsMktdataExample.py

import blpapi
import time
from optparse import OptionParser, OptionValueError
import datetime
import threading

TOKEN_SUCCESS = blpapi.Name("TokenGenerationSuccess")
TOKEN_FAILURE = blpapi.Name("TokenGenerationFailure")
AUTHORIZATION_SUCCESS = blpapi.Name("AuthorizationSuccess")
TOKEN = blpapi.Name("token")
MARKET_DATA = blpapi.Name("MarketData")
SESSION_TERMINATED = blpapi.Name("SessionTerminated")


g_running = True
g_mutex = threading.Lock()


class AuthorizationStatus:
    WAITING = 1
    AUTHORIZED = 2
    FAILED = 3
    __metaclass__ = blpapi.utils.MetaClassForClassesWithEnums


g_authorizationStatus = dict()


class MyStream(object):
    def __init__(self, id=""):
        self.id = id


class MyEventHandler(object):
    def processEvent(self, event, session):
        global g_running

        for msg in event:
            print msg
            if event.eventType() == blpapi.Event.SESSION_STATUS:
                if msg.messageType() == SESSION_TERMINATED:
                    g_running = False
                continue

            cids = msg.correlationIds()
            with g_mutex:
                for cid in cids:
                    if cid in g_authorizationStatus:
                        if msg.messageType() == AUTHORIZATION_SUCCESS:
                            g_authorizationStatus[cid] = \
                                AuthorizationStatus.AUTHORIZED
                        else:
                            g_authorizationStatus[cid] = \
                                AuthorizationStatus.FAILED


def authOptionCallback(option, opt, value, parser):
    vals = value.split('=', 1)

    if value == "user":
        parser.values.auth = "AuthenticationType=OS_LOGON"
    elif value == "none":
        parser.values.auth = None
    elif vals[0] == "app" and len(vals) == 2:
        parser.values.auth = "AuthenticationMode=APPLICATION_ONLY;" \
                             "ApplicationAuthenticationType=APPNAME_AND_KEY;" \
                             "ApplicationName=" + vals[1]
    elif vals[0] == "userapp" and len(vals) == 2:
        parser.values.auth = "AuthenticationMode=USER_AND_APPLICATION;" \
                             "AuthenticationType=OS_LOGON;" \
                             "ApplicationAuthenticationType=APPNAME_AND_KEY;" \
                             "ApplicationName=" + vals[1]
    elif vals[0] == "dir" and len(vals) == 2:
        parser.values.auth = "AuthenticationType=DIRECTORY_SERVICE;" \
                             "DirSvcPropertyName=" + vals[1]
    else:
        raise OptionValueError("Invalid auth option '%s'" % value)


def parseCmdLine():
    parser = OptionParser(description="Market data contribution.")
    parser.add_option("-a",
                      "--ip",
                      dest="hosts",
                      help="server name or IP (default: localhost)",
                      metavar="ipAddress",
                      action="append",
                      default=[])
    parser.add_option("-p",
                      dest="port",
                      type="int",
                      help="server port (default: %default)",
                      metavar="tcpPort",
                      default=8194)
    parser.add_option("-s",
                      dest="service",
                      help="service name (default: %default)",
                      metavar="service",
                      default="//blp/mpfbapi")
    parser.add_option("-t",
                      dest="topic",
                      help="topic (default: %default)",
                      metavar="topic",
                      default="/ticker/AUDEUR Curncy")
    parser.add_option("--auth",
                      dest="auth",
                      help="authentication option: "
                           "user|none|app=<app>|userapp=<app>|dir=<property>"
                           " (default: %default)",
                      metavar="option",
                      action="callback",
                      callback=authOptionCallback,
                      type="string",
                      default="user")

    (options, args) = parser.parse_args()

    if not options.hosts:
        options.hosts = ["localhost"]

    return options


def authorize(authService, identity, session, cid):
    with g_mutex:
        g_authorizationStatus[cid] = AuthorizationStatus.WAITING

    tokenEventQueue = blpapi.EventQueue()

    # Generate token
    session.generateToken(eventQueue=tokenEventQueue)

    # Process related response
    ev = tokenEventQueue.nextEvent()
    token = None
    if ev.eventType() == blpapi.Event.TOKEN_STATUS or \
                    ev.eventType() == blpapi.Event.REQUEST_STATUS:
        for msg in ev:
            print msg
            if msg.messageType() == TOKEN_SUCCESS:
                token = msg.getElementAsString(TOKEN)
            elif msg.messageType() == TOKEN_FAILURE:
                break
    if not token:
        print "Failed to get token"
        return False

    # Create and fill the authorithation request
    authRequest = authService.createAuthorizationRequest()
    authRequest.set(TOKEN, token)

    # Send authorithation request to "fill" the Identity
    session.sendAuthorizationRequest(authRequest, identity, cid)

    # Process related responses
    startTime = datetime.datetime.today()
    WAIT_TIME_SECONDS = datetime.timedelta(seconds=10)
    while True:
        with g_mutex:
            if AuthorizationStatus.WAITING != g_authorizationStatus[cid]:
                return AuthorizationStatus.AUTHORIZED == \
                       g_authorizationStatus[cid]

        endTime = datetime.datetime.today()
        if endTime - startTime > WAIT_TIME_SECONDS:
            return False

        time.sleep(1)


def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    for idx, host in enumerate(options.hosts):
        sessionOptions.setServerAddress(host, options.port, idx)
    sessionOptions.setAuthenticationOptions(options.auth)
    sessionOptions.setAutoRestartOnDisconnection(True)
    sessionOptions.setNumStartAttempts(len(options.hosts))

    myEventHandler = MyEventHandler()

    # Create a Session
    session = blpapi.ProviderSession(sessionOptions,
                                     myEventHandler.processEvent)

    # Start a Session
    if not session.start():
        print "Failed to start session."
        return

    providerIdentity = session.createIdentity()

    if options.auth:
        isAuthorized = False
        authServiceName = "//blp/apiauth"
        if session.openService(authServiceName):
            authService = session.getService(authServiceName)
            isAuthorized = authorize(
                authService, providerIdentity, session,
                blpapi.CorrelationId("auth"))
        if not isAuthorized:
            print "No authorization"
            return

    topicList = blpapi.TopicList()
    topicList.add(options.service + options.topic,
                  blpapi.CorrelationId(MyStream(options.topic)))

    # Create topics
    session.createTopics(topicList,
                         blpapi.ProviderSession.AUTO_REGISTER_SERVICES,
                         providerIdentity)
    # createTopics() is synchronous, topicList will be updated
    # with the results of topic creation (resolution will happen
    # under the covers)

    streams = []
    for i in xrange(topicList.size()):
        stream = topicList.correlationIdAt(i).value()
        status = topicList.statusAt(i)
        topicString = topicList.topicStringAt(i)

        if (status == blpapi.TopicList.CREATED):
            stream.topic = session.getTopic(topicList.messageAt(i))
            streams.append(stream)
        else:
            print "Stream '%s': topic not resolved, status = %d" % (
                stream.id, status)

    service = session.getService(options.service)

    try:
        # Now we will start publishing
        value = 1
        while streams and g_running:
            event = service.createPublishEvent()
            eventFormatter = blpapi.EventFormatter(event)

            for stream in streams:
                value += 1
                eventFormatter.appendMessage(MARKET_DATA, stream.topic)
                eventFormatter.setElement("BID", 0.5 * value)
                eventFormatter.setElement("ASK", value)

            for msg in event:
                print msg

            session.publish(event)
            time.sleep(10)
    finally:
        # Stop the session
        session.stop()

if __name__ == "__main__":
    print "ContributionsMktdataExample"
    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.
"""

异常:

ContributionsMktdataExample

23MAY2016_15:50:15.552 6836:4756 ERROR blpapi_platformtransporttcp.cpp:671 blpapi.session.transporttcp.{1}.<7.220.156.135:8194> Connection failed 

23MAY2016_15:50:15.552 6836:4756 WARN blpapi_platformcontroller.cpp:371 blpapi.session.platformcontroller.{1} Platform: 0 failed 1 consecutive connect attempts, stopped trying to reconnect. 

23MAY2016_15:50:15.552 6836:5612 ERROR blpapi_providersessionimpl.cpp:642 blpapi.providersession.{1} Failed to start provider session: rc=9 
Failed to start session.

命令:

python main.py --ip=7.220.156.135 --auth=none

最佳答案

听起来您正在尝试使用 Desktop APIv3 从运行终端的机器上获取数据到您的机器。这不受支持。如果您使用的是 Desktop API,则只能连接到 localhost。您可以连接到另一台机器以获取彭博数据的唯一情况是使用服务器 API 或 B-PIPE。

即使支持这一点,桌面 API 契约(Contract)也规定您不能将彭博数据发送到另一台计算机。

关于python - 如何使用 python sdk 连接 bloomberg 终端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37389321/

相关文章:

python - python中的模板

python - 在 Python 中使用字符串格式打印元组

c++ - 直接或通过构造函数初始化具有相同类型的类

python - 使用 Bloomberg 函数从循环创建 DataFrame

Python 在 CSV 中搜索一列中的字符串,从同一行中的另一列返回字符串

python - matplotlib imshow - 默认颜色归一化

c++ - 编写程序将指令输出到 Windows 命令行

c++ - Windows 中 MSYS 与 MinGW 的需求是什么

R:从 Bloomberg 中提取多个出价

vba - 在 vba 中使用 Bloomberg API