def main():
    """Main function"""

    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = prepareZfpSessionOptions(options) \
        if options.remote \
        else prepareStandardSessionOptions(options)
    sessionOptions.setAuthenticationOptions(options.auth['option'])
    sessionOptions.setAutoRestartOnDisconnection(True)

    session = blpapi.Session(sessionOptions)

    if not session.start():
        print("Failed to start session.")
        return

    subscriptionIdentity = session.createIdentity()

    if options.auth['option']:
        isAuthorized = False
        authServiceName = "//blp/apiauth"
        if session.openService(authServiceName):
            authService = session.getService(authServiceName)
            isAuthorized = authorize(
                authService, subscriptionIdentity, session,
                blpapi.CorrelationId("auth"),
                options.auth.get('manual'))
        if not isAuthorized:
            print("No authorization")
            return

    subscriptions = blpapi.SubscriptionList()
    for t in options.topics:
        topic = options.service + t
        subscriptions.add(topic,
                          options.fields,
                          options.options,
                          blpapi.CorrelationId(topic))

    session.subscribe(subscriptions, subscriptionIdentity)

    try:
        eventCount = 0
        while True:
            # Specify timeout to give a chance for Ctrl-C
            event = session.nextEvent(1000)
            for msg in event:
                if event.eventType() == blpapi.Event.SUBSCRIPTION_STATUS or \
                        event.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
                    print("%s - %s" % (msg.correlationIds()[0].value(), msg))
                else:
                    print(msg)
            if event.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
                eventCount += 1
                if eventCount >= options.maxEvents:
                    break
    finally:
        session.stop()
def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    sessionOptions.setServerHost(options.host)
    sessionOptions.setServerPort(options.port)

    print("Connecting to %s:%d" % (options.host, options.port))

    # Create a Session
    session = blpapi.Session(sessionOptions)

    # Start a Session
    if not session.start():
        print("Failed to start session.")
        return

    if not session.openService("//blp/mktdata"):
        print("Failed to open //blp/mktdata")
        return

    security1 = "IBM US Equity"
    security2 = "/cusip/912828GM6@BGN"

    subscriptions = blpapi.SubscriptionList()
    subscriptions.add(security1,
                      "LAST_PRICE,BID,ASK",
                      "",
                      blpapi.CorrelationId(security1))
    subscriptions.add(security2,
                      "LAST_PRICE,BID,ASK,BID_YIELD,ASK_YIELD",
                      "",
                      blpapi.CorrelationId(security2))

    session.subscribe(subscriptions)

    try:
        # Process received events
        eventCount = 0
        while(True):
            # We provide timeout to give the chance to Ctrl+C handling:
            event = session.nextEvent(500)
            for msg in event:
                if event.eventType() == blpapi.Event.SUBSCRIPTION_STATUS or \
                        event.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
                    print("%s - %s" % (msg.correlationIds()[0].value(), msg))
                else:
                    print(msg)
            if event.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
                eventCount += 1
                if eventCount >= options.maxEvents:
                    break
    finally:
        # Stop the session
        session.stop()
Exemple #3
0
def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    for idx, host in enumerate(options.hosts):
        sessionOptions.setServerAddress(host, options.port, idx)
    sessionOptions.setSessionIdentityOptions(options.auth['option'])
    sessionOptions.setAutoRestartOnDisconnection(True)

    # NOTE: If running without a backup server, make many attempts to
    # connect/reconnect to give that host a chance to come back up (the
    # larger the number, the longer it will take for SessionStartupFailure
    # to come on startup, or SessionTerminated due to inability to fail
    # over).  We don't have to do that in a redundant configuration - it's
    # expected at least one server is up and reachable at any given time,
    # so only try to connect to each server once.
    sessionOptions.setNumStartAttempts(1 if len(options.hosts) > 1 else 1000)

    print("Connecting to port %d on %s" %
          (options.port, ", ".join(options.hosts)))

    session = blpapi.Session(sessionOptions)

    if not session.start():
        print("Failed to start session.")
        return

    topic = options.service + "/1245/4/5"
    topic2 = options.service + "/330/1/1"
    subscriptions = blpapi.SubscriptionList()
    subscriptions.add(topic, correlationId=blpapi.CorrelationId(topic))
    subscriptions.add(topic2, correlationId=blpapi.CorrelationId(topic2))

    session.subscribe(subscriptions)

    try:
        eventCount = 0
        while True:
            # Specify timeout to give a chance for Ctrl-C
            event = session.nextEvent(1000)
            for msg in event:
                if event.eventType() == blpapi.Event.SUBSCRIPTION_STATUS or \
                        event.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
                    print("%s - %s" % (msg.correlationIds()[0].value(), msg))
                else:
                    print(msg)
            if event.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
                eventCount += 1
                if eventCount >= options.maxEvents:
                    break
    finally:
        session.stop()
    def processServiceStatusEvent(self, event, session):
        print("Processing SERVICE_STATUS event")

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print("Service opened...")

                service = session.getService(d_service)

                request = service.createRequest("SellSideAck")

                #request.set("EMSX_REQUEST_SEQ", 1)

                request.setElement("EMSX_SEQUENCE", 1234567)

                # If performing the ack on an order owned by another team member, provide owner's UUID
                #request.set("EMSX_TRADER_UUID", 7654321)

                print("Request: %s" % request.toString())

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, ("Error: Service failed to open")
def main():
    """Main function"""

    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = prepareZfpSessionOptions(options) \
        if options.remote \
        else prepareStandardSessionOptions(options)
    sessionOptions.setSessionIdentityOptions(options.auth['option'])

    session = blpapi.Session(sessionOptions)
    try:
        if not session.start():
            checkFailures(session)
            print("Failed to start session.")
            return

        if not session.openService(options.service):
            checkFailures(session)
            return

        subscriptions = blpapi.SubscriptionList()
        for t in options.topics:
            topic = options.service + t
            subscriptions.add(topic, options.fields, options.options,
                              blpapi.CorrelationId(topic))
        session.subscribe(subscriptions)

        processSubscriptionEvents(session, options.maxEvents)
    finally:
        session.stop()
Exemple #6
0
    def processServiceStatusEvent(self, event, session):
        print("Processing SERVICE_STATUS event")

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print("Service opened...")

                service = session.getService(d_service)

                request = service.createRequest("SellSideAck")

                #request.set("EMSX_REQUEST_SEQ", 1)

                request.append("EMSX_SEQUENCE", 1234567)

                # The following Element is currently not being used in this request.
                #request.set("EMSX_TRADER_UUID", 7654321)

                print("Request: %s" % request.toString())

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, ("Error: Service failed to open")
Exemple #7
0
    def processServiceStatusEvent(self, event, session):
        print "Processing SERVICE_STATUS event"

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print "Service opened..."

                service = session.getService(d_service)

                request = service.createRequest("AssignTrader")

                request.append("EMSX_SEQUENCE", 3744303)
                request.append("EMSX_SEQUENCE", 3744341)

                request.set("EMSX_ASSIGNEE_TRADER_UUID", 12109783)

                print "Request: %s" % request.toString()

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, "Error: Service failed to open"
    def processServiceStatusEvent(self, event, session):
        print "Processing SERVICE_STATUS event"

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print "Service opened..."

                service = session.getService(d_service)

                request = service.createRequest("CancelRoute")

                #request.set("EMSX_REQUEST_SEQ", 1)
                #request.set("EMSX_TRADER_UUID", 1234567)        # UUID of trader who owns the order

                routes = request.getElement("ROUTES")

                route = routes.appendElement()
                route.getElement("EMSX_SEQUENCE").setValue(3744354)
                route.getElement("EMSX_ROUTE_ID").setValue(1)

                print "Request: %s" % request.toString()

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, "Error: Service failed to open"
    def processServiceStatusEvent(self, event, session):
        print("Processing SERVICE_STATUS event")

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print("Service opened...")

                service = session.getService(d_service)

                request = service.createRequest("AssignTrader")

                request.append(
                    "EMSX_SEQUENCE", 5062768
                )  #This is the EMSX_SEQUENCE or Order# from EMSX blotter
                #request.append("EMSX_SEQUENCE", 5062767)

                request.set("EMSX_ASSIGNEE_TRADER_UUID",
                            7569479)  #This is the new UUID

                print("Request: %s" % request.toString())

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, ("Error: Service failed to open")
Exemple #10
0
    def _beqs(self, screen_name, screen_type, group, language_id, asof_date):

        # flush event queue in case previous call errored out
        while (self.session.tryNextEvent()):
            pass

        request = self._beqs_create_req(screen_name, screen_type, group,
                                        language_id)

        cid = None
        if asof_date is not None:
            overrides = request.getElement("overrides")
            ovrd = overrides.appendElement()
            ovrd.setElement("fieldId", "PiTDate")
            ovrd.setElement("value", asof_date.strftime('%Y%m%d'))
            cid = blpapi.CorrelationId(asof_date)

        logging.debug("Sending Request:\n %s" % request)
        # Send the request
        self.session.sendRequest(request, correlationId=cid)
        data = []
        # Process received events
        while (True):
            # We provide timeout to give the chance for Ctrl+C handling:
            ev = self.session.nextEvent(500)
            data = self._beqs_parse_event(data, ev)

            if ev.eventType() == blpapi.Event.RESPONSE:
                # Response completely received, so we could exit
                break

        return data
Exemple #11
0
 def __init__(self, host_ip=None, host_port=None, uuid=None, local_ip=None):
     if host_ip is not None:
         host_port = int(host_port)  # needs to be an int
         uuid = int(uuid)  # needs to be an int
         opt = blpapi.SessionOptions()
         opt.setClientMode(2)
         opt.setServerHost(host_ip)
         opt.setServerPort(host_port)
         blpapi.Session.__init__(self, opt)
         self.start()
         identity = self.createIdentity()
         self.openService('//blp/apiauth')
         apiAuthSvc = self.getService('//blp/apiauth')
         auth_req = apiAuthSvc.createAuthorizationRequest()
         auth_req.set('uuid', uuid)
         auth_req.set('ipAddress', local_ip)
         corr = blpapi.CorrelationId(uuid)
         self.sendAuthorizationRequest(auth_req, identity, corr)
         while True:
             event = self.nextEvent()
             if event.eventType() == blpapi.event.Event.RESPONSE:
                 break
         msg_iter = blpapi.event.MessageIterator(event)
         auth_msg = msg_iter.next().toString()[0:20]
         if auth_msg == 'AuthorizationSuccess':
             print(str(uuid) + ' authorized and connected.')
             self.auth_success = True
         else:
             print(str(uuid) + ' failed to connect.')
             self.auth_success = False
     else:
         blpapi.Session.__init__(self)
         self.start()
Exemple #12
0
def processTokenStatus(event):
    global g_identity
    print("processTokenEvents")

    # Handle response to token generation request
    for msg in event:
        if msg.messageType() == TOKEN_SUCCESS:
            print(msg)

            # Authentication phase has passed; send authorization request
            authService = g_session.getService("//blp/apiauth")
            authRequest = authService.createAuthorizationRequest()
            authRequest.set("token",
                            msg.getElementAsString("token"))

            g_identity = g_session.createIdentity()
            g_session.sendAuthorizationRequest(
                authRequest,
                g_identity,
                blpapi.CorrelationId(1))
        elif msg.messageType() == TOKEN_FAILURE:
            # Token generation failure
            print(msg)
            return False
    return True
Exemple #13
0
    def processServiceStatusEvent(self, event, session):
        print("Processing SERVICE_STATUS event")

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print("Service opened...")

                service = session.getService(d_service)

                request = service.createRequest("CancelOrderEx")

                #request.set("EMSX_REQUEST_SEQ", 1)
                #request.set("EMSX_TRADER_UUID", 1234567)        # UUID of trader who owns the order

                request.getElement("EMSX_SEQUENCE").appendValue(55783249)
                #request.getElement("EMSX_SEQUENCE").appendValue(1234567)

                print("Request: %s" % request.toString())

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, ("Error: Service failed to open")
Exemple #14
0
    def processServiceStatusEvent(self, event, session):
        print("Processing SERVICE_STATUS event")

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print("Service opened...")

                service = session.getService(d_service)

                request = service.createRequest(
                    "GetBrokerStrategyInfoWithAssetClass")

                request.set("EMSX_REQUEST_SEQ", 1)

                request.set("EMSX_ASSET_CLASS",
                            "EQTY")  # one of EQTY, OPT, FUT or MULTILEG_OPT
                request.set("EMSX_BROKER", "BMTB")
                request.set("EMSX_STRATEGY", "VWAP")

                print("Request: %s" % request.toString())

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, ("Error: Service failed to open")
Exemple #15
0
    def testSuccessfulResolution(self):
        """ Test the creation of a successful permission response. """
        mockSession = Mock()
        service = getService()

        cid = blpapi.CorrelationId(1)
        permissionEvent = createPermissionEvent(cid, ALLOWED_APP_ID)
        permissionRequest = getFirstMessage(permissionEvent)

        handlePermissionRequest(mockSession, service, permissionRequest)

        mockSession.sendResponse.assert_called_once()
        response = mockSession.sendResponse.call_args[0][0]
        self.assertEqual(blpapi.Event.RESPONSE, response.eventType())

        permissionResponse = getFirstMessage(response)
        self.assertEqual(cid, permissionResponse.correlationIds()[0])
        self.assertEqual(PERMISSION_RESPONSE, permissionResponse.messageType())
        self.assertTrue(permissionResponse.hasElement(TOPIC_PERMISSIONS))

        topicPermissions = permissionResponse.getElement(TOPIC_PERMISSIONS)

        topicCount = 2
        self.assertEqual(topicCount, topicPermissions.numValues())

        for i in range(topicCount):
            topicPermission = topicPermissions.getValueAsElement(i)
            self.assertTrue(topicPermission.hasElement(RESULT))
            self.assertEqual(0, topicPermission.getElementAsInteger(RESULT))
Exemple #16
0
    def processServiceStatusEvent(self, event, session):
        print "Processing SERVICE_STATUS event"

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print "Service opened..."

                service = session.getService(d_service)

                request = service.createRequest("DeleteOrder")

                #request.set("EMSX_REQUEST_SEQ", 1)

                request.getElement("EMSX_SEQUENCE").appendValue(3744363)
                request.getElement("EMSX_SEQUENCE").appendValue(3744364)

                print "Request: %s" % request.toString()

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, "Error: Service failed to open"
    def processServiceStatusEvent(self, event, session):
        print("Processing SERVICE_STATUS event")

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print("Service opened...")

                service = session.getService(d_service)

                request = service.createRequest("GetFieldMetaData")

                #request.set("EMSX_REQUEST_SEQ", 1)

                request.getElement("EMSX_FIELD_NAMES").appendValue(
                    "EMSX_TICKER")
                request.getElement("EMSX_FIELD_NAMES").appendValue("EMSX_P_A")
                request.getElement("EMSX_FIELD_NAMES").appendValue(
                    "EMSX_CLEARING_ACCOUNT")

                print("Request: %s" % request.toString())

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, ("Error: Service failed to open")
def authorizeUsers():
    authService = g_session.getService(APIAUTH_SVC)
    is_any_user_authorized = False

    # Authorize each of the users
    for index, token in enumerate(g_tokens):
        identity = g_session.createIdentity()
        g_identities.append(identity)
        authRequest = authService.createAuthorizationRequest()
        authRequest.set("token", token)
        correlator = blpapi.CorrelationId(token)
        eventQueue = blpapi.EventQueue()
        g_session.sendAuthorizationRequest(authRequest, identity, correlator,
                                           eventQueue)
        event = eventQueue.nextEvent()
        if (event.eventType() == blpapi.Event.RESPONSE
                or event.eventType() == blpapi.Event.REQUEST_STATUS):
            for msg in event:
                if msg.messageType() == AUTHORIZATION_SUCCESS:
                    print("User %s authorization success" % (index + 1))
                    is_any_user_authorized = True
                else:
                    print("User %s authorization failed" % (index + 1))
                    printEvent(event)
    return is_any_user_authorized
Exemple #19
0
    def subscribe(self, topics, fields, options, identity):
        """Subscribes to the provided service/topics."""

        subscription_list = blpapi.SubscriptionList()
        for topic in topics:
            subscription_list.add(topic, fields, options,
                                  blpapi.CorrelationId(topic))
        self._session.subscribe(subscription_list, identity)
Exemple #20
0
def subscribe(session, options, identity=None):
    sl = blpapi.SubscriptionList()
    for s in options.securities:
        topic = topicName(s)
        cid = blpapi.CorrelationId(s)
        print("Subscribing {0} => {1}".format(cid, topic))
        sl.add(topic, options.fields, correlationId=cid)
    session.subscribe(sl, identity)
Exemple #21
0
    def authorize(self, identity, queue=None):
        """Authorize the provided identity.

        Return True on success and False on failure.
        """
        if self._session.openService("//blp/apiauth"):
            service = self._session.getService("//blp/apiauth")
            cid = blpapi.CorrelationId("auth")
            return self._authorize(service, identity, cid, queue)
        return False
Exemple #22
0
def subscribe():
    # Create a SubscriptionList and populate it with securities, fields etc
    subscriptions = blpapi.SubscriptionList()

    for i, security in enumerate(g_securities):
        subscriptions.add(security, g_fields, g_options,
                          blpapi.CorrelationId(i))

    print("Subscribing...")
    g_session.subscribe(subscriptions, g_identity)
Exemple #23
0
def main():
    global g_session, g_securities, g_fields

    print("GenerateTokenSubscriptionExample")
    options = parseCmdLine()

    # Create SessionOptions object and populate it with data
    sessionOptions = blpapi.SessionOptions()
    sessionOptions.setServerHost(options.host)
    sessionOptions.setServerPort(options.port)
    authOptions = "AuthenticationType=OS_LOGON"
    if options.dirSvcProperty:
        authOptions = "AuthenticationType=DIRECTORY_SERVICE;" + \
            "DirSvcPropertyName=" + options.dirSvcProperty
    print("authOptions = %s" % authOptions)
    sessionOptions.setAuthenticationOptions(authOptions)

    g_securities = options.securities
    g_fields = options.fields

    print("Connecting to %s:%s" % (options.host, options.port))
    g_session = blpapi.Session(sessionOptions)
    if not g_session.start():
        print("Failed to start session.")
        return

    # Open market data service
    if not g_session.openService("//blp/mktdata"):
        print("Failed to open //blp/mktdata")
        return

    # Open authorization service
    if not g_session.openService("//blp/apiauth"):
        print("Failed to open //blp/apiauth")
        return

    # Submit a token generation request
    tokenReqId = blpapi.CorrelationId(99)
    g_session.generateToken(tokenReqId)

    # Handle and respond to incoming events
    while True:
        # nextEvent() method below is called with a timeout to let
        # the program catch Ctrl-C between arrivals of new events
        event = g_session.nextEvent(1000)
        if event.eventType() != blpapi.Event.TIMEOUT:
            if event.eventType() == blpapi.Event.TOKEN_STATUS:
                # Handle response to token generation request
                if not processTokenStatus(event):
                    break
            else:
                # Handle all other events
                if not processEvent(event):
                    break
Exemple #24
0
    def subscribe(self, topic, message_handler):
        try:
            self.next_cor_id+=1
            c_id = blpapi.CorrelationId(self.next_cor_id)
            subscriptions = blpapi.SubscriptionList()
            subscriptions.add(topic=topic, correlationId=c_id)
            self.session.subscribe(subscriptions)
            self.subscription_message_handlers[c_id.value()] = message_handler
#            print("Request submitted (" + str(cID)  + "): \n" + str(topic))
            
        except Exception as err:
            print("EasyMSX >>  Error subscribing to topic: " + str(err))
Exemple #25
0
def get_ref_data(identifier, identifier_value, fields_map):
    sessionOptions = blpapi.SessionOptions()
    sessionOptions.setServerAddress('localhost', 8194, 0)
    sessionOptions.setNumStartAttempts(1)
    sessionOptions.setAutoRestartOnDisconnection(True)
    session = blpapi.Session(sessionOptions)
    if not session.start():
        print("Failed to start session.")
        return 0
    identity = session.createIdentity()
    session.openService("//blp/refdata")
    service = session.getService("//blp/refdata")
    request = service.createRequest("ReferenceDataRequest")
    sec = "/%s/%s" % (identifier, identifier_value)
    request.append("securities", sec)
    all_fields = []
    for fields in fields_map.values():
        if type(fields) == str:
            request.append("fields", fields)
            all_fields.append(fields)
        else:
            for field in fields:
                request.append("fields", field)
                all_fields.append(field)
    eventQueue = blpapi.EventQueue()
    session.sendRequest(request, identity, blpapi.CorrelationId("AddRequest"),
                        eventQueue)
    data = pd.DataFrame()
    while True:
        # Specify timeout to give a chance for Ctrl-C
        event = eventQueue.nextEvent(500)

        if event.eventType() == blpapi.Event.TIMEOUT:
            continue

        for msg in event:
            securityData = msg.getElement(SECURITY_DATA)
            securityDataList = [securityData.getValueAsElement(i) for i in range(securityData.numValues())]
            data = pd.DataFrame(index=[0], columns=all_fields)

            for sec in securityDataList:
                fieldData = sec.getElement(FIELD_DATA)
                fieldDataList = [fieldData.getElement(i) for i in range(fieldData.numElements())]

                for fld in fieldDataList:
                    data[str(fld.name())] = fld.getValue()
        if event.eventType() == blpapi.Event.RESPONSE:
            break
    session.stop()
    if len(data):
        return data
    else:
        print("No Data found")
    def processServiceStatusEvent(self,event,session):
        print "Processing SERVICE_STATUS event"
        
        for msg in event:
            
            if msg.messageType() == SERVICE_OPENED:
                print "Service opened..."

                service = session.getService(d_service)
    
                request = service.createRequest("CreateOrderAndRouteManually")

                # The fields below are mandatory
                request.set("EMSX_TICKER", "IBM US Equity")
                request.set("EMSX_AMOUNT", 1000)
                request.set("EMSX_ORDER_TYPE", "MKT")
                request.set("EMSX_TIF", "DAY")
                request.set("EMSX_HAND_INSTRUCTION", "ANY")
                request.set("EMSX_SIDE", "BUY")
                request.set("EMSX_BROKER", "BB")
            
                # The fields below are optional
                #request.set("EMSX_ACCOUNT","TestAccount")
                #request.set("EMSX_CFD_FLAG", "1")
                #request.set("EMSX_CLEARING_ACCOUNT", "ClrAccName")
                #request.set("EMSX_CLEARING_FIRM", "FirmName")
                #request.set("EMSX_EXCHANGE_DESTINATION", "ExchDest")
                #request.set("EMSX_EXEC_INSTRUCTIONS", "AnyInst")
                #request.set("EMSX_GET_WARNINGS", "0")
                #request.set("EMSX_GTD_DATE", "20170105")
                #request.set("EMSX_INVESTOR_ID", "InvID")
                #request.set("EMSX_LIMIT_PRICE", 123.45)
                #request.set("EMSX_LOCATE_BROKER", "BMTB")
                #request.set("EMSX_LOCATE_ID", "SomeID")
                #request.set("EMSX_LOCATE_REQ", "Y")
                #request.set("EMSX_NOTES", "Some notes")
                #request.set("EMSX_ODD_LOT", "0")
                #request.set("EMSX_ORDER_ORIGIN", "")
                #request.set("EMSX_ORDER_REF_ID", "UniqueID")
                #request.set("EMSX_P_A", "P")
                #request.set("EMSX_RELEASE_TIME", 34341)
                #request.set("EMSX_REQUEST_SEQ", 1001)
                #request.set("EMSX_SETTLE_DATE", 20170106)
                #request.set("EMSX_STOP_PRICE", 123.5)

                print "Request: %s" % request.toString()
                    
                self.requestID = blpapi.CorrelationId()
                
                session.sendRequest(request, correlationId=self.requestID )
                            
            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, "Error: Service failed to open"        
    def processServiceStatusEvent(self, event, session):
        print "Processing SERVICE_STATUS event"

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print "Service opened..."

                service = session.getService(d_service)

                request = service.createRequest("GetFills")

                request.set("FromDateTime", "2017-03-30T00:00:00.000+00:00")
                request.set("ToDateTime", "2017-03-30T23:59:00.000+00:00")

                scope = request.getElement("Scope")

                #scope.setChoice("Team")
                #scope.setChoice("TradingSystem")
                scope.setChoice("Uuids")

                #scope.setElement("Team", "SEXEGROUP")
                #scope.setElement("TradingSystem",false)

                scope.getElement("Uuids").appendValue(8049857)
                '''
                scope.getElement("Uuids").appendValue(14348220);
                scope.getElement("Uuids").appendValue(8639067);
                scope.getElement("Uuids").appendValue(4674574);
                '''

                #filter = request.getElement("FilterBy")

                #filter.setChoice("Basket")
                #filter.setChoice("Multileg")
                #filter.setChoice("OrdersAndRoutes")

                #filter.getElement("Basket").appendValue("TESTRJC")
                #filter.getElement("Multileg").appendValue("mymlegId")

                #newOrder = filter.getElement("OrdersAndRoutes").appendElement()
                #newOrder.setElement("OrderId",4292580)
                #newOrder.setElement("RouteId",1)

                print "Request: %s" % request.toString()

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, "Error: Service failed to open"
    def processServiceStatusEvent(self, event, session):
        print("Processing SERVICE_STATUS event")

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:
                print("Service opened...")

                service = session.getService(d_service)

                request = service.createRequest("GetFills")

                request.set("FromDateTime", "2017-11-03T00:00:00.000+00:00")
                request.set("ToDateTime", "2017-11-03T23:59:00.000+00:00")

                scope = request.getElement("Scope")

                #scope.setChoice("Team") # Team Name
                #scope.setChoice("TradingSystem") # AIM Px#
                scope.setChoice("Uuids")  # UUID

                #scope.setElement("Team", "MyTeamName")
                #scope.setElement("TradingSystem", True) # no need to specify px# this will be picked up based on the login.

                scope.getElement("Uuids").appendValue(1234)  # User's UUID

                #scope.getElement("Uuids").appendValue(12345);
                #scope.getElement("Uuids").appendValue(123456);
                #scope.getElement("Uuids").appendValue(1234567);

                #filter = request.getElement("FilterBy")

                #filter.setChoice("Basket")
                #filter.setChoice("Multileg")
                #filter.setChoice("OrdersAndRoutes")

                #filter.getElement("Basket").appendValue("TESTRJC")
                #filter.getElement("Multileg").appendValue("mymlegId")

                #newOrder = filter.getElement("OrdersAndRoutes").appendElement()
                #newOrder.setElement("OrderId",4292580)
                #newOrder.setElement("RouteId",1)

                print("Request: %s" % request.toString())

                self.requestID = blpapi.CorrelationId()

                session.sendRequest(request, correlationId=self.requestID)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                print >> sys.stderr, ("Error: Service failed to open")
Exemple #29
0
def clientRun(session, options):
    print("Client is starting------")

    if not session.start():
        print("Failed to start client session.")
        return

    if not session.openService(options.service):
        print("Failed to open", options.service)
        return

    service = session.getService(options.service)
    request = service.createRequest("ReferenceDataRequest")

    # append securities to request
    # Add securities to request
    securities = request.getElement("securities")
    for security in options.securities:
        securities.appendValue(security)

    # Add fields to request
    fields = request.getElement("fields")
    for field in options.fields:
        fields.appendValue(field)

    request.set("timestamp", time.time())

    print("Sendind Request:", request)

    eventQueue = blpapi.EventQueue()
    session.sendRequest(
        request, None, blpapi.CorrelationId("AddRequest"), eventQueue)

    while True:
        # Specify timeout to give a chance for Ctrl-C
        event = eventQueue.nextEvent(500)

        if event.eventType() == blpapi.Event.TIMEOUT:
            continue

        print("Client received an event")
        for msg in event:
            with g_mutex:
                if event.eventType() == blpapi.Event.RESPONSE:
                    if msg.hasElement("timestamp"):
                        responseTime = msg.getElementAsFloat("timestamp")
                        print("Response latency =", time.time() - responseTime)
                print(msg)

        if event.eventType() == blpapi.Event.RESPONSE:
            break
def main():
    options = parseCmdLine()

    # Fill SessionOptions
    sessionOptions = blpapi.SessionOptions()
    sessionOptions.setServerHost(options.host)
    sessionOptions.setServerPort(options.port)

    print("Connecting to %s:%d" % (options.host, options.port))

    # Create a Session
    session = blpapi.Session(sessionOptions)

    # Start a Session
    if not session.start():
        print("Failed to start session.")
        return

    if not session.openService("//blp/mktdata"):
        print("Failed to open //blp/mktdata")
        return

    securities = ["IBM US Equity", "VOD LN Equity"]
    gridWindow = GridWindow("SecurityInfo", securities)

    subscriptions = blpapi.SubscriptionList()
    for i, security in enumerate(securities):
        subscriptions.add(security,
                          "LAST_PRICE",
                          "",
                          blpapi.CorrelationId(i))

    session.subscribe(subscriptions)

    try:
        # Process received events
        eventCount = 0
        while(True):
            # We provide timeout to give the chance to Ctrl+C handling:
            event = session.nextEvent(500)
            if event.eventType() == blpapi.Event.SUBSCRIPTION_DATA:
                for msg in event:
                    row = msg.correlationIds()[0].value()
                    gridWindow.processSecurityUpdate(msg, row)

                eventCount += 1
                if eventCount >= options.maxEvents:
                    break
    finally:
        # Stop the session
        session.stop()