blpapi.Session

class blpapi.Session

Bases: blpapi.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 (SessionOptions) – Options to construct the session with

  • eventHandler (Callable) – Handler for events generated by the session. Takes two arguments - received event and related session

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 correlationId request.

Parameters

correlationId (CorrelationId or [CorrelationId]) – Correlation id associated with the request to cancel

If the specified correlationId identifies a current request then 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.

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, identity, correlationId)

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

Parameters
  • subscriptionString (str) – String that specifies the subscription

  • identity (Identity) – Identity used for authorization

  • correlationId (CorrelationId) – Correlation id to associate with events generated by this operation

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.

destroy()
generateToken(correlationId=None, eventQueue=None, authId=None, ipAddress=None)

Generate a token to be used for authorization.

Parameters
  • correlationId (CorrelationId) – Correlation id to be associated with the request

  • eventQueue (EventQueue) – Event queue on which to receive Events related to this request

  • authId (str) – The id used for authentication

  • ipAddress (str) – 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.

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>.

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

Returns

service identified by the specified serviceName.

Return type

Service

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 (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='', resubscriptionId=None)

Modify subscriptions in subscriptionList.

Parameters
  • subscriptionList (SubscriptionList) – List of subscriptions to modify

  • requestLabel (str) – String which will be recorded along with any diagnostics for this operation

  • resubscriptionId (int) – An id that will be included in the event generated from this operation

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 (Request) – Authorization request to send

  • identity (Identity) – Identity to update with the results

  • correlationId (CorrelationId) – Correlation id to associate with the request

  • eventQueue (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.

sendRequest(request, identity=None, correlationId=None, eventQueue=None, requestLabel='')

Send the specified request.

Parameters
  • request (Request) – Request to send

  • identity (Identity) – Identity used for authorization

  • correlationId (CorrelationId) – Correlation id to associate with the request

  • eventQueue (EventQueue) – Event queue on which the events related to this operation will arrive

  • requestLabel (str) – 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 specified identity for authorization. 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.

sendRequestTemplate(requestTemplate, correlationId=None)

Send a request defined by the specified requestTemplate.

Parameters
  • requestTemplate (RequestTemplate) – Template that defines the request

  • correlationId (CorrelationId) – Correlation id to associate with the request

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.

setStatusCorrelationId(service, correlationId, identity=None)

Set the Correlation id on which service status messages will be received.

Parameters
  • service (Service) – The service which from which the status messages are received

  • correlationId (CorrelationId) – Correlation id to associate with the service status messages

  • identity (Identity) – Identity used for authorization

Note

No service status messages are received prior to this call

start()

Start this Session in synchronous mode.

Returns

True if the Session started successfully, False otherwise.

Return type

bool

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.

Returns

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

Return type

bool

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.

Returns

True if the Session stopped successfully, False otherwise.

Return type

bool

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.

Returns

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

Return type

bool

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='')

Begin subscriptions for each entry in the specified list.

Parameters
  • subscriptionList (SubscriptionList) – List of subscriptions to begin

  • identity (Identity) – Identity used for authorization

  • requestLabel (str) – String which will be recorded along with any diagnostics for this operation

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.

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 (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.