如何订阅Bloomberg API?Python启动及订阅报错求助
Fixing the Bloomberg API Port Error & Implementing Subscriptions
First: Resolve the Server Port Error
The error you’re seeing (argument 2 of type 'unsigned short') happens because setServerPort expects an integer (unsigned short) instead of a string. Here’s how to fix your initial code:
Correct Session Setup Code
import blpapi # Configure session options options = blpapi.SessionOptions() # Use 'localhost' if you're running alongside the Bloomberg Terminal on your machine options.setServerHost("localhost") # Default port for Bloomberg Desktop API is 8194 (use this unless your admin specified a different one) options.setServerPort(8194) # Initialize and start the session session = blpapi.Session(options) if not session.start(): print("Failed to start Bloomberg session. Check if Terminal is running and host/port are correct.") exit() print("Session started successfully!")
Key notes:
- Port: Always use an integer (8194 is the standard for Desktop API). Never pass a string here.
- Host: If you’re using the Bloomberg Terminal locally,
localhostworks. If connecting to a remote Bloomberg server, use the server’s hostname provided by your admin. - Session Start Check: Always verify if
session.start()returnsTrue—this catches issues like the Terminal not being open or incorrect credentials.
Second: Implementing Bloomberg API Subscriptions
Subscribing to real-time market data involves a few key steps: opening the market data service, creating a subscription list, and processing incoming events. Here’s a complete, working example:
Full Subscription Code
import blpapi def main(): # Step 1: Set up and start session (same as fixed code above) options = blpapi.SessionOptions() options.setServerHost("localhost") options.setServerPort(8194) session = blpapi.Session(options) if not session.start(): print("Session failed to start.") return try: # Step 2: Open the market data service MARKET_DATA_SERVICE = "//blp/mktdata" if not session.openService(MARKET_DATA_SERVICE): print(f"Failed to open {MARKET_DATA_SERVICE} service.") return service = session.getService(MARKET_DATA_SERVICE) # Step 3: Create subscription list subscription_list = blpapi.SubscriptionList() # Define securities and fields to subscribe to securities = ["AAPL US Equity", "MSFT US Equity", "TSLA US Equity"] fields = ["LAST_PRICE", "BID", "ASK", "VOLUME"] # Add each security to the subscription list for security in securities: # Use CorrelationId to link incoming messages to the security subscription_list.add( security, fields, "", # No additional subscription options (leave empty for default) blpapi.CorrelationId(security) ) # Step 4: Subscribe to the data session.subscribe(subscription_list) print(f"Subscribed to: {', '.join(securities)}") print("Waiting for real-time data... (Press Ctrl+C to stop)") # Step 5: Process incoming events while True: # Wait for next event (timeout after 500ms to keep loop responsive) event = session.nextEvent(500) for msg in event: # Handle real-time data messages if event.eventType() == blpapi.Event.SUBSCRIPTION_DATA: security = msg.correlationId().value() print(f"\n--- {security} ---") # Extract each requested field for field in fields: if msg.hasElement(field): value = msg.getElement(field).getValueAsString() print(f"{field}: {value}") # Handle subscription status updates (e.g., errors, confirmations) elif event.eventType() == blpapi.Event.SUBSCRIPTION_STATUS: status = msg.getElement("subscriptionStatus").getValueAsString() security = msg.correlationId().value() print(f"\nSubscription Status for {security}: {status}") # Exit if we get a termination event if event.eventType() == blpapi.Event.TERMINATION: break except KeyboardInterrupt: print("\nStopping subscription...") finally: # Clean up: stop the session session.stop() print("Session stopped.") if __name__ == "__main__": main()
Key Subscription Concepts
- Market Data Service: The
//blp/mktdataservice is used for real-time market data subscriptions. - Correlation ID: Links incoming messages to the specific security you subscribed to—critical when monitoring multiple securities.
- Event Processing: The loop continuously fetches events, which can be data updates, status messages, or termination signals.
- Field Names: Use Bloomberg’s field codes (e.g.,
LAST_PRICE,BID). You can look up valid fields using theFLDScommand in the Bloomberg Terminal.
Prerequisites to Remember
- Bloomberg Terminal: If using the Desktop API, ensure the Bloomberg Terminal is running on your machine (or connected via a remote desktop).
- blpapi Installation: Make sure you have the correct version of
blpapiinstalled (match the version of your Bloomberg Terminal). Install via:pip install blpapi - Permissions: Ensure your Bloomberg account has access to the securities and fields you’re trying to subscribe to.
内容的提问来源于stack exchange,提问作者Hannah Lee
相关产品推荐
相关产品推荐

