Ejemplo n.º 1
0
def processMessage(msg):
    SECURITY_DATA = blpapi.Name("securityData")
    SECURITY = blpapi.Name("security")
    FIELD_DATA = blpapi.Name("fieldData")

    securityDataArray = msg.getElement(SECURITY_DATA)
    for securityData in securityDataArray.values():
        print(securityData.getElementAsString(SECURITY))
        fieldData = securityData.getElement(FIELD_DATA)
        for field in fieldData.elements():
            for i, row in enumerate(field.values()):
                for j in range(row.numElements()):
                    e = row.getElement(j)
                    print("Row %d col %d: %s %s" %
                          (i, j, e.name(), e.getValue()))
Ejemplo n.º 2
0
    def testSubscriptionFailure(self):
        """Sample SubscriptionFailure message"""
        event = blpapi.test.createEvent(blpapi.Event.SUBSCRIPTION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("SubscriptionFailure"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "reason": {
                "source": "TestUtil",
                "errorCode": -1,
                "category": "CATEGORY",
                "description": "for testing",
                "subcategory": "SUBCATEGORY",
            },
            "failureDetails": [{
                "fieldId": "field",
                "reason": {
                    "source": "TestUtil",
                    "errorCode": -1,
                    "category": "CATEGORY",
                    "description": "for testing",
                    "subcategory": "SUBCATEGORY",
                }
            }],
            "resubscriptionId":
            123,
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 3
0
    def testRequestTemplatePending(self):
        """Sample RequestTemplatePending message"""
        event = blpapi.test.createEvent(blpapi.Event.ADMIN)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("RequestTemplatePending"))

        blpapi.test.appendMessage(event, schema)
Ejemplo n.º 4
0
    def __init__(self):
        super(BBGLowLevelTick, self).__init__()

        self.logger = LoggerManager().getLogger(__name__)

        # constants
        self.TICK_DATA = blpapi.Name("tickData")
        self.COND_CODE = blpapi.Name("conditionCodes")
        self.TICK_SIZE = blpapi.Name("size")
        self.TIME = blpapi.Name("time")
        self.TYPE = blpapi.Name("type")
        self.VALUE = blpapi.Name("value")
        self.RESPONSE_ERROR = blpapi.Name("responseError")
        self.CATEGORY = blpapi.Name("category")
        self.MESSAGE = blpapi.Name("message")
        self.SESSION_TERMINATED = blpapi.Name("SessionTerminated")
Ejemplo n.º 5
0
    def testSubscriptionStarted(self):
        """Sample SubscriptionStarted message"""
        event = blpapi.test.createEvent(blpapi.Event.SUBSCRIPTION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("SubscriptionStarted"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "exceptions": [{
                "fieldId": "field",
                "reason": {
                    "source": "TestUtil",
                    "errorCode": -1,
                    "category": "CATEGORY",
                    "description": "for testing",
                    "subcategory": "SUBCATEGORY",
                }
            }],
            "resubscriptionId":
            123,
            "streamIds": ["123", "456"],
            "receivedFrom": {
                "address": "12.34.56.78:81964"
            },
            "reason":
            "TestUtil"
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 6
0
    def testNotifierReceivesSubscriptionStarted(self):
        """ Verify that notifier receives a `SubscriptionStarted` message.

        Plan:
        1. Create a SubscriptionStatus admin event using
           blpapi.test.createEvent().
        2. Obtain the schema for SubscriptionStarted message using
           blpapi.test.getAdminMessageDefinition().
        3. Append a message of type `SubscriptionStarted` using
           blpapi.test.appendMessage().
        4. Verify that the expected message is passed to
           notifier.log_subscription_state().
        """
        event = blpapi.test.createEvent(blpapi.Event.SUBSCRIPTION_STATUS)
        subscription_started = blpapi.Name("SubscriptionStarted")
        schema_def = blpapi.test.getAdminMessageDefinition(subscription_started)

        blpapi.test.appendMessage(event, schema_def)

        self.event_processor.processEvent(event, self.mock_session)

        self.mock_notifier.log_subscription_state.assert_called_once()
        actual_message = \
            self.mock_notifier.log_subscription_state.call_args[0][0]
        self.assertEqual(subscription_started, actual_message.messageType())
Ejemplo n.º 7
0
        def bar(self, sec, s_date, e_date, evtType="TRADE", intvl=60):

            refDataService = self.session.getService("//blp/refdata")
            request = refDataService.createRequest("IntradayBarRequest")
            request.set("security", sec)
            request.set("eventType", evtType)
            request.set("interval", intvl)
            request.set("startDateTime", s_dt)
            request.set("endDateTime", e_dt)
            self.session.sendRequest(request)

            while (True):
                ev = self.session.nextEvent(500)
                if ev.eventType() == blpapi.Event.RESPONSE:
                    a = [msg for msg in ev]
                    break

            pd_barData = pd.DataFrame(columns=[
                "time", "open", "high", "low", "close", "volume", "vwap"
            ])
            bt_data = a[0].getElement(blpapi.Name("barData")).getElement(
                blpapi.Name("barTickData"))

            for bar in bt_data.values():
                t = bar.getElementAsDatetime("time")
                o = bar.getElementAsFloat("open")
                h = bar.getElementAsFloat("high")
                l = bar.getElementAsFloat("low")
                c = bar.getElementAsFloat("close")
                v = bar.getElementAsInteger("volume")
                if v != 0:
                    vwap = bar.getElementAsFloat("value") / v
                else:
                    vwap = bar.getElementAsFloat("value") / 4

                pd_barData = pd_barData.append(
                    {
                        "time": t,
                        "open": o,
                        "high": h,
                        "low": l,
                        "close": c,
                        "volume": v,
                        "vwap": vwap
                    },
                    ignore_index=True)
            return (pd_barData)
Ejemplo n.º 8
0
    def __init__(self):
        super(BBGLowLevelIntraday, self).__init__()

        # constants
        self.BAR_DATA = blpapi.Name("barData")
        self.BAR_TICK_DATA = blpapi.Name("barTickData")
        self.OPEN = blpapi.Name("open")
        self.HIGH = blpapi.Name("high")
        self.LOW = blpapi.Name("low")
        self.CLOSE = blpapi.Name("close")
        self.VOLUME = blpapi.Name("volume")
        self.NUM_EVENTS = blpapi.Name("numEvents")
        self.TIME = blpapi.Name("time")
Ejemplo n.º 9
0
def get_curve_members(field_data, field_name="CURVE_MEMBERS"):
    field_blp_name = blpapi.Name(field_name)
    curve_members_e = field_data.getElement(field_blp_name)
    curve_members = [
        curve_members_e.getValueAsElement(i).getElementAsString(
            "Curve Members") for i in range(curve_members_e.numValues())
    ]
    return curve_members
Ejemplo n.º 10
0
    def testAuthorizationFailure(self):
        """ Verify that for a invalid identity the authorization returns False.

        Plan:
        1. Create a service instance from the apiauth schema.
        2. Create and format an event to represent the authorization failure.
        3. Call authorize()
        4. Verify the following:
           a. The service is opened and retrieved.
           b. A token is generated.
           c. An authorization request is sent.
           d. authorize() returns False.
        """
        self.mock_session.openService.return_value = True

        service = blpapi.test.deserializeService(APIAUTH_SCHEMA)
        self.mock_session.getService.return_value = service

        token = "abcdefg"
        self.mock_token_generator.generate.return_value = token

        event = blpapi.test.createEvent(blpapi.Event.RESPONSE)
        authorization_request = blpapi.Name("AuthorizationRequest")
        authorization_failure_index = 1
        schema_def = service \
                        .getOperation(authorization_request) \
                        .getResponseDefinitionAt(authorization_failure_index)

        formatter = blpapi.test.appendMessage(event, schema_def)

        message_content = {
            "reason": {
                "code": 101,
                "message": "Invalid user",
                "category": "BAD_ARGS",
                "subcategory": "INVALID_USER",
                "source": "test-source"
            }
        }

        formatter.formatMessageDict(message_content)

        self.mock_event_queue.nextEvent.return_value = event

        identity = Mock()
        authorization_result = self.authorizer.authorize(
            identity, self.mock_event_queue)

        self.mock_session.openService.assert_called_once()
        self.mock_session.getService.assert_called_once()
        self.mock_session.sendAuthorizationRequest.assert_called_once()

        self.mock_token_generator.generate.assert_called_once()
        self.mock_event_queue.nextEvent.assert_called_once()

        self.assertFalse(authorization_result)
Ejemplo n.º 11
0
    def testDataLoss(self):
        """Sample DataLoss message"""
        event = blpapi.test.createEvent(blpapi.Event.ADMIN)
        schema = blpapi.test.getAdminMessageDefinition(blpapi.Name("DataLoss"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {"id": "id", "source": "Test", "numMessagesDropped": 123}

        formatter.formatMessageDict(content)
Ejemplo n.º 12
0
    def testTokenGenerationSuccess(self):
        """Sample TokenGenerationSuccess message"""
        event = blpapi.test.createEvent(blpapi.Event.TOKEN_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("TokenGenerationSuccess"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {"token": "mytoken"}

        formatter.formatMessageDict(content)
Ejemplo n.º 13
0
    def testTopicSubscribed(self):
        """Sample TopicSubscribed message"""
        event = blpapi.test.createEvent(blpapi.Event.TOPIC_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("TopicSubscribed"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {"topic": "mytopic", "topicWithOptions": "topicwithopts"}

        formatter.formatMessageDict(content)
Ejemplo n.º 14
0
    def testResolutionSuccess(self):
        """Sample ResolutionSuccess message"""
        event = blpapi.test.createEvent(blpapi.Event.RESOLUTION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("ResolutionSuccess"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {"resolvedTopic": "//blp/myservice/rtopic"}

        formatter.formatMessageDict(content)
Ejemplo n.º 15
0
    def testSlowConsumerWarningCleared(self):
        """Sample SlowConsumerWarningCleared message"""
        event = blpapi.test.createEvent(blpapi.Event.ADMIN)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("SlowConsumerWarningCleared"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {"eventsDropped": 123}

        formatter.formatMessageDict(content)
Ejemplo n.º 16
0
    def testServiceDeregistered(self):
        """Sample ServiceDeregistered message"""
        event = blpapi.test.createEvent(blpapi.Event.SERVICE_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("ServiceDeregistered"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {"serviceName": "//blp/myservice"}

        formatter.formatMessageDict(content)
Ejemplo n.º 17
0
    def testTopicDeactivated(self):
        """Sample TopicDeactivated message"""
        event = blpapi.test.createEvent(blpapi.Event.TOPIC_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("TopicDeactivated"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {"topic": "mytopic", "reason": "TestUtil"}

        formatter.formatMessageDict(content)
Ejemplo n.º 18
0
    def processMessage(self, session, sec, field):
        # Set various variables equal to various features within BLPAPI
        # These "names" references keys with the JSON that is returned by BBG after a call
        SECURITY_DATA = blpapi.Name("securityData")
        SECURITY = blpapi.Name("security")
        FIELD_DATA = blpapi.Name("fieldData")
        FIELD_EXCEPTIONS = blpapi.Name("fieldExceptions")
        FIELD_ID = blpapi.Name("fieldId")
        ERROR_INFO = blpapi.Name("errorInfo")

        while (True):
            ev = session.nextEvent(500)
            for msg in ev:
                # print(msg)
                if ev.eventType() == blpapi.Event.PARTIAL_RESPONSE or ev.eventType() == blpapi.Event.RESPONSE:
                    secName = msg.getElement(SECURITY_DATA).getElementAsString(SECURITY)
                    fieldDataArray = msg.getElement(SECURITY_DATA).getElement(FIELD_DATA)
                    size = fieldDataArray.numValues()
                    fieldDataList = [fieldDataArray.getValueAsElement(i) for i in range(0, size)]
                    outDates = [x.getElementAsDatetime('date') for x in fieldDataList]
                    dateFrame = pd.DataFrame({'date': outDates})
                    strData = [field]
                    output = pd.DataFrame(columns=strData)
                    for strD in strData:
                        outData = [x.getElementAsFloat(strD) for x in fieldDataList]
                        output[strD] = outData
                        output['secID'] = secName
                        output = pd.concat([output], axis=1)
                    output = pd.concat([dateFrame, output], axis=1)
            if ev.eventType() == blpapi.Event.RESPONSE:
                break
        return output
Ejemplo n.º 19
0
    def testSessionConnectionDown(self):
        """Sample SessionConnectionDown message"""
        event = blpapi.test.createEvent(blpapi.Event.SESSION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("SessionConnectionDown"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "server": "12.34.56.78:8194",
            "serverId": "ny-hostname",
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 20
0
    def testSessionConnectionUp(self):
        """Sample SessionConnectionUp message"""
        event = blpapi.test.createEvent(blpapi.Event.SESSION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("SessionConnectionUp"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "server": "12.34.56.78:8194",
            "serverId": "ny-hostname",
            "encryptionStatus": "Clear",
            "compressionStatus": "Uncompressed"
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 21
0
    def testAuthorizationSuccess(self):
        """ Verify that for a valid identity the authorization returns True.

        Plan:
        1. Create a service instance from the apiauth schema.
        2. Set the following expectations:
           b. Verify that service is opened and successfully retrieved.
        3. Create an admin event to represent the authorization success.
        4. Call authorize()
        4. Verify the following:
           a. The service is opened and retrieved.
           b. A token is generated.
           c. An authorization request is sent.
           d. authorize() returns True.
        """
        self.mock_session.openService.return_value = True

        service = blpapi.test.deserializeService(APIAUTH_SCHEMA)
        self.mock_session.getService.return_value = service

        token = "abcdefg"
        self.mock_token_generator.generate.return_value = token

        event = blpapi.test.createEvent(blpapi.Event.RESPONSE)
        authorization_success = blpapi.Name("AuthorizationSuccess")
        schema_def = \
            blpapi.test.getAdminMessageDefinition(authorization_success)

        blpapi.test.appendMessage(event, schema_def)

        # The AuthorizationSuccess message does not have any fields, therefore
        # no formatting is required.

        self.mock_event_queue.nextEvent.return_value = event

        identity = Mock()
        authorization_result = self.authorizer.authorize(
            identity, self.mock_event_queue)

        self.mock_session.openService.assert_called_once()
        self.mock_session.getService.assert_called_once()
        self.mock_session.sendAuthorizationRequest.assert_called_once()

        self.mock_token_generator.generate.assert_called_once()
        self.mock_event_queue.nextEvent.assert_called_once()

        self.assertTrue(authorization_result)
Ejemplo n.º 22
0
    def testRequestTemplateAvailable(self):
        """Sample RequestTemplateAvailable message"""
        event = blpapi.test.createEvent(blpapi.Event.ADMIN)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("RequestTemplateAvailable"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "boundTo": {
                "dataConnection": [{
                    "address": "12.34.56.78:8194"
                }]
            }
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 23
0
    def testSessionStarted(self):
        """Sample SessionStarted message"""
        event = blpapi.test.createEvent(blpapi.Event.SESSION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("SessionStarted"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "initialEndpoints": [{
                "address": "12.34.56.78:8194"
            }, {
                "address": "98.76.54.32:8194"
            }]
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 24
0
    def testSessionTerminated(self):
        """Sample SessionTerminated message"""
        event = blpapi.test.createEvent(blpapi.Event.SESSION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("SessionTerminated"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "reason": {
                "source": "TestUtil",
                "errorCode": -1,
                "category": "CATEGORY",
                "description": "for testing",
                "subcategory": "SUBCATEGORY",
            }
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 25
0
    def testResolutionFailure(self):
        """Sample ResolutionFailure message"""
        event = blpapi.test.createEvent(blpapi.Event.RESOLUTION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("ResolutionFailure"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "reason": {
                "source": "TestUtil",
                "errorCode": -1,
                "category": "CATEGORY",
                "description": "for testing",
                "subcategory": "SUBCATEGORY",
            }
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 26
0
    def testServiceAvailabilityInfo(self):
        """Sample ServiceAvailabilityInfo message"""
        event = blpapi.test.createEvent(blpapi.Event.SERVICE_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("ServiceAvailabilityInfo"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "serviceName": "//blp/myservice",
            "serverAdded": {
                "address": "12.34.56.78"
            },
            "serverRemoved": {
                "address": "12.34.56.78"
            },
            "servers": ["12.34.56.78", "12.34.56.78"]
        }
        formatter.formatMessageDict(content)
Ejemplo n.º 27
0
    def testNotifierReceivesSubscriptionData(self):
        """ Verify that:
        1. Compute engine receives the correct LAST_PRICE.
        2. Compute engine performs the correct computation and returns the
           correct value.
        3. The correct value is sent to the terminal.

        Plan:
        1. Obtain the service by deserializing its schema.
        2. Create a SubscriptionEvent using blpapi.test.createEvent().
        3. Obtain the element schema definition from the service.
        4. Append a message of type `MarketDataEvents' using
           blpapi.test.appendMessage().
        5. Format the message using the formatter returned by appendMessage().
           In this example the message's body is represented by
           { LAST_PRICE: 142.80 }.
        6. Verify that the expected and actual values are the same.
        """
        event = blpapi.test.createEvent(blpapi.Event.SUBSCRIPTION_DATA)

        service = blpapi.test.deserializeService(MKTDATA_SCHEMA)
        mktdata_events = blpapi.Name("MarketDataEvents")
        schema_def = service.getEventDefinition(mktdata_events)

        formatter = blpapi.test.appendMessage(event, schema_def)

        expected_last_price = 142.80
        message_content = {
            "LAST_PRICE": expected_last_price
        }
        formatter.formatMessageDict(message_content)

        expected_compute_result = 200.00

        self.mock_compute_engine.someVeryComplexComputation.return_value = \
            expected_compute_result

        self.event_processor.processEvent(event, self.mock_session)

        self.mock_compute_engine.someVeryComplexComputation \
            .assert_called_once_with(expected_last_price)
        self.mock_notifier.send_to_terminal \
            .assert_called_once_with(expected_compute_result)
Ejemplo n.º 28
0
    def testSessionClusterUpdate(self):
        """Sample SessionClusterUpdate message"""
        event = blpapi.test.createEvent(blpapi.Event.SESSION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("SessionClusterUpdate"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "name": "clustername",
            "endpointsAdded": [{
                "address": "12.34.56.78:8194"
            }],
            "endpointsRemoved": [{
                "address": "98.76.54.32:8194"
            }]
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 29
0
    def testSubscriptionStreamsDeactivated(self):
        """Sample SubscriptionStreamsDeactivated message"""
        event = blpapi.test.createEvent(blpapi.Event.SUBSCRIPTION_STATUS)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("SubscriptionStreamsDeactivated"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "streams": [{
                "id": "streamId",
                "endpoint": {
                    "address": "12.34.56.78:8194"
                }
            }],
            "reason":
            "TestUtil"
        }

        formatter.formatMessageDict(content)
Ejemplo n.º 30
0
    def testPermissionRequest(self):
        """Sample PermissionRequest message"""
        event = blpapi.test.createEvent(blpapi.Event.REQUEST)
        schema = blpapi.test.getAdminMessageDefinition(
            blpapi.Name("PermissionRequest"))

        formatter = blpapi.test.appendMessage(event, schema)

        content = {
            "topics": ["topic1", "topic2"],
            "serviceName": "//blp/mytestservice",
            "uuid": 1234,
            "seatType": 1234,
            "applicationId": 1234,
            "userName": "******",
            "appName": "myAppName",
            "deviceAddress": "myDevice"
        }

        formatter.formatMessageDict(content)