Python: Bloomberg API 未获得授权
Python: Bloomberg API is not authorized
我正在尝试使用 Python API 从 Bloomberg 提取数据。 API 软件包附带示例代码,只需要本地主机即可完美运行的程序。但是使用其他授权方式的程序总是卡在错误:
Connecting to port 8194 on localhost
TokenGenerationFailure = {
reason = {
source = "apitkns (apiauth) on ebbdbp-ob-053"
category = "NO_AUTH"
errorCode = 12
description = "User not in emrs userid=NA\mds firm=22691"
subcategory = "INVALID_USER"
}
}
Failed to get token
No authorization
我看到另外一个人遇到了类似的问题,但他没有解决问题,而是选择使用本地主机。我不能总是使用 localhost,因为我将不得不协助其他用户并进行故障排除。所以我需要提示如何克服这个错误。
我的问题是如何设置除 OS_LOGON
之外的用户 ID,它会自动使用我帐户的登录凭据,以便我可以在需要时使用其他用户的名称?我尝试用用户名更改 OS_LOGON
但没有成功。
我正在尝试 运行 的完整程序是:
"""SnapshotRequestTemplateExample.py"""
from __future__ import print_function
from __future__ import absolute_import
import datetime
from optparse import OptionParser, OptionValueError
import blpapi
TOKEN_SUCCESS = blpapi.Name("TokenGenerationSuccess")
TOKEN_FAILURE = blpapi.Name("TokenGenerationFailure")
AUTHORIZATION_SUCCESS = blpapi.Name("AuthorizationSuccess")
TOKEN = blpapi.Name("token")
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():
"""parse cli arguments"""
parser = OptionParser(description="Retrieve realtime data.")
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("--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")
(opts, _) = parser.parse_args()
if not opts.hosts:
opts.hosts = ["localhost"]
if not opts.topics:
opts.topics = ["/ticker/IBM US Equity"]
return opts
def authorize(authService, identity, session, cid):
"""authorize the session for identity via authService"""
tokenEventQueue = blpapi.EventQueue()
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 authorization request
authRequest = authService.createAuthorizationRequest()
authRequest.set(TOKEN, token)
# Send authorization request to "fill" the Identity
session.sendAuthorizationRequest(authRequest, identity, cid)
# Process related responses
startTime = datetime.datetime.today()
WAIT_TIME_SECONDS = 10
while True:
event = session.nextEvent(WAIT_TIME_SECONDS * 1000)
if event.eventType() == blpapi.Event.RESPONSE or \
event.eventType() == blpapi.Event.REQUEST_STATUS or \
event.eventType() == blpapi.Event.PARTIAL_RESPONSE:
for msg in event:
print(msg)
if msg.messageType() == AUTHORIZATION_SUCCESS:
return True
print("Authorization failed")
return False
endTime = datetime.datetime.today()
if endTime - startTime > datetime.timedelta(seconds=WAIT_TIME_SECONDS):
return False
def main():
"""main entry point"""
global options
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)
print("Connecting to port %d on %s" % (
options.port, ", ".join(options.hosts)))
session = blpapi.Session(sessionOptions)
if not session.start():
print("Failed to start session.")
return
subscriptionIdentity = None
if options.auth:
subscriptionIdentity = session.createIdentity()
isAuthorized = False
authServiceName = "//blp/apiauth"
if session.openService(authServiceName):
authService = session.getService(authServiceName)
isAuthorized = authorize(authService, subscriptionIdentity,
session, blpapi.CorrelationId("auth"))
if not isAuthorized:
print("No authorization")
return
else:
print("Not using authorization")
.
.
.
.
.
finally:
session.stop()
if __name__ == "__main__":
print("SnapshotRequestTemplateExample")
try:
main()
except KeyboardInterrupt:
print("Ctrl+C pressed. Stopping...")
此示例适用于 Bloomberg 的 BPIPE 产品,因此包含必要的授权代码。对于此示例,如果您要连接到桌面 API(通常为 localhost:8194),您可能希望传递“none”的身份验证参数。请注意,此示例适用于 Desktop API.
不支持的 mktdata 快照功能
您声明您正在尝试代表其他用户进行故障排除,这些用户可能是根据其凭据使用 BPIPE 的交易员。在这种情况下,您需要创建一个 Identity 对象来表示该用户。
这样做会是这样的:
# Create and fill the authorization request
authRequest = authService.createAuthorizationRequest()
authRequest.set("authId", STRING_CONTAINING_USERS_EMRS_LOGON)
authRequest.set("ipAddress", STRING_OF_IP_ADDRESS_WHERE_USER_IS_LOGGED_INTO_TERMINAL)
# Send authorization request to "fill" the Identity
session.sendAuthorizationRequest(authRequest, identity, cid)
使用此方法时请注意潜在的许可合规性问题,因为这可能会产生严重后果。如有任何疑问,请联系贵公司的市场数据团队,他们可以询问他们的彭博联系人。
编辑:
正如评论中所问,详细说明 AuthorizationRequest 的其他可能参数很有用。
"uuid" + "ipAddress";这将是验证服务器 API 用户的默认方法。在 BPIPE 上,这需要 Bloomberg 明确为您启用它。 UUID 是分配给每个 Bloomberg Anywhere 用户的唯一整数标识符。您可以通过 运行 IAM
在终端中查找
"emrsId" + "ipAddress"; “emrsId”是“authId”的已弃用别名。这不应该再使用了。
"authId" + "ipAddress"; “authId”是 EMRS(BPIPE 权利管理和报告系统)或 SAPE(服务器 API 的 EMRS 等价物)中定义的字符串,代表每个用户。这通常是该用户的 OS 登录详细信息(例如 DOMAIN/USERID)或 Active Directory 属性(例如邮件 -> blah@blah.blah)
"authId" + "ipAddress" + "application"; “application”是在 EMRS/SAPE 上定义的应用程序名称。这将检查是否为 EMRS 上的指定应用程序启用了 authId 中定义的用户。在请求中使用这些用户+应用程序样式身份对象之一应该在 EMRS 使用报告中记录针对用户和应用程序的使用情况。
“令牌”;这是首选方法。使用 session.generateToken 功能(可以在原始问题的代码片段中看到)将生成一个字母数字字符串。您会将其作为唯一参数传递到授权请求中。请注意,令牌生成系统是 virtualization-aware;如果它在 Citrix 或远程桌面中检测到它是 运行,它将报告显示计算机的 IP 地址(或指向用户实际位置的一跳)。
我正在尝试使用 Python API 从 Bloomberg 提取数据。 API 软件包附带示例代码,只需要本地主机即可完美运行的程序。但是使用其他授权方式的程序总是卡在错误:
Connecting to port 8194 on localhost
TokenGenerationFailure = {
reason = {
source = "apitkns (apiauth) on ebbdbp-ob-053"
category = "NO_AUTH"
errorCode = 12
description = "User not in emrs userid=NA\mds firm=22691"
subcategory = "INVALID_USER"
}
}
Failed to get token
No authorization
我看到另外一个人遇到了类似的问题,但他没有解决问题,而是选择使用本地主机。我不能总是使用 localhost,因为我将不得不协助其他用户并进行故障排除。所以我需要提示如何克服这个错误。
我的问题是如何设置除 OS_LOGON
之外的用户 ID,它会自动使用我帐户的登录凭据,以便我可以在需要时使用其他用户的名称?我尝试用用户名更改 OS_LOGON
但没有成功。
我正在尝试 运行 的完整程序是:
"""SnapshotRequestTemplateExample.py"""
from __future__ import print_function
from __future__ import absolute_import
import datetime
from optparse import OptionParser, OptionValueError
import blpapi
TOKEN_SUCCESS = blpapi.Name("TokenGenerationSuccess")
TOKEN_FAILURE = blpapi.Name("TokenGenerationFailure")
AUTHORIZATION_SUCCESS = blpapi.Name("AuthorizationSuccess")
TOKEN = blpapi.Name("token")
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():
"""parse cli arguments"""
parser = OptionParser(description="Retrieve realtime data.")
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("--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")
(opts, _) = parser.parse_args()
if not opts.hosts:
opts.hosts = ["localhost"]
if not opts.topics:
opts.topics = ["/ticker/IBM US Equity"]
return opts
def authorize(authService, identity, session, cid):
"""authorize the session for identity via authService"""
tokenEventQueue = blpapi.EventQueue()
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 authorization request
authRequest = authService.createAuthorizationRequest()
authRequest.set(TOKEN, token)
# Send authorization request to "fill" the Identity
session.sendAuthorizationRequest(authRequest, identity, cid)
# Process related responses
startTime = datetime.datetime.today()
WAIT_TIME_SECONDS = 10
while True:
event = session.nextEvent(WAIT_TIME_SECONDS * 1000)
if event.eventType() == blpapi.Event.RESPONSE or \
event.eventType() == blpapi.Event.REQUEST_STATUS or \
event.eventType() == blpapi.Event.PARTIAL_RESPONSE:
for msg in event:
print(msg)
if msg.messageType() == AUTHORIZATION_SUCCESS:
return True
print("Authorization failed")
return False
endTime = datetime.datetime.today()
if endTime - startTime > datetime.timedelta(seconds=WAIT_TIME_SECONDS):
return False
def main():
"""main entry point"""
global options
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)
print("Connecting to port %d on %s" % (
options.port, ", ".join(options.hosts)))
session = blpapi.Session(sessionOptions)
if not session.start():
print("Failed to start session.")
return
subscriptionIdentity = None
if options.auth:
subscriptionIdentity = session.createIdentity()
isAuthorized = False
authServiceName = "//blp/apiauth"
if session.openService(authServiceName):
authService = session.getService(authServiceName)
isAuthorized = authorize(authService, subscriptionIdentity,
session, blpapi.CorrelationId("auth"))
if not isAuthorized:
print("No authorization")
return
else:
print("Not using authorization")
.
.
.
.
.
finally:
session.stop()
if __name__ == "__main__":
print("SnapshotRequestTemplateExample")
try:
main()
except KeyboardInterrupt:
print("Ctrl+C pressed. Stopping...")
此示例适用于 Bloomberg 的 BPIPE 产品,因此包含必要的授权代码。对于此示例,如果您要连接到桌面 API(通常为 localhost:8194),您可能希望传递“none”的身份验证参数。请注意,此示例适用于 Desktop API.
不支持的 mktdata 快照功能您声明您正在尝试代表其他用户进行故障排除,这些用户可能是根据其凭据使用 BPIPE 的交易员。在这种情况下,您需要创建一个 Identity 对象来表示该用户。
这样做会是这样的:
# Create and fill the authorization request
authRequest = authService.createAuthorizationRequest()
authRequest.set("authId", STRING_CONTAINING_USERS_EMRS_LOGON)
authRequest.set("ipAddress", STRING_OF_IP_ADDRESS_WHERE_USER_IS_LOGGED_INTO_TERMINAL)
# Send authorization request to "fill" the Identity
session.sendAuthorizationRequest(authRequest, identity, cid)
使用此方法时请注意潜在的许可合规性问题,因为这可能会产生严重后果。如有任何疑问,请联系贵公司的市场数据团队,他们可以询问他们的彭博联系人。
编辑: 正如评论中所问,详细说明 AuthorizationRequest 的其他可能参数很有用。
"uuid" + "ipAddress";这将是验证服务器 API 用户的默认方法。在 BPIPE 上,这需要 Bloomberg 明确为您启用它。 UUID 是分配给每个 Bloomberg Anywhere 用户的唯一整数标识符。您可以通过 运行 IAM
在终端中查找"emrsId" + "ipAddress"; “emrsId”是“authId”的已弃用别名。这不应该再使用了。
"authId" + "ipAddress"; “authId”是 EMRS(BPIPE 权利管理和报告系统)或 SAPE(服务器 API 的 EMRS 等价物)中定义的字符串,代表每个用户。这通常是该用户的 OS 登录详细信息(例如 DOMAIN/USERID)或 Active Directory 属性(例如邮件 -> blah@blah.blah)
"authId" + "ipAddress" + "application"; “application”是在 EMRS/SAPE 上定义的应用程序名称。这将检查是否为 EMRS 上的指定应用程序启用了 authId 中定义的用户。在请求中使用这些用户+应用程序样式身份对象之一应该在 EMRS 使用报告中记录针对用户和应用程序的使用情况。
“令牌”;这是首选方法。使用 session.generateToken 功能(可以在原始问题的代码片段中看到)将生成一个字母数字字符串。您会将其作为唯一参数传递到授权请求中。请注意,令牌生成系统是 virtualization-aware;如果它在 Citrix 或远程桌面中检测到它是 运行,它将报告显示计算机的 IP 地址(或指向用户实际位置的一跳)。