def setup(self):
     self.connection = Connection(self.url, self.session)
     # start a connection
     self.connection.start()
     # add a handler to process notifications to the connection
     self.connection.handlers += \
         lambda data: self._logger.debug(
             'Connection: new notification - %s' % data)
     # get hub
     self._hub = self.connection.hub(self.hub_name)
Esempio n. 2
2
def main():
    with Session() as session:
        session.auth = HTTPBasicAuth("known", "user")
        # connection = Connection("http://localhost:16338/signalr", session)
        connection = Connection("http://netmonsterraspisignalr.azurewebsites.net", session)
        # connection = Connection("http://localhost:5000/signalr", session)
        chat = connection.register_hub("raspiGrowHub")

        def print_received_message(name, message):
            print("received: ", message)

        def print_error(error):
            print("error: ", error)

        chat.client.on("addNewMessageToPage", print_received_message)
        # chat.client.on('topicChanged', print_topic)

        connection.error += print_error

        with connection:
            chat.server.invoke("send", "Kris", "Python is here!")
            # chat.server.invoke('setTopic', 'Welcome python!')
            # chat.server.invoke('requestError')
            # chat.server.invoke('send', 'Bye-bye!')

            connection.wait(1)
Esempio n. 3
0
 def _create_signalr_connection(self):
     with cfscrape.create_scraper() as connection:
         conn = Connection(None, connection)
     conn.received += self._on_debug
     conn.error += self.on_error
     corehub = conn.register_hub('coreHub')
     return BittrexConnection(conn, corehub)
Esempio n. 4
0
def main():
    with Session() as session:
        session.auth = HTTPBasicAuth("known", "user")
        connection = Connection("http://localhost:5000/signalr", session)
        chat = connection.register_hub('chat')

        def print_received_message(data):
            print('received: ', data)

        def print_topic(topic, user):
            print('topic: ', topic, user)

        def print_error(error):
            print('error: ', error)

        chat.client.on('newMessageReceived', print_received_message)
        chat.client.on('topicChanged', print_topic)

        connection.error += print_error

        with connection:
            chat.server.invoke('send', 'Python is here')
            chat.server.invoke('setTopic', 'Welcome python!')
            chat.server.invoke('requestError')
            chat.server.invoke('send', 'Bye-bye!')

            connection.wait(1)
Esempio n. 5
0
 def get_signalr_hub(self):
     try:
         self.session = Session()
         self.connection = Connection("http://202.104.118.59:8070/signalr/",
                                      self.session)
         self.hub = self.connection.register_hub('dashBoardHub')
         self.connection.start()
     except Exception as e:
         print(e)
         self.ready = False
 def setup(self):
     self.connection = Connection(self.url, self.session)
     # start a connection
     self.connection.start()
     # add a handler to process notifications to the connection
     self.connection.handlers += \
         lambda data: self._logger.debug(
             'Connection: new notification - %s' % data)
     # get hub
     self._hub = self.connection.hub(self.hub_name)
 def get_signalr_hub(self):
     """
     获取websocket连接
     """
     self.session = Session()
     self.connection = Connection(settings.signalr_hub_info['url'],
                                  self.session)
     self.hub = self.connection.register_hub(
         settings.signalr_hub_info["name"])
     self.connection.start()
Esempio n. 8
0
    def request_order_book(self):
        try:
            with Session() as session:
                connection = Connection(self.url, session)
                self.hub = connection.register_hub(self.hub_name)

                connection.received += self.on_receive

                connection.start()

                while self.order_book_is_received is not True:
                    self.hub.server.invoke(
                        BittrexParameters.QUERY_EXCHANGE_STATE, self.pair_name)
                    connection.wait(
                        5
                    )  # otherwise it shoot thousands of query and we will be banned :(

                connection.close()

                msg = "Got orderbook for Bittrex!"
                log_to_file(msg, SOCKET_ERRORS_LOG_FILE_NAME)
                print(msg)

                return STATUS.SUCCESS

        except Exception as e:
            # log_error_on_receive_from_socket("Bittrex", e)
            msg = "Error during order book retrieval for Bittrex {}".format(
                str(e))
            log_to_file(msg, SOCKET_ERRORS_LOG_FILE_NAME)
            print(msg)

        return STATUS.FAILURE
Esempio n. 9
0
    def configure(self):
        self.apikey_sonarr = settings.sonarr.apikey
        self.connection = Connection(url_sonarr() + "/signalr", self.session)
        self.connection.qs = {'apikey': self.apikey_sonarr}
        sonarr_hub = self.connection.register_hub(
            '')  # Sonarr doesn't use named hub

        sonarr_method = ['series', 'episode']
        for item in sonarr_method:
            sonarr_hub.client.on(item, dispatcher)

        self.connection.exception += self.exception_handler
Esempio n. 10
0
    def connect(self):
        """
        Connects to the signalR server.

        Raises
        ------
        pyhomebroker.exceptions.SessionException
            If the user is not logged in.
        """

        if not self._auth.is_user_logged_in:
            raise SessionException('User is not logged in')

        url = '{}/signalr/hubs'.format(self._auth.broker['page'])

        with rq.Session() as session:
            rq.utils.add_dict_to_cookiejar(session.cookies, self._auth.cookies)

            if self._proxies:
                session.proxies.update(self._proxies)

            session.headers = {'User-Agent': user_agent}

            self._connection = Connection(url, session)
            self._hub = self._connection.register_hub('stockpriceshub')

            self._hub.client.on('broadcast',
                                self.__internal_securities_options_repos)

            self._hub.client.on('sendStartStockFavoritos',
                                self.__internal_personal_portfolio)
            self._hub.client.on('sendStockFavoritos',
                                self.__internal_personal_portfolio)

            self._hub.client.on('sendStartStockPuntas',
                                self.__internal_order_book)
            self._hub.client.on('sendStockPuntas', self.__internal_order_book)

            if self._on_error:
                self._connection.error += self._on_error

            self._connection.exception += self.__on_internal_exception
            self._connection.start()

            self.is_connected = self._connection.is_open

            if self.is_connected and self._on_open:
                self._on_open()

                self.__worker_thread_event = Event()
                self.__worker_thread = Thread(target=self.__worker_thread_run)
                self.__worker_thread.start()
Esempio n. 11
0
 def get_value(self, hub, method):
     self.res = {}
     with Session() as session:
         #create a connection
         connection = Connection(self.url, session)
         chat = connection.register_hub(hub)
         chat.client.on(method, self.update_res)
         connection.start()
         connection.wait(3)
         connection.close()
         return self.res
Esempio n. 12
0
def test_bittrex():
    def process_message(message):
        deflated_msg = decompress(b64decode(message), -MAX_WBITS)
        return loads(deflated_msg.decode())

    def on_receive(**kwargs):
        global order_book_is_received 
        # print "on_receive", kwargs
        if 'R' in kwargs and type(kwargs['R']) is not bool:
            msg = process_message(kwargs['R'])
            if msg is not None:
                order_book_is_received = False
                with open('data.json', 'w') as outfile:
                    json.dump(msg, outfile)
        else:
            if order_book_is_received:
                time.sleep(5)

    def on_public(args):
        # print "on_public", args
        msg = process_message(args)
        if msg is not None:
            print msg

    # create error handler
    def print_error(error):
        print('error: ', error)

    with Session() as session:
        connection = Connection("https://socket.bittrex.com/signalr", session)
        hub = connection.register_hub('c2')

        connection.received += on_receive

        hub.client.on(BittrexParameters.MARKET_DELTA, on_public)
        
        connection.error += print_error

        connection.start()

        while order_book_is_received:
            hub.server.invoke("QueryExchangeState", "BTC-ETH")

        print "Order book should be received at this stage"

        while connection.started:
            hub.server.invoke("SubscribeToExchangeDeltas", "BTC-ETH")
Esempio n. 13
0
    def subscribe(self):

        #
        #       FIXME DBG PART - REMOVE AFTER TESTS
        #

        if self.should_run:
            die_hard("Bittrex another running?")

        msg = "Bittrex - call subscribe!"
        log_to_file(msg, SOCKET_ERRORS_LOG_FILE_NAME)
        print msg

        self.should_run = True

        try:
            with Session() as session:

                self.connection = Connection(self.url, session)
                self.hub = self.connection.register_hub(self.hub_name)

                self.hub.client.on(BittrexParameters.MARKET_DELTA,
                                   self.on_public)

                self.connection.start()

                log_conect_to_websocket("Bittrex")

                while self.connection.started and self.should_run:
                    try:
                        self.hub.server.invoke(
                            BittrexParameters.SUBSCRIBE_EXCHANGE_DELTA,
                            self.pair_name)
                    except Exception as e:
                        log_send_heart_beat_failed("Bittrex", e)

                        # FIXME NOTE - still not sure - connection.wait(1)
                        self.should_run = False

                        break
                    sleep_for(1)
        except Exception as e:
            log_error_on_receive_from_socket("Bittrex", e)

        log_subscription_cancelled("Bittrex")

        self.disconnect()
Esempio n. 14
0
 def run(self, hub, message):
     connection = Connection(self.url, self.session)
     connection.start()
     # get hub
     hub = connection.hub(hub)
     hub.server.invoke('send_message', message)
     connection.close()
Esempio n. 15
0
    def run(self, source=None):
        with Session() as session:
            #create a connection
            self.connection = Connection(self.hub_url, session)

            #connect to the hub
            self.hub  = self.connection.register_hub(self.hub_name)

            # start the connection
            self.connection.start()
                
            def OnProducerChanged(data):
                if self.stop_received is False:
                    print('received: ', data)
                    """
                    Starts emotiv, called upon initialization.
                    """
                    if data == "start":
                        self.running = True

                    elif data == "stop":
                        self.running = False
                        self.stop_received = True
                        print("Emotiv Stopped")


            #receive new chat messages from the hub
            self.hub.client.on(self.hub_event, OnProducerChanged)

            #create error handler
            def print_signalr_error(error):
                print('error: ', error)

            #process errors
            self.connection.error += print_signalr_error

            #hold the connection (annoying way to do it)
            self.lock.acquire()
            while not self.stop_connection:
                self.lock.release()
                self.connection.wait()
                if(self.reader_init):
                    self.hub.server.invoke("Init");
                    self.reader_init = False
                self.lock.acquire()
Esempio n. 16
0
def main():
    r = requests.get("https://api.bittrex.com/api/v1.1/public/getmarkets")
    marketData = r.json()["result"]
    markets = []
    for i in marketData:
        if (i["IsRestricted"] == False):
            markets.append(i["MarketName"])
    createDirectories(markets)
    while (-1):
        try:
            with Session() as session:
                print("Restarting connection!")
                connection = Connection("https://socket.bittrex.com/signalr",
                                        session)
                chat = connection.register_hub('corehub')
                connection.received += handle_received
                connection.error += print_error
                connection.start()

                # You missed this part
                chat.client.on('updateExchangeState', msg_received)
                for i in range(10):
                    for market in markets:
                        print("Querying: " + market)
                        #chat.server.invoke('SubscribeToExchangeDeltas', market)
                        chat.server.invoke('QueryExchangeState', market)
                    connection.wait(60)

                # Value of 1 will not work, you will get disconnected
                #connection.wait(120000)
        except KeyboardInterrupt:
            break
        except:
            continue
Esempio n. 17
0
    async def signalr_connect(self, symbols, queue):
        self.queue = queue
        with cfscrape.create_scraper() as session:
            connection = Connection("https://www.bittrex.com/signalR/",
                                    session)
            chat = connection.register_hub('corehub')
            connection.received += self.signalr_connected
            connection.error += self.error
            await connection.start()

            chat.client.on('updateExchangeState', self.signalr_message)

            for symbol in symbols:
                await chat.server.invoke('SubscribeToExchangeDeltas',
                                         self.market_id(symbol))
                await chat.server.invoke('QueryExchangeState',
                                         self.market_id(symbol))
                market_connection_ids[connection.get_send_counter()] = symbol
Esempio n. 18
0
    def collect_ws(this):
        with Session() as session:
            connection = Connection(this.WS_URL, session=session)
            hub = connection.register_hub('c2')
            connection.start()

            hub.client.on('uS', this.on_message)
            hub.server.invoke('SubscribeToSummaryDeltas')

            connection.wait()
Esempio n. 19
0
 def run(self, hub, message):
     connection = Connection(self.url, self.session)
     connection.start()
     # get hub
     hub = connection.hub(hub)
     hub.server.invoke('send_message', message)
     connection.close()
Esempio n. 20
0
    def run_forever(self,
                    ping_interval=0, ping_timeout=None, ):

        if ping_timeout and ping_interval and ping_interval <= ping_timeout:
            raise logging.warning("Ensure ping_interval > ping_timeout")
        if self.conn:
            raise logging.warning("connection is already opened")
        thread = None
        self.keep_running = True

        try:
            with cfscrape.create_scraper() as connection:
                self.conn = Connection(None, connection)
            self.conn.received += self.r  #
            self.conn.url = 'https://socket-stage.bittrex.com/signalr'
            self.corehub = self.conn.register_hub('coreHub')
            logging.info(MSG_TRY_TO_CONNECT.format('Bittrex',self.conn.url))
            self.conn.start()
            logging.info(MSG_CONNECT_SUCCESS.format('Bittrex',self.conn.url))
            self._callback(self.on_open)

            self.corehub.client.on('updateSummaryState', self.received)
            self.corehub.client.on('updateExchangeState', self.received)

            while self.conn.started:
                if not self.keep_running:
                    break
                self.conn.wait(1)                   #Data will receive when connection is waiting

        except (Exception, KeyboardInterrupt, SystemExit) as e:
            self._callback(self.on_error, e)
        finally:
            if thread and thread.isAlive():
                thread.join()
            self.keep_running = False
            self._callback(self.on_close)
            self.conn = None
            self.corehub = None
class SignalRHubSensor(Sensor):
    def __init__(self, sensor_service, config=None):
        super(SignalRHubSensor, self).__init__(sensor_service=sensor_service,
                                               config=config)
        self._logger = self._sensor_service.get_logger(__name__)
        self.url = config['hub_url']
        self.hub_name = config['hub_name']
        self._trigger_ref = 'signalr.message_received'
        self._hub = None
        self.connection = None
        self.session = None

    def setup(self):
        self.connection = Connection(self.url, self.session)
        # start a connection
        self.connection.start()
        # add a handler to process notifications to the connection
        self.connection.handlers += \
            lambda data: self._logger.debug(
                'Connection: new notification - %s' % data)
        # get hub
        self._hub = self.connection.hub(self.hub_name)

    def message_received(self, message):
        self._logger.debug('Connection: new notification.' % message)
        self._sensor_service.dispatch(trigger=self._trigger_ref,
                                      payload={message: message})

    def run(self):
        self._hub.client.on('message_received',
                            SignalRHubSensor.message_received)

    def cleanup(self):
        # do not receive new messages
        self._hub.client.off('message_received', self.message_received)
        self.connection.close()
Esempio n. 22
0
def sendNewMailRequestInSeparateThread():
    with Session() as session:
        upload_result = uploadImage()

        #create a connection
        connection = Connection(HUB_HOST_URL, session)

        #get PeepneeHub hub
        peepneeHub = connection.register_hub(HUB_NAME)

        peepneeHub.client.on('mailRequestAccepted', mailRequestAccepted)
        peepneeHub.client.on('mailRequestDeclined', mailRequestDeclined)
        peepneeHub.client.on('repeatMailRequest', repeatMailRequest)
        peepneeHub.client.on('updateDefaultOwnerSettings', updateDefaultOwnerSettings)

        #process errors
        connection.error += print_error

        #start a connection
        log("Connection was started", True)
        with connection:
            peepneeHub.server.invoke('newMailRequest', upload_result['link'], "OCR PARSED TEXT")
            connection.wait(16)
            log("Connection to SignalR hub was closed!", True)
class SignalRHubSensor(Sensor):
    def __init__(self, sensor_service, config=None):
        super(SignalRHubSensor, self).__init__(sensor_service=sensor_service,
                                               config=config)
        self._logger = self._sensor_service.get_logger(__name__)
        self.url = config['hub_url']
        self.hub_name = config['hub_name']
        self._trigger_ref = 'signalr.message_received'
        self._hub = None
        self.connection = None
        self.session = None

    def setup(self):
        self.connection = Connection(self.url, self.session)
        # start a connection
        self.connection.start()
        # add a handler to process notifications to the connection
        self.connection.handlers += \
            lambda data: self._logger.debug(
                'Connection: new notification - %s' % data)
        # get hub
        self._hub = self.connection.hub(self.hub_name)

    def message_received(self, message):
        self._logger.debug('Connection: new notification.' % message)
        self._sensor_service.dispatch(trigger=self._trigger_ref,
                                      payload={message: message})

    def run(self):
        self._hub.client.on('message_received',
                            SignalRHubSensor.message_received)

    def cleanup(self):
        # do not receive new messages
        self._hub.client.off('message_received', self.message_received)
        self.connection.close()
Esempio n. 24
0
def signal_r_setup(): 
    with Session() as session:
        #create a connection
        connection = Connection("http://localhost:6658/signalr", session)
        #connection = Connection("https://atbot01.azurewebsites.net/signalr", session)

        #get chat hub
        bot = connection.register_hub('BotControl')
        hub = connection.register_hub('WebRtcHub')

        #start a connection
        connection.start()

        hub.server.invoke('registerBot', 'PyBot')
        print('connected to SignalR hub... connection id: ' + connection.token)
        

        #create new chat message handler
        def print_received_message(data):
            print('received: ', data)
            robot.go(-data['Y'], data['X'])
            bot.server.invoke('sendLocation', data)
            print('sent: ', data)
            

        #receive new chat messages from the hub
        bot.client.on('controllerAt', print_received_message)

        #create error handler
        def print_error(error):
            print('error: ', error)


        #process errors
        connection.error += print_error

        #connection.start()

        #start connection, optionally can be connection.start()
        with connection:

            #post new message
            #bot.server.invoke('sendLocation', 'RaspPi')

            #wait a second before exit
            connection.wait(None) # no timeout
Esempio n. 25
0
def main():
    with Session() as session:
        connection = Connection("https://www.bittrex.com/signalR/", session)
        chat = connection.register_hub('corehub')
        connection.start()

        connection.received += handle_received
        connection.error += print_error

        for market in ["BTC-MEME", "BTC-ANS"]:
            chat.server.invoke('SubscribeToExchangeDeltas', market)
            chat.server.invoke('QueryExchangeState', market)

        while True:
            connection.wait(1)
Esempio n. 26
0
def initSignalrConnection():
    with Session() as session:
        #create a connection
        connection = Connection(HUB_URL, session)

        #get BoongalooGroupsActivityHub hub
        boongalooGroupsActivityHub = connection.register_hub(HUB_NAME)

        #receive new message from the hub
        boongalooGroupsActivityHub.client.on('groupWasLeftByUser',
                                             groupWasLeftByUserHandler)

        #process errors
        connection.error += signalrErrorHandler

        #start a connection
        connection.qs = {'userId': '5b8e69b6-fc13-494d-9228-4215de85254f'}

        print("Connection was started")
        with connection:
            connection.wait(13)
Esempio n. 27
0
class OnlineSignalR(OnlineCore):

    __worker_thread = None
    __worker_thread_event = None

    __personal_portfolio_queue_lock = Lock()
    __personal_portfolio_queue = []
    __securities_options_repos_queue_lock = Lock()
    __securities_options_repos_queue = []
    __order_book_queue_lock = Lock()
    __order_book_queue = []

    def __init__(self,
                 auth,
                 on_open=None,
                 on_personal_portfolio=None,
                 on_securities=None,
                 on_options=None,
                 on_repos=None,
                 on_order_book=None,
                 on_error=None,
                 on_close=None,
                 proxy_url=None):
        """
        Class constructor.

        Parameters
        ----------
        auth : home_broker_session
            An object with the authentication information.
        on_open : function(), optional
            Callable object which is called at opening the signalR connection.
            This function has no argument.
        on_personal_portfolio : function(quotes), optional
            Callable object which is called when personal portfolio data is received.
            This function has 1 argument. The argument is the dataframe with the quotes.
        on_securities : function(quotes), optional
            Callable object which is called when security data is received.
            This function has 1 argument. The argument is the dataframe with the quotes.
        on_options : function(quotes), optional
            Callable object which is called when options data is received.
            This function has 1 argument. The argument is the dataframe with the quotes.
        on_repos : function(quotes), optional
            Callable object which is called when repo data is received.
            This function has 1 argument. The argument is the dataframe with the quotes.
        on_order_book : function(quotes), optional
            Callable object which is called when the order book data (level 2) is received.
            This function has 1 argument. The argument is the dataframe with the quotes.
        on_error : function(exception, connection_lost), optional
            Callable object which is called when we get error.
            This function has 2 arguments.
                The 1st argument is the exception object.
                The 2nd argument is if the connection was lost due to the error.
        on_close : function(), optional
            Callable object which is called when closed the connection.
            This function has no argument.
        proxy_url : str, optional
            The proxy URL with one of the following formats:
                - scheme://user:pass@hostname:port
                - scheme://user:pass@ip:port
                - scheme://hostname:port
                - scheme://ip:port

            Ex. https://john:[email protected]:3128
        """

        self._proxies = {
            'http': proxy_url,
            'https': proxy_url
        } if proxy_url else None
        self._auth = auth
        self._on_open = on_open
        self._on_personal_portfolio = on_personal_portfolio
        self._on_securities = on_securities
        self._on_options = on_options
        self._on_repos = on_repos
        self._on_order_book = on_order_book
        self._on_error = on_error
        self._on_close = on_close

        self._connection = None
        self._hub = None

        self.is_connected = False

########################
#### PUBLIC METHODS ####
########################

    def connect(self):
        """
        Connects to the signalR server.

        Raises
        ------
        pyhomebroker.exceptions.SessionException
            If the user is not logged in.
        """

        if not self._auth.is_user_logged_in:
            raise SessionException('User is not logged in')

        url = '{}/signalr/hubs'.format(self._auth.broker['page'])

        with rq.Session() as session:
            rq.utils.add_dict_to_cookiejar(session.cookies, self._auth.cookies)

            if self._proxies:
                session.proxies.update(self._proxies)

            session.headers = {'User-Agent': user_agent}

            self._connection = Connection(url, session)
            self._hub = self._connection.register_hub('stockpriceshub')

            self._hub.client.on('broadcast',
                                self.__internal_securities_options_repos)

            self._hub.client.on('sendStartStockFavoritos',
                                self.__internal_personal_portfolio)
            self._hub.client.on('sendStockFavoritos',
                                self.__internal_personal_portfolio)

            self._hub.client.on('sendStartStockPuntas',
                                self.__internal_order_book)
            self._hub.client.on('sendStockPuntas', self.__internal_order_book)

            if self._on_error:
                self._connection.error += self._on_error

            self._connection.exception += self.__on_internal_exception
            self._connection.start()

            self.is_connected = self._connection.is_open

            if self.is_connected and self._on_open:
                self._on_open()

                self.__worker_thread_event = Event()
                self.__worker_thread = Thread(target=self.__worker_thread_run)
                self.__worker_thread.start()

    def disconnect(self):
        """
        Disconnects from the signalR server.

        Raises
        ------
        pyhomebroker.exceptions.SessionException
            If the user is not logged in.
            If the connection or hub is not assigned.
        """

        if not self._auth.is_user_logged_in:
            raise SessionException('User is not logged in')

        if not self._connection or not self._hub:
            raise SessionException('Connection or hub is not assigned')

        if self._connection.is_open:
            self._connection.close()

        self._connection = None
        self._hub = None

        self.is_connected = False

        if self._on_close:
            self._on_close()

        self.__worker_thread_stop()

    def join_group(self, group_name):
        """
        Subscribe to a group to start receiving event notifications.

        Raises
        ------
        pyhomebroker.exceptions.SessionException
            If the user is not logged in.
            If the connection or hub is not assigned.
            If the connection is not open.
        """

        if not self._auth.is_user_logged_in:
            raise SessionException('User is not logged in')

        if not self._connection or not self._hub:
            raise SessionException('Connection or hub is not assigned')

        if not self._connection.is_open:
            raise SessionException('Connection is not open')

        self._hub.server.invoke('JoinGroup', group_name)

    def quit_group(self, group_name):
        """
        Unsubscribe from a group to stop receiving event notifications.

        Raises
        ------
        pyhomebroker.exceptions.SessionException
            If the user is not logged in.
            If the connection or hub is not assigned.
            If the connection is not open.
        """

        if not self._auth.is_user_logged_in:
            raise SessionException('User is not logged in')

        if not self._connection or not self._hub:
            raise SessionException('Connection or hub is not assigned')

        if not self._connection.is_open:
            raise SessionException('Connection is not open')

        self._hub.server.invoke('QuitGroup', group_name)

#########################
#### PRIVATE METHODS ####
#########################

    def __worker_thread_run(self):

        while not self.__worker_thread_event.wait(0.1):

            with self.__personal_portfolio_queue_lock:
                data = self.__personal_portfolio_queue
                self.__personal_portfolio_queue = []
            self.__process_personal_portfolio(data)

            with self.__securities_options_repos_queue_lock:
                data = self.__securities_options_repos_queue
                self.__securities_options_repos_queue = []
            self.__process_securities_options_repos(data)

            with self.__order_book_queue_lock:
                data = self.__order_book_queue
                self.__order_book_queue = []
            self.__process_order_books(data)

    def __worker_thread_stop(self):

        if self.__worker_thread_event and not self.__worker_thread_event.is_set(
        ):
            self.__worker_thread_event.set()
            self.__worker_thread.join()
            self.__worker_thread_event = None
            self.__worker_thread = None

    def __process_personal_portfolio(self, data):

        try:  #  Handle any exception processing the information or triggered by the user code
            if not self._on_personal_portfolio or len(data) == 0:
                return

            ts = time.time()

            # Remove duplicates from Json Document
            data_filter = {}
            for item in data:
                data_filter[item['Symbol'] + '-' + item['Term']] = item
            data = list(data_filter.values())

            df_portfolio = self.process_personal_portfolio(data)
            ts_pp_process = time.time()

            df_order_book = self.process_order_books(data)
            ts_ob_process = time.time()

            self._on_personal_portfolio(df_portfolio, df_order_book)
            ts_event = time.time()

            logging.debug(
                "[HOMEBROKER: SIGNALR] Performance [__process_personal_portfolio (P: {} - OB: {})]: (PP Proc: {:.3f}s - OB Proc: {:.3f}s - Notif: {:.3f}s)"
                .format(len(df_portfolio.index), len(df_order_book.index),
                        ts_pp_process - ts, ts_ob_process - ts_pp_process,
                        ts_event - ts_ob_process))
        except Exception as ex:
            if self._on_error:
                try:  # Catch user exceptions inside the except block (Inception Mode Activated :D)
                    self._on_error(ex, False)
                except:
                    pass

    def __process_securities_options_repos(self, data):

        try:  # Handle any exception processing the information or triggered by the user code
            if len(data) == 0:
                return

            # Remove duplicates from Json Document
            data_filter = {}
            for item in data:
                data_filter[item['Symbol'] + '-' + item['Term']] = item
            data = list(data_filter.values())

            df = pd.DataFrame(data) if data else pd.DataFrame()

            df_repo = df[df.Group == 'cauciones-'].copy()
            df_options = df[df.Group == 'opciones-'].copy()
            df_securities = df[(df.Group != 'cauciones-')
                               & (df.Group != 'opciones-')].copy()

            if len(df_repo) and self._on_repos:
                ts = time.time()

                repos = self.process_repos(df_repo)
                ts_process = time.time()

                self._on_repos(repos)
                ts_event = time.time()

                logging.debug(
                    "[HOMEBROKER: SIGNALR] Performance [__process_securities_options_repos (R: {})]: (Proc: {:.3f}s - Notif: {:.3f}s)"
                    .format(len(repos.index), ts_process - ts,
                            ts_event - ts_process))

            if len(df_options) and self._on_options:
                ts = time.time()

                options = self.process_options(df_options)
                ts_process = time.time()

                self._on_options(options)
                ts_event = time.time()

                logging.debug(
                    "[HOMEBROKER: SIGNALR] Performance [__process_securities_options_repos (O: {})]: (Proc: {:.3f}s - Notif: {:.3f}s)"
                    .format(len(options.index), ts_process - ts,
                            ts_event - ts_process))

            if len(df_securities) and self._on_securities:
                ts = time.time()

                securities = self.process_securities(df_securities)
                ts_process = time.time()

                self._on_securities(securities)
                ts_event = time.time()

                logging.debug(
                    "[HOMEBROKER: SIGNALR] Performance [__process_securities_options_repos (S: {})]: (Proc: {:.3f}s - Notif: {:.3f}s)"
                    .format(len(securities.index), ts_process - ts,
                            ts_event - ts_process))
        except Exception as ex:
            if self._on_error:
                try:  # Catch user exceptions inside the except block (Inception Mode Activated :D)
                    self._on_error(ex, False)
                except:
                    pass

    def __process_order_books(self, data):

        try:  # Handle any exception processing the information or triggered by the user code
            if not self._on_order_book or len(data) == 0:
                return

            ts = time.time()

            # Remove duplicates from Json Document
            data_filter = {}
            for item in data:
                data_filter[item['Symbol'] + '-' + item['Term']] = item
            data = list(data_filter.values())

            order_books = self.process_order_books(data)
            ts_process = time.time()

            self._on_order_book(order_books)
            ts_event = time.time()

            logging.debug(
                "[HOMEBROKER: SIGNALR] Performance [__process_order_books ({})]: (Proc: {:.3f}s - Notif: {:.3f}s)"
                .format(len(data), ts_process - ts, ts_event - ts_process))
        except Exception as ex:
            if self._on_error:
                try:  # Catch user exceptions inside the except block (Inception Mode Activated :D)
                    self._on_error(ex, False)
                except:
                    pass

#############################################
#### PRIVATE METHODS - SIGNALR CALLBACKS ####
#############################################

    def __internal_personal_portfolio(self, data):

        if not data:
            return

        if not isinstance(data, list):
            data = [data]

        with self.__personal_portfolio_queue_lock:
            self.__personal_portfolio_queue.extend(data)

    def __internal_securities_options_repos(self, data):

        if not data:
            return

        if not isinstance(data, list):
            data = [data]

        with self.__securities_options_repos_queue_lock:
            self.__securities_options_repos_queue.extend(data)

    def __internal_order_book(self, data):

        if not data:
            return

        if not isinstance(data, list):
            data = [data]

        with self.__order_book_queue_lock:
            self.__order_book_queue.extend(data)

    def __on_internal_exception(self, exception_type, value, traceback):

        self.__worker_thread_stop()

        if self._on_error:
            try:  # Catch user exceptions inside the except block (Inception Mode Activated :D)
                self._on_error(exception_type(value), True)
            except:
                pass
Esempio n. 28
0
class SignalR(object):

    def __init__(self, header=None,
                 on_open=None, on_message=None, on_error=None,
                 on_close=None, ):

        self.header = header if header is not None else []
        self.on_open = on_open
        self.on_message = on_message
        self.on_error = on_error
        self.on_close = on_close
        self.keep_running = False
        self.conn = None
        self.corehub = None
        self.cps = []

    def r(self, **kwargs):
        msg = kwargs
        if 'R' in msg and type(msg['R']) is not bool:
            if 'MarketName' in msg['R'] and msg['R']['MarketName'] is None:
                msg['R']['MarketName'] = self.cps[0]  # MarketName is None Problem
                self.cps.pop(0)                       # message FIFO >?
                del msg['R']['Fills']
                self.received(kwargs)

    def received(self, data):
        self._callback(self.on_message, data)

    def subscribe(self, channel, cp='BTC-USDT'):
        self.cps.append(cp)
        if channel == 'ticker':
            self.corehub.server.invoke('SubscribeToSummaryDeltas')
        elif channel == 'trader':
            self.corehub.server.invoke('SubscribeToExchangeDeltas', cp)
            self.corehub.server.invoke('queryExchangeState', cp)

    def close(self):
        self.keep_running = False
        if self.conn:
            self.conn.close
        self._callback(self.on_close)

    def run_forever(self,
                    ping_interval=0, ping_timeout=None, ):

        if ping_timeout and ping_interval and ping_interval <= ping_timeout:
            raise logging.warning("Ensure ping_interval > ping_timeout")
        if self.conn:
            raise logging.warning("connection is already opened")
        thread = None
        self.keep_running = True

        try:
            with cfscrape.create_scraper() as connection:
                self.conn = Connection(None, connection)
            self.conn.received += self.r  #
            self.conn.url = 'https://socket-stage.bittrex.com/signalr'
            self.corehub = self.conn.register_hub('coreHub')
            logging.info(MSG_TRY_TO_CONNECT.format('Bittrex',self.conn.url))
            self.conn.start()
            logging.info(MSG_CONNECT_SUCCESS.format('Bittrex',self.conn.url))
            self._callback(self.on_open)

            self.corehub.client.on('updateSummaryState', self.received)
            self.corehub.client.on('updateExchangeState', self.received)

            while self.conn.started:
                if not self.keep_running:
                    break
                self.conn.wait(1)                   #Data will receive when connection is waiting

        except (Exception, KeyboardInterrupt, SystemExit) as e:
            self._callback(self.on_error, e)
        finally:
            if thread and thread.isAlive():
                thread.join()
            self.keep_running = False
            self._callback(self.on_close)
            self.conn = None
            self.corehub = None

    def _callback(self, callback, *args):
        if callback:
            try:
                callback(self, *args)
            except Exception as e:
                logging.error("error from callback {}: {}".format(callback, e))
Esempio n. 29
0
from requests import Session
from signalr import Connection

with Session() as session:
    #create a connection
    connection = Connection("http://localhost:5000/signalr", session)

    #get chat hub
    chat = connection.register_hub('chat')

    #start a connection
    connection.start()

    #create new chat message handler
    def print_received_message(data):
        print('received: ', data)

    #create new chat topic handler
    def print_topic(topic, user):
        print('topic: ', topic, user)

    #create error handler
    def print_error(error):
        print('error: ', error)

    #receive new chat messages from the hub
    chat.client.on('newMessageReceived', print_received_message)

    #change chat topic
    chat.client.on('topicChanged', print_topic)
Esempio n. 30
0
conf_thres=0.8

# Load model and weights
model = Darknet(config_path, img_size=img_size)
model.load_weights(weights_path)
model.cuda()
model.eval()
classes = utils.load_classes(class_path)
Tensor = torch.cuda.FloatTensor


# In[59]:


session = Session()
connection = Connection("http://127.0.0.1:8088/signalr", session)
conn = connection.register_hub('step5')
connection.start()


# In[54]:


def detect_image(img):
    # scale and pad image
    ratio = min(img_size/img.size[0], img_size/img.size[1])
    imw = round(img.size[0] * ratio)
    imh = round(img.size[1] * ratio)
    img_transforms=transforms.Compose([transforms.Resize((imh,imw)),
         transforms.Pad((max(int((imh-imw)/2),0), 
              max(int((imw-imh)/2),0), max(int((imh-imw)/2),0),
Esempio n. 31
0
class EmotivConnection(object):
    """
    Read data from file or hid. Only CSV for now.
    """

    def __init__(self):
        self.hub_url = 'http://localhost:51560/signalr'
        self.hub_name = 'EmokitHub'
        self.connection = None
        self.hub = None
        self.hub_event = 'OnProducerChanged'
        self.stop_connection = False
        self.connection_thread = Thread(target=self.run)
        self.running = False
        self.stop_received = False;
        self.reader_init = False
        self.lock = Lock()

    def start(self):
        """
        Starts the connection thread.
        """
        self.stopped = False
        self.connection_thread.start()

    def stop(self):
        """
        Stops the reader thread.
        """
        self.lock.acquire()
        self._stop_signal = True
        self.lock.release()

    def run(self, source=None):
        with Session() as session:
            #create a connection
            self.connection = Connection(self.hub_url, session)

            #connect to the hub
            self.hub  = self.connection.register_hub(self.hub_name)

            # start the connection
            self.connection.start()
                
            def OnProducerChanged(data):
                if self.stop_received is False:
                    print('received: ', data)
                    """
                    Starts emotiv, called upon initialization.
                    """
                    if data == "start":
                        self.running = True

                    elif data == "stop":
                        self.running = False
                        self.stop_received = True
                        print("Emotiv Stopped")


            #receive new chat messages from the hub
            self.hub.client.on(self.hub_event, OnProducerChanged)

            #create error handler
            def print_signalr_error(error):
                print('error: ', error)

            #process errors
            self.connection.error += print_signalr_error

            #hold the connection (annoying way to do it)
            self.lock.acquire()
            while not self.stop_connection:
                self.lock.release()
                self.connection.wait()
                if(self.reader_init):
                    self.hub.server.invoke("Init");
                    self.reader_init = False
                self.lock.acquire()

    def __exit__(self, exc_type, exc_value, traceback):
        self.stop()
        if self.connection_thread:
            self.connection_thread.close()
Esempio n. 32
0
from requests import Session
from signalr import Connection

with Session() as session:
    #create a connection
    connection = Connection("http://localhost:3000/signalr", session)

    print(connection)

    #get chat hub
    chat = connection.register_hub('chatHub')

    print(chat)

    #start a connection
    connection.start()

    #create new chat message handler
    def print_received_message(data):
        print('received: ', data)

    #create new chat topic handler
    def print_topic(topic, user):
        print('topic: ', topic, user)

    #create error handler
    def print_error(error):
        print('error: ', error)

    #receive new chat messages from the hub
    chat.client.on('newMessageReceived', print_received_message)
Esempio n. 33
0
from requests import Session
from signalr import Connection

with Session() as session:
    #create a connection
    connection = Connection(
        "http://likkleapi-staging.azurewebsites.net/signalr", session)

    #get PeepneeHub hub
    peepneeHub = connection.register_hub('PeepneeHub')

    #define message handlers
    def mailRequestAccepted():
        print('OMG! Mail was accepted.')

    def mailRequestDeclined():
        print('Hmm! Mail was declined.')

    def repeatMailRequest():
        print('What? Repeat mail request.')

    def updateDefaultOwnerSettings(openAfterDefaultTime,
                                   secondsToDefaultBehaviour):
        print(
            "Kewl? Update settings to openAfterDefaultTime: {0} and secondsToDefaultBehaviour: {1}"
            .format(openAfterDefaultTime, secondsToDefaultBehaviour))

    def print_error(error):
        print('error: ', error)

    peepneeHub.client.on('mailRequestAccepted', mailRequestAccepted)
Esempio n. 34
0
File: isa.py Progetto: gkrabbe/isa
conf_thres = 0.8

# Load model and weights
model = Darknet(config_path, img_size=img_size)
model.load_weights(weights_path)
model.cuda()
model.eval()
classes = utils.load_classes(class_path)
Tensor = torch.cuda.FloatTensor

print("3")

input("press ENTER to start VISIO")

session = Session()
connection = Connection("http://127.0.0.1:8088/signalr", session)
chat = connection.register_hub('isaHub')
connection.start()

print("started")

print("4")


def detect_image(img):
    # scale and pad image
    ratio = min(img_size / img.size[0], img_size / img.size[1])
    imw = round(img.size[0] * ratio)
    imh = round(img.size[1] * ratio)
    img_transforms = transforms.Compose([
        transforms.Resize((imh, imw)),
Esempio n. 35
0
from gevent import monkey
monkey.patch_all()

from requests import Session
from signalr import Connection

with Session() as session:
    # create a connection
    connection = Connection("http://192.168.240.100:8080", session)

    #get chat hub
    chat = connection.register_hub('chat')

    #start a connection
    connection.start()
    print("connect start")

    #create new chat message handler
    def print_received_message(data):
        print('received: ', data)

    #create new chat topic handler
    def print_topic(topic, user):
        print('topic: ', topic, user)

    #create error handler
    def print_error(error):
        print('error: ', error)

    #receive new chat messages from the hub
    chat.client.on('newMessageReceived', print_received_message)