blpapi.Session

class blpapi.Session(options=None, eventHandler=None, eventDispatcher=None)

Bases: AbstractSession

Consumer 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 eventHandler argument is supplied when it is constructed. The nextEvent() method may not be called. All incoming events are delivered to the eventHandler supplied on construction.

If supplied, eventHandler must be a callable object that takes two arguments: received Event and related session.

A Session is synchronous if an eventHandler argument is not supplied when it is constructed. The nextEvent() method must be called to read incoming events.

Several methods in Session take a CorrelationId parameter. The application may choose to supply its own CorrelationId values or allow the Session to create values. If the application supplies its own CorrelationId values it must manage their lifetime such that the same value is not reused for more than one operation at a time. The lifetime of a CorrelationId begins when it is supplied in a method invoked on a Session and ends either when it is explicitly cancelled using cancel() or unsubscribe(), when a RESPONSE Event (not a PARTIAL_RESPONSE) containing it is received or when a SUBSCRIPTION_STATUS Event which 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_STATUS Event generated by a startAsync() may be processed before startAsync() has returned (even though startAsync() itself will not block).

This becomes more significant when Session generated CorrelationIds are in use. For example, if a call to subscribe() which returns a Session generated CorrelationId has not completed before the first Events which contain that CorrelationId arrive the application may not be able to interpret those events correctly. For this reason, it is preferable to use user generated CorrelationIds when using asynchronous Sessions. This issue does not arise when using a synchronous Session as long as the calls to subscribe() etc. are made on the same thread as the calls to nextEvent().

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 eventHandler is None and and the eventDispatcher is not None

If eventHandler is not None then this Session will operate in asynchronous mode, otherwise the Session will operate in synchronous mode.

If eventDispatcher is None then the Session will create a default EventDispatcher for this Session which will use a single thread for dispatching events. For more control over event dispatching a specific instance of EventDispatcher can be supplied. This can be used to share a single EventDispatcher amongst multiple Session objects.

If an eventDispatcher is supplied which uses more than one thread the Session will 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 eventDispatcher uses 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 separate eventDispatcher.

Note

In case of unhandled exception in eventHandler, the exception traceback will be printed to sys.stderr and application will be terminated with nonzero exit code.

cancel(correlationId)

Cancel request(s) with a single correlationId or a list.

Parameters:

correlationId (Union[CorrelationId, Sequence[CorrelationId], None]) – Correlation id(s) associated with the request(s) to cancel

For all specified correlationId values that identify an ongoing request cancel that request.

Once this call returns the specified correlationId will not be seen in any subsequent Message obtained from a MessageIterator by calling next(). However, any Message currently pointed to by a MessageIterator when cancel() is called is not affected even if it has the specified correlationId. Also any Message where a reference has been retained by the application may still contain the correlationId. For these reasons, although technically an application is free to re-use correlationId as soon as this method returns it is preferable not to aggressively re-use correlation IDs, particularly with an asynchronous Session.

Return type:

None

createIdentity()

Create an Identity which is valid but has not been authorized.

Returns:

Identity which is valid but has not been authorized

Return type:

Identity

createSnapshotRequestTemplate(subscriptionString, correlationId, identity=None)

Create a snapshot request template for getting subscription data specified by the subscriptionString using the specified identity.

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:

RequestTemplate

Raises:

Exception – If one or more of the following conditions is not met: the session is established, subscriptionString is a valid subscription string and correlationId is not used in this session.

The provided correlationId will be used for status updates about the created request template state and an implied subscription associated with it delivered by SUBSCRIPTION_STATUS events.

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, and Terminated. Right after creation a request template is in the Pending state.

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 into Pending state only from the Available state. In this case the RequestTemplatePending message 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 the Available state concurrently with requests being sent, so no guarantee of service from the cache can be provided. Request template may transition into Available state only from the Pending state. In this case the RequestTemplateAvailable message is generated. This message will also contain information about currently used connection in the boundTo field. Note that it is possible to get the RequestTemplateAvailable message with a new connection information, even if a request template is already in the Available state.

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 provided correlationId will be the RequestTemplateTerminated message 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 the RequestTemplateTerminated message, correlationId may be reused.

Note that resources used by a snapshot request template are released only when request template transitions into the Terminated state or when session is destroyed. In order to release resources when request template is not needed anymore, user should call the cancel() method unless the RequestTemplateTerminated message was already received due to some problems. When the last copy of a RequestTemplate object goes out of scope and there are no outstanding requests left, the snapshot request template will be destroyed automatically. If the last copy of a RequestTemplate object 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 identity is None, the session identity will be used if it has been authorized.

destroy()

Destroy the handle using stored dtor

Return type:

None

generateAuthorizedIdentity(authOptions, correlationId=None)

Generates an authorized Identity with the specified authOptions and correlationId.

Parameters:
  • authOptions – Used to generate the Identity.

  • correlationId – Optional. Will identify the messages associated with the generated Identity.

Returns:

Identifies the aforementioned events and the generated Identity.

Return type:

CorrelationId

If this is an asynchronous session then an Event may be delivered to the registered EventHandler before generateAuthorizedIdentity() has returned.

One or more Event.AUTHORIZATION_STATUS events, zero or more Event.TOKEN_STATUS events, and zero or more Event.SERVICE_STATUS events are generated.

The behavior is undefined if either authOptions or correlationId is None.

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:

CorrelationId

Raises:

InvalidArgumentException – If the authentication options in SessionOptions or the arguments to the function are invalid.

The authId and ipAddress must be provided together and can only be provided if the authentication mode is MANUAL.

getAuthorizedIdentity(correlationId=None)

Returns the authorized Identity associated with correlationId. If correlationId is not given, returns the session identity.

Parameters:

correlationId (Optional[CorrelationId]) – Optional. Associated with an Identity.

Returns:

the Identity associated with correlationId.

Return type:

Identity

Raises:

NotFoundException – If there is no Identity associated with correlationId, if the associated Identity is not authorized, or if correlationId is not given and the session identity is not authorized.

getService(serviceName)

Return a Service object representing the service.

Parameters:

serviceName (str) – Name of the service to retrieve

Returns:

Service identified by the service name

Return type:

Service

Raises:

InvalidStateException – If the service identified by the specified serviceName is not open already

The serviceName must contain a fully qualified service name. That is, it must be of the form //<namespace>/<service-name>.

isValid()

Returns: True if this class holds a handle and the handle is not None.

Return type:

bool

nextEvent(timeout=0)
Parameters:

timeout (int) – Timeout threshold in milliseconds

Returns:

Next available event for this session

Return type:

Event

Raises:

InvalidStateException – If invoked on a session created in asynchronous mode

If there is no Event available this will block for up to the specified timeout milliseconds for an Event to arrive. A value of 0 for timeout (the default) indicates nextEvent() should not timeout and will not return until the next Event is available.

If nextEvent() returns due to a timeout it will return an event of type TIMEOUT.

openService(serviceName)

Open the service identified by the specified serviceName.

Parameters:

serviceName (str) – Name of the service

Return type:

bool

Returns:

True if the service is opened successfully, False otherwise.

Attempt to open the service identified by the specified serviceName and block until the service is either opened successfully or has failed to be opened. Return True if the service is opened successfully and False if the service cannot be successfully opened.

The serviceName must contain a fully qualified service name. That is, it must be of the form //<namespace>/<service-name>.

Before openService() returns a SERVICE_STATUS Event is generated. If this is an asynchronous Session then this Event may be processed by the registered eventHandler before openService() has returned.

openServiceAsync(serviceName, correlationId=None)

Begin the process to open the service and return immediately.

Parameters:
  • serviceName (str) – Name of the service

  • correlationId (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:

CorrelationId

Begin the process to open the service identified by the specified serviceName and return immediately. The optional specified correlationId is used to track Events generated as a result of this call.

The serviceName must 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_STATUS Event which 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 SubscriptionPreprocessMode for an explanation of the available modes.

Returns:

If mode is FAIL_ON_FIRST_ERROR,

then None is returned. If mode is RETURN_INDIVIDUAL_ERRORS, then a list of SubscriptionPreprocessError is returned.

Modify each subscription in the specified subscriptionList, which must be an object of type SubscriptionList, to reflect the modified options specified for it. If the optional requestLabel is provided it defines a string which will be recorded along with any diagnostics for this operation.

For each entry in the subscriptionList which has a correlation ID which identifies a current subscription the modified options replace the current options for the subscription and a SUBSCRIPTION_STATUS Event (containing the resubscriptionId if 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 the subscriptionList does 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:

CorrelationId

Send the specified authorizationRequest and update the specified identity with the results. If the optionally specified correlationId is supplied, it is used; otherwise create a CorrelationId. The actual CorrelationId used is returned. If the optionally specified eventQueue is supplied all Events relating to this Request will arrive on that EventQueue.

The underlying user information must remain valid until the Request has completed successfully or failed.

A successful request will generate zero or more PARTIAL_RESPONSE Messages followed by exactly one RESPONSE Message. Once the final RESPONSE Message has been received the specified identity will have been updated to contain the users entitlement information and the CorrelationId associated with the request may be re-used. If the request fails at any stage a REQUEST_STATUS will be generated, the specified identity will not be modified and the CorrelationId may be re-used.

The identity supplied must have been returned from this Session’s createIdentity() 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:

CorrelationId

Send the specified request using the optionally specified identity for authorization. If identity is not provided, then the request will be sent using the session identity. If the optionally specified correlationId is supplied use it, otherwise create a CorrelationId. The actual CorrelationId used is returned. If the optionally specified eventQueue is supplied all events relating to this Request will arrive on that EventQueue. If the optional requestLabel is 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_RESPONSE Messages followed by exactly one RESPONSE Message. Once the final RESPONSE Message has been received the CorrelationId associated with this request may be re-used. If the request fails at any stage a REQUEST_STATUS will be generated after which the CorrelationId associated with the request may be re-used.

When identity is 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:
Returns:

The actual correlation id used for the request is returned.

Return type:

CorrelationId

If the optionally specified correlationId is supplied, use it otherwise create a new CorrelationId. The actual CorrelationId used is returned.

A successful request will generate zero or more PARTIAL_RESPONSE events followed by exactly one RESPONSE event. Once the final RESPONSE event has been received the CorrelationId associated with this request may be re-used. If the request fails at any stage a REQUEST_STATUS will be generated after which the CorrelationId associated with the request may be re-used.

sessionName()
Return type:

str

Returns:

The session name.

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 Session in synchronous mode.

Return type:

bool

Returns:

True if the Session started successfully, False otherwise.

Attempt to start this Session and block until the Session has started or failed to start. Before start() returns a SESSION_STATUS Event is generated. A Session may only be started once.

startAsync()

Start this Session in asynchronous mode.

Return type:

bool

Returns:

True if the process to start a Session began successfully, False otherwise.

Attempt to begin the process to start this Session. The application must monitor events for a SESSION_STATUS Event which will be generated once the Session has started or if it fails to start. The SESSION_STATUS Event may be processed by the registered eventHandler before startAsync() has returned. A Session may only be started once.

stop()

Stop operation of this Session and wait until it stops.

Return type:

bool

Returns:

True if the Session stopped successfully, False otherwise.

Stop operation of this Session and block until all callbacks to eventHandler objects relating to this Session which are currently in progress have completed (including the callback to handle the SESSION_STATUS Event this call generates). Once this returns no further callbacks to eventHandlers will occur. If stop() is called from within an eventHandler callback it is silently converted to a stopAsync() in order to prevent deadlock. Once a Session has been stopped it can only be destroyed.

stopAsync()

Begin the process to stop this Session and return immediately.

Return type:

bool

Returns:

True if the process to stop a Session began successfully, False otherwise.

The application must monitor events for a SESSION_STATUS Event which will be generated once the Session has been stopped. After this SESSION_STATUS Event no further callbacks to eventHandlers will occur. Once a Session has 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 SubscriptionPreprocessMode for an explanation of the available modes.

Returns:

If mode is FAIL_ON_FIRST_ERROR,

then None is returned. If mode is RETURN_INDIVIDUAL_ERRORS, then a list of SubscriptionPreprocessError is returned.

Begin subscriptions for each entry in the specified subscriptionList, which must be an object of type SubscriptionList, optionally using the specified identity for authorization. If no identity is specified, the default authorization information is used. If the optional requestLabel is provided it defines a string which will be recorded along with any diagnostics for this operation.

A SUBSCRIPTION_STATUS Event will be generated for each entry in the subscriptionList.

When identity is not provided, the session identity will be used if it has been authorized.

tryNextEvent()
Returns:

Next available event for this session

Return type:

Event

If there are Events available for the session, return the next Event If there is no event available for the Session, return None. 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 type SubscriptionList. If the correlation ID of any entry in the subscriptionList does 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 subscriptionList will not be seen in any subsequent Message obtained from a MessageIterator by calling next() However, any Message currently pointed to by a MessageIterator when unsubscribe() is called is not affected even if it has one of the correlation IDs in the subscriptionList. Also any Message where a reference has been retained by the application may still contain a correlation ID from the subscriptionList. 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 asynchronous Session.