blpapi.Session
- class blpapi.Session(options=None, eventHandler=None, eventDispatcher=None)
Bases:
AbstractSessionConsumer session for making requests for Bloomberg services.
This class provides a consumer session for making requests for Bloomberg services. For information on generic session operations, see the parent class:
AbstractSession.Sessions manage access to services either by requests and responses or subscriptions. A Session can dispatch events and replies in either a synchronous or asynchronous mode. The mode of a Session is determined when it is constructed and cannot be changed subsequently.
A Session is asynchronous if an
eventHandlerargument is supplied when it is constructed. ThenextEvent()method may not be called. All incoming events are delivered to theeventHandlersupplied on construction.If supplied,
eventHandlermust be a callable object that takes two arguments: receivedEventand related session.A Session is synchronous if an
eventHandlerargument is not supplied when it is constructed. ThenextEvent()method must be called to read incoming events.Several methods in Session take a
CorrelationIdparameter. The application may choose to supply its ownCorrelationIdvalues or allow the Session to create values. If the application supplies its ownCorrelationIdvalues it must manage their lifetime such that the same value is not reused for more than one operation at a time. The lifetime of aCorrelationIdbegins when it is supplied in a method invoked on a Session and ends either when it is explicitly cancelled usingcancel()orunsubscribe(), when aRESPONSEEvent(not aPARTIAL_RESPONSE) containing it is received or when aSUBSCRIPTION_STATUSEventwhich indicates that the subscription it refers to has been terminated is received.When using an asynchronous Session, the application must be aware that because the callbacks are generated from another thread, they may be processed before the call which generates them has returned. For example, the
SESSION_STATUSEventgenerated by astartAsync()may be processed beforestartAsync()has returned (even thoughstartAsync()itself will not block).This becomes more significant when Session generated
CorrelationIds are in use. For example, if a call tosubscribe()which returns a Session generatedCorrelationIdhas not completed before the firstEvents which contain thatCorrelationIdarrive the application may not be able to interpret those events correctly. For this reason, it is preferable to use user generatedCorrelationIds when using asynchronous Sessions. This issue does not arise when using a synchronous Session as long as the calls tosubscribe()etc. are made on the same thread as the calls tonextEvent().Events of a synchronous Session can be consumed using for event in session statement. Note, this is not possible with an asynchronous Session (an exception is raised). The user must not mix calls to session.nextEvent and for event in session iteration.
A synchronous Session supports async compatible usage. The Session exposes an awaitable function awaitEvent, which returns the next event without blocking, and the possibility to iterate asynchronously over the Session, using the syntax async for event in session. This enables iteration over the generated Events without blocking. The user must not mix calls to session.nextEvent and async for event in session iteration.
The class attributes represent the states in which a subscription can be.
- CANCELLED = 3
No longer active, terminated by Application.
- PENDING_CANCELLATION = 4
No longer active, terminated by Application.
- SUBSCRIBED = 2
Updates are flowing.
- SUBSCRIBING = 1
Initiated but no updates received.
- UNSUBSCRIBED = 0
No longer active, terminated by API.
- __init__(options=None, eventHandler=None, eventDispatcher=None)
Create a consumer
Session.- Parameters:
options – Options to construct the session with
eventHandler – Handler for events generated by the session. Takes two arguments - received event and related session
eventDispatcher – An optional dispatcher for events.
- Raises:
InvalidArgumentException – If
eventHandlerisNoneand and theeventDispatcheris notNone
If
eventHandleris notNonethen thisSessionwill operate in asynchronous mode, otherwise theSessionwill operate in synchronous mode.If
eventDispatcherisNonethen theSessionwill create a defaultEventDispatcherfor thisSessionwhich will use a single thread for dispatching events. For more control over event dispatching a specific instance ofEventDispatchercan be supplied. This can be used to share a singleEventDispatcheramongst multipleSessionobjects.If an
eventDispatcheris supplied which uses more than one thread theSessionwill ensure that events which should be ordered are passed to callbacks in a correct order. For example, partial response to a request or updates to a single subscription.Each
eventDispatcheruses it’s own thread or pool of threads so if you want to ensure that a session which receives very large messages and takes a long time to process them does not delay a session that receives small messages and processes each one very quickly then give each one a separateeventDispatcher.Note
In case of unhandled exception in
eventHandler, the exception traceback will be printed tosys.stderrand application will be terminated with nonzero exit code.
- async awaitEvent()
- Returns:
Next available event for this session
- Return type:
- Raises:
InvalidStateException – If invoked on a session created in asynchronous mode
Await until there is not an event or the session is closed. This method does not block. If the
Sessionis async, then it raises the same error, as synchronous nextEvent()
- cancel(correlationId)
Cancel request(s) with a single
correlationIdor a list.- Parameters:
correlationId (
Union[CorrelationId,Sequence[CorrelationId],None]) – Correlation id(s) associated with the request(s) to cancel
For all specified
correlationIdvalues that identify an ongoing request cancel that request.Once this call returns the specified
correlationIdwill not be seen in any subsequentMessageobtained from aMessageIteratorby callingnext(). However, anyMessagecurrently pointed to by aMessageIteratorwhencancel()is called is not affected even if it has the specifiedcorrelationId. Also anyMessagewhere a reference has been retained by the application may still contain thecorrelationId. For these reasons, although technically an application is free to re-usecorrelationIdas soon as this method returns it is preferable not to aggressively re-use correlation IDs, particularly with an asynchronous Session.- Return type:
- createIdentity()
Create an
Identitywhich is valid but has not been authorized.- Returns:
Identity which is valid but has not been authorized
- Return type:
- createSnapshotRequestTemplate(subscriptionString, correlationId, identity=None)
Create a snapshot request template for getting subscription data specified by the
subscriptionStringusing the specifiedidentity.- Parameters:
subscriptionString – String that specifies the subscription
correlationId – Correlation id to associate with events generated by this operation
identity – Optional. Identity used for authorization.
- Returns:
Created request template
- Return type:
- Raises:
Exception – If one or more of the following conditions is not met: the session is established,
subscriptionStringis a valid subscription string andcorrelationIdis not used in this session.
The provided
correlationIdwill be used for status updates about the created request template state and an implied subscription associated with it delivered bySUBSCRIPTION_STATUSevents.The benefit of the snapshot request templates is that these requests may be serviced from a cache and the user may expect to see significantly lower response time.
There are 3 possible states for a created request template:
Pending,Available, andTerminated. Right after creation a request template is in thePendingstate.If a state is
Pending, the user may send a request using this template but there are no guarantees about response time since cache is not available yet. Request template may transition intoPendingstate only from theAvailablestate. In this case theRequestTemplatePendingmessage is generated.If state is
Available, all requests will be serviced from a cache and the user may expect to see significantly reduced latency. Note, that a snapshot request template can transition out of theAvailablestate concurrently with requests being sent, so no guarantee of service from the cache can be provided. Request template may transition intoAvailablestate only from thePendingstate. In this case theRequestTemplateAvailablemessage is generated. This message will also contain information about currently used connection in theboundTofield. Note that it is possible to get theRequestTemplateAvailablemessage with a new connection information, even if a request template is already in theAvailablestate.If state is
Terminated, sending request will always result in a failure response. Request template may transition into this state from any other state. This is a final state and it is guaranteed that the last message associated with the providedcorrelationIdwill be theRequestTemplateTerminatedmessage which is generated when a request template transitions into this state. If a request template transitions into this state, all outstanding requests will be failed and appropriate messages will be generated for each request. After receiving theRequestTemplateTerminatedmessage,correlationIdmay be reused.Note that resources used by a snapshot request template are released only when request template transitions into the
Terminatedstate or when session is destroyed. In order to release resources when request template is not needed anymore, user should call thecancel()method unless theRequestTemplateTerminatedmessage was already received due to some problems. When the last copy of aRequestTemplateobject goes out of scope and there are no outstanding requests left, the snapshot request template will be destroyed automatically. If the last copy of aRequestTemplateobject goes out of scope while there are still some outstanding requests left, snapshot service request template will be destroyed automatically when the last request gets a final response.When
identityisNone, the session identity will be used if it has been authorized.
- generateAuthorizedIdentity(authOptions, correlationId=None)
Generates an authorized
Identitywith the specifiedauthOptionsandcorrelationId.- Parameters:
- Returns:
Identifies the aforementioned events and the generated
Identity.- Return type:
If this is an asynchronous session then an
Eventmay be delivered to the registeredEventHandlerbeforegenerateAuthorizedIdentity()has returned.One or more
Event.AUTHORIZATION_STATUSevents, zero or moreEvent.TOKEN_STATUSevents, and zero or moreEvent.SERVICE_STATUSevents are generated.The behavior is undefined if either
authOptionsorcorrelationIdisNone.
- generateToken(correlationId=None, eventQueue=None, authId=None, ipAddress=None)
Generate a token to be used for authorization.
- Parameters:
correlationId – Correlation id to be associated with the request
eventQueue – Event queue on which to receive Events related to this request
authId – The id used for authentication
ipAddress – IP of the machine used for authentication
- Returns:
The correlation id used to identify the Events generated as a result of this call
- Return type:
- Raises:
InvalidArgumentException – If the authentication options in
SessionOptionsor the arguments to the function are invalid.
The
authIdandipAddressmust be provided together and can only be provided if the authentication mode isMANUAL.
- getAuthorizedIdentity(correlationId=None)
Returns the authorized
Identityassociated withcorrelationId. IfcorrelationIdis not given, returns the session identity.- Parameters:
correlationId (
Optional[CorrelationId]) – Optional. Associated with anIdentity.- Returns:
the
Identityassociated withcorrelationId.- Return type:
- Raises:
NotFoundException – If there is no
Identityassociated withcorrelationId, if the associatedIdentityis not authorized, or ifcorrelationIdis not given and the session identity is not authorized.
- getService(serviceName)
Return a
Serviceobject representing the service.- Parameters:
serviceName (
str) – Name of the service to retrieve- Returns:
Service identified by the service name
- Return type:
- Raises:
InvalidStateException – If the service identified by the specified
serviceNameis not open already
The
serviceNamemust contain a fully qualified service name. That is, it must be of the form//<namespace>/<service-name>.
- nextEvent(timeout=0)
- Parameters:
timeout (
int) – Timeout threshold in milliseconds- Returns:
Next available event for this session
- Return type:
- Raises:
InvalidStateException – If invoked on a session created in asynchronous mode
If there is no
Eventavailable this will block for up to the specifiedtimeoutmilliseconds for anEventto arrive. A value of0fortimeout(the default) indicatesnextEvent()should not timeout and will not return until the nextEventis available.If
nextEvent()returns due to a timeout it will return an event of typeTIMEOUT.
- openService(serviceName)
Open the service identified by the specified
serviceName.- Parameters:
serviceName (
str) – Name of the service- Return type:
- Returns:
Trueif the service is opened successfully,Falseotherwise.
Attempt to open the service identified by the specified
serviceNameand block until the service is either opened successfully or has failed to be opened. ReturnTrueif the service is opened successfully andFalseif the service cannot be successfully opened.The
serviceNamemust contain a fully qualified service name. That is, it must be of the form//<namespace>/<service-name>.Before
openService()returns aSERVICE_STATUSEventis generated. If this is an asynchronous Session then thisEventmay be processed by the registeredeventHandlerbeforeopenService()has returned.
- openServiceAsync(serviceName, correlationId=None)
Begin the process to open the service and return immediately.
- Parameters:
serviceName (
str) – Name of the servicecorrelationId (
Optional[CorrelationId]) – Correlation id to associate with events generated as a result of this call
- Returns:
The correlation id used to identify the Events generated as a result of this call
- Return type:
Begin the process to open the service identified by the specified
serviceNameand return immediately. The optional specifiedcorrelationIdis used to trackEvents generated as a result of this call.The
serviceNamemust contain a fully qualified service name. That is, it must be of the form//<namespace>/<service-name>.The application must monitor events for a
SERVICE_STATUSEventwhich will be generated once the service has been successfully opened or the opening has failed.
- resubscribe(subscriptionList, requestLabel=None, resubscriptionId=None, mode=SubscriptionPreprocessMode.FAIL_ON_FIRST_ERROR)
Modify subscriptions in
subscriptionList.- Parameters:
subscriptionList – List of subscriptions to modify
requestLabel – String which will be recorded along with any diagnostics for this operation
resubscriptionId – An id that will be included in the event generated from this operation
mode – Mode to use for this operation. See
SubscriptionPreprocessModefor an explanation of the available modes.
- Returns:
- If mode is
FAIL_ON_FIRST_ERROR, then
Noneis returned. If mode isRETURN_INDIVIDUAL_ERRORS, then a list ofSubscriptionPreprocessErroris returned.
- If mode is
Modify each subscription in the specified
subscriptionList, which must be an object of typeSubscriptionList, to reflect the modified options specified for it. If the optionalrequestLabelis provided it defines a string which will be recorded along with any diagnostics for this operation.For each entry in the
subscriptionListwhich has a correlation ID which identifies a current subscription the modified options replace the current options for the subscription and aSUBSCRIPTION_STATUSEvent(containing theresubscriptionIdif specified) will be generated in the event stream before the first update based on the new options. If the correlation ID of an entry in thesubscriptionListdoes not identify a current subscription then that entry is ignored.
- sendAuthorizationRequest(request, identity, correlationId=None, eventQueue=None)
Send the specified
authorizationRequest.- Parameters:
request – Authorization request to send
identity – Identity to update with the results
correlationId – Correlation id to associate with the request
eventQueue – Event queue on which the events related to this request will arrive
- Returns:
The correlation id used to identify the Events generated as a result of this call
- Return type:
Send the specified
authorizationRequestand update the specifiedidentitywith the results. If the optionally specifiedcorrelationIdis supplied, it is used; otherwise create aCorrelationId. The actualCorrelationIdused is returned. If the optionally specifiedeventQueueis supplied allEvents relating to thisRequestwill arrive on thatEventQueue.The underlying user information must remain valid until the Request has completed successfully or failed.
A successful request will generate zero or more
PARTIAL_RESPONSEMessages followed by exactly oneRESPONSEMessage. Once the finalRESPONSEMessagehas been received the specifiedidentitywill have been updated to contain the users entitlement information and theCorrelationIdassociated with the request may be re-used. If the request fails at any stage aREQUEST_STATUSwill be generated, the specifiedidentitywill not be modified and theCorrelationIdmay be re-used.The
identitysupplied must have been returned from this Session’screateIdentity()method and must not be the session identity.
- sendRequest(request, identity=None, correlationId=None, eventQueue=None, requestLabel=None)
Send the specified
request.- Parameters:
request – Request to send
identity – Identity used for authorization
correlationId – Correlation id to associate with the request
eventQueue – Event queue on which the events related to this operation will arrive
requestLabel – String which will be recorded along with any diagnostics for this operation
- Returns:
The actual correlation id associated with the request
- Return type:
Send the specified
requestusing the optionally specifiedidentityfor authorization. Ifidentityis not provided, then the request will be sent using the session identity. If the optionally specifiedcorrelationIdis supplied use it, otherwise create aCorrelationId. The actualCorrelationIdused is returned. If the optionally specifiedeventQueueis supplied all events relating to thisRequestwill arrive on thatEventQueue. If the optionalrequestLabelis provided it defines a string which will be recorded along with any diagnostics for this operation.A successful request will generate zero or more
PARTIAL_RESPONSEMessages followed by exactly oneRESPONSEMessage. Once the finalRESPONSEMessagehas been received theCorrelationIdassociated with this request may be re-used. If the request fails at any stage aREQUEST_STATUSwill be generated after which theCorrelationIdassociated with the request may be re-used.When
identityis not provided, the session identity will be used if it has been authorized.
- sendRequestTemplate(requestTemplate, correlationId=None)
Send a request defined by the specified
requestTemplate.- Parameters:
requestTemplate (
RequestTemplate) – Template that defines the requestcorrelationId (
Optional[CorrelationId]) – Correlation id to associate with the request
- Returns:
The actual correlation id used for the request is returned.
- Return type:
If the optionally specified
correlationIdis supplied, use it otherwise create a newCorrelationId. The actualCorrelationIdused is returned.A successful request will generate zero or more
PARTIAL_RESPONSEevents followed by exactly oneRESPONSEevent. Once the finalRESPONSEevent has been received theCorrelationIdassociated with this request may be re-used. If the request fails at any stage aREQUEST_STATUSwill be generated after which theCorrelationIdassociated with the request may be re-used.
- setStatusCorrelationId(service, correlationId, identity=None)
Set the Correlation id on which service status messages will be received.
- Parameters:
service – The service from which the status messages are received
correlationId – Correlation id to associate with the service status messages
identity – Identity used for authorization
Note
No service status messages are received prior to this call
- start()
Start this
Sessionin synchronous mode.Attempt to start this
Sessionand block until theSessionhas started or failed to start. Beforestart()returns aSESSION_STATUSEventis generated. ASessionmay only be started once.
- startAsync()
Start this
Sessionin asynchronous mode.- Return type:
- Returns:
Trueif the process to start aSessionbegan successfully,Falseotherwise.
Attempt to begin the process to start this
Session. The application must monitor events for aSESSION_STATUSEventwhich will be generated once theSessionhas started or if it fails to start. TheSESSION_STATUSEventmay be processed by the registeredeventHandlerbeforestartAsync()has returned. ASessionmay only be started once.
- stop()
Stop operation of this
Sessionand wait until it stops.Stop operation of this
Sessionand block until all callbacks toeventHandlerobjects relating to thisSessionwhich are currently in progress have completed (including the callback to handle theSESSION_STATUSEventthis call generates). Once this returns no further callbacks toeventHandlerswill occur. Ifstop()is called from within aneventHandlercallback it is silently converted to astopAsync()in order to prevent deadlock. Once aSessionhas been stopped it can only be destroyed.
- stopAsync()
Begin the process to stop this Session and return immediately.
- Return type:
- Returns:
Trueif the process to stop aSessionbegan successfully,Falseotherwise.
The application must monitor events for a
SESSION_STATUSEventwhich will be generated once theSessionhas been stopped. After thisSESSION_STATUSEventno further callbacks toeventHandlerswill occur. Once aSessionhas been stopped it can only be destroyed.
- subscribe(subscriptionList, identity=None, requestLabel=None, mode=SubscriptionPreprocessMode.FAIL_ON_FIRST_ERROR)
Begin subscriptions for each entry in the specified list.
- Parameters:
subscriptionList – List of subscriptions to begin
identity – Identity used for authorization
requestLabel – String which will be recorded along with any diagnostics for this operation
mode – Mode to use for this operation. See
SubscriptionPreprocessModefor an explanation of the available modes.
- Returns:
- If mode is
FAIL_ON_FIRST_ERROR, then
Noneis returned. If mode isRETURN_INDIVIDUAL_ERRORS, then a list ofSubscriptionPreprocessErroris returned.
- If mode is
Begin subscriptions for each entry in the specified
subscriptionList, which must be an object of typeSubscriptionList, optionally using the specifiedidentityfor authorization. If noidentityis specified, the default authorization information is used. If the optionalrequestLabelis provided it defines a string which will be recorded along with any diagnostics for this operation.A
SUBSCRIPTION_STATUSEventwill be generated for each entry in thesubscriptionList.When
identityis not provided, the session identity will be used if it has been authorized.
- tryNextEvent()
- Returns:
Next available event for this session
- Return type:
If there are
Events available for the session, return the nextEventIf there is no event available for theSession, returnNone. This method never blocks.
- unsubscribe(subscriptionList)
Cancel subscriptions from the specified
subscriptionList.- Parameters:
subscriptionList – List of subscriptions to cancel
Cancel each of the current subscriptions identified by the specified
subscriptionList, which must be an object of typeSubscriptionList. If the correlation ID of any entry in thesubscriptionListdoes not identify a current subscription then that entry is ignored. All entries which have valid correlation IDs will be cancelled.Once this call returns the correlation ids in the
subscriptionListwill not be seen in any subsequentMessageobtained from aMessageIteratorby callingnext()However, anyMessagecurrently pointed to by aMessageIteratorwhenunsubscribe()is called is not affected even if it has one of the correlation IDs in thesubscriptionList. Also anyMessagewhere a reference has been retained by the application may still contain a correlation ID from thesubscriptionList. For these reasons, although technically an application is free to re-use the correlation IDs as soon as this method returns it is preferable not to aggressively re-use correlation IDs, particularly with an asynchronousSession.