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)
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
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)
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
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)
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
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()
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
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)
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")
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
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)
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)
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)
def signal_r_setup(): with Session() as session: # create a connection #connection = Connection("https://atbot01.azurewebsites.net/signalr", session) connection = Connection("https://dube.azurewebsites.net/signalr", session) #connection = Connection("http://localhost:6658/signalr", session) # get control hub bot = connection.register_hub('BotControl') hub = connection.register_hub('WebRtcHub') # start a connection connection.start() t = Timer(.1, RHANDLER.stop) hub.server.invoke('registerBot', 'PyBot') print('connected to SignalR hub... connection id: ' + connection.token) # create new control message handler def handle_bot_control_request(data): print('received: ', data) try: command = data['Command'] #RHANDLER.get_sensors() if command == "turn": RHANDLER.turn(data) elif command == "rise": RHANDLER.rise(data) else: #RHANDLER.go(data) RHANDLER.go_direct(data) t.cancel() t = Timer(0.50, RHANDLER.stop) t.start() except: pass def send_telemetry(): cnt = 0 while True: cnt = cnt + 1 j = RHANDLER.get_sensors() bot.server.invoke('sendBotTelemetry', j) time.sleep(5) # receive new chat messages from the hub bot.client.on('controllerAt', handle_bot_control_request) thread = Thread(target=send_telemetry, args=()) thread.daemon = True thread.start() # create error handler def print_error(error): print('error: ', error) # process errors connection.error += print_error # wait before exit connection.wait(None)
# 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)), transforms.Pad((max(int(
# image_upload.py from requests import Session from signalr import Connection with Session() as session: # create a connection # connection = Connection(get_server_url(), session) connection = Connection("http://localhost:5001", session) # get chat hub chat = connection.register_hub('http://localhost:5001/chatHub') # device = connection.send("message") # 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('ReceivedMessage', print_received_message)
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))
# 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), max(int((imw-imh)/2),0)), (128,128,128)),
def signalRTest(): # monkey.patch_all() # from requests.packages.urllib3.util.ssl_ import create_urllib3_context # create_urllib3_context() with Session() as session: # create a connection # connection = Connection("http://tvbetapi.net/mainfeed", session) # connection = Connection("http://192.168.212.172:11009/mainfeed", session) # connection = Connection("http://192.168.212.172:9005/mainfeed", session) # connection = Connection("http://localhost:11009/mainfeed", session) # connection = Connection("http://localhost:30258/mainfeed", session) # connection = Connection("http://localhost:30258/feedhub", session) # connection = Connection("http://localhost:14507/hubs", session) # connection = Connection("http://localhost:44312/hubs", session) # connection = Connection("http://192.168.212.172:11011/hubs", session) connection = Connection("http://192.168.212.172:11993/hubs", session) # connection = Connection("http://192.168.212.172:9005/feedhub", session) # get chat hub # feedHub = connection.register_hub('mainfeed') feedHub = connection.register_hub('FeedHub') # start a connection connection.start() # create new chat message handler def print_received_message(data): t = json.dumps(data) temp = json.loads(t) print(temp) # if temp['NI'] != 1: # print(temp) # if temp['NI'] == 8: # print('LastHands: ', temp['D']['LH']) # print('Hands: ', temp['D']['H']) # print('------') # create error handler def print_error(error): print('error: ', error) # receive new chat messages from the hub # feedHub.client.on('addMessage', print_received_message) # feedHub.client.on('addMessage', print_received_message) feedHub.client.on('TimingSubscribe', print_received_message) feedHub.client.on('VideoGamesSubscribe', print_received_message) feedHub.client.on('GamesInfoSubscribe', print_received_message) feedHub.client.on('GamesSubscribe', print_received_message) feedHub.client.on('GamesLastResultsSubscribe', print_received_message) feedHub.client.on('GamesStatisticsSubscribe', print_received_message) feedHub.client.on('GamesEventsSubscribe', print_received_message) feedHub.client.on('PromterGameSubscribe', print_received_message) # # change chat topic # chat.client.on('topicChanged', print_topic) # process errors connection.error += print_error money = 10 # start connection, optionally can be connection.start() with connection: # post new message # feedHub.server.invoke('send', '{"M":14,"GT":5}') # SubscribeOnGame # feedHub.server.invoke('send', '{"M":2,"GT":4,"C":"EUR","CID":46,"CG":5,"L":"en"}') # feedHub.server.invoke('send', '{"M":3,"GT":3,"C":"EUR","CI":127,"CG":3,"L":"en"}') # SubOnGame # feedHub.server.invoke('send', '{"M":16,"GID":90018722430,"CID":35,"L":"en"}') # feedHub.server.invoke('send', '{"M":17,"CI":192,"GID":30001947193,"GT":3,"L":"ru"}') # feedHub.server.invoke('send', '{"M":20,"GID":50007287757,"GT":5}') # SubscribeOnGameStatistic feedHub.server.invoke('SubscribeOnTiming', [2]) # feedHub.server.invoke('SubscribeOnVideoGames', [2], 2026) # feedHub.server.invoke('SubscribeOnGamesInfo', 2, 3) # feedHub.server.invoke('SubscribeOnPromterGame', 5) # feedHub.server.invoke('SubscribeOnGamesLastResults', 2, 3) # feedHub.server.invoke('SubscribeOnGamesStatistics', 6) # feedHub.server.invoke('SubscribeOnGames', [{"i": 6703045, "t": 5}], 46) # feedHub.server.invoke('SubscribeOnCashDeskGames', [{"i": 90000037378, "t": 2}], 127) # feedHub.server.invoke('SubscribeOnCashDeskGamesEvents', [{"i": 131197, "t": 7, "e": [{"t": 123, "p": ["175.5"]}, {"t": 2169, "p": ["-1", "0"]}]}], 127, 0) # SubscribeOnPromterGame # feedHub.server.invoke('send', '{"M":21,"GT":2,"CI":121,"CE":15,"EM":2,"EI":[{"ET":21,"P":[1]},{"ET":4043,"P":[1,2,3,4,5,6]},{"ET":23,"P":[18.5]},{"ET":30,"P":[]}]}') # feedHub.server.invoke('send', '{"M": 21,"GT": 2,"CI":121,"CE":30,"EM":1,"EI":[{"ET":21,"P":["1"]}]}') # feedHub.server.invoke('send', '{"M":8,"GT":3}') # feedHub.server.invoke('send', '{"M":9,"CID":46}') # feedHub.server.invoke('send', '{"GTS":[2],"C":"EUR","L":"en","PM":0.05,"M":19}') # feedHub.server.invoke('send', '{"M":4,"GT":2,"CG":2}') # change chat topic # chat.server.invoke('setTopic', 'Welcome python!') # invoke server method that throws error # chat.server.invoke('requestError') # chat.server.invoke('send', 'Bye-bye!') # wait a second before exit connection.wait(None)
class OnlineSignalR: 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(error), optional Callable object which is called when we get error. This function has 1 arguments. The argument is the exception object. 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) 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() 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() 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 __internal_personal_portfolio(self, data): try: # Handle any exception processing the information or triggered by the user code if self._on_personal_portfolio: if data and not isinstance(data, list): data = [data] df = pd.DataFrame(data if data else pd.DataFrame()) self._on_personal_portfolio(helper.process_personal_portfolio(df)) except Exception as ex: if self._on_error: try: # Catch user exceptions inside the except block (Inception Mode Activated :D) self._on_error(ex) except: pass def __internal_securities_options_repos(self, data): try: # Handle any exception processing the information or triggered by the user code df = pd.DataFrame(data) if data else pd.DataFrame() df_repo = df[df.Group == 'cauciones-'] df_options = df[df.Group == 'opciones-'] df_securities = df[(df.Group != 'cauciones-') & (df.Group != 'opciones-')] if len(df_repo) and self._on_repos: self._on_repos(helper.process_repos(df_repo)) if len(df_options) and self._on_options: self._on_options(helper.process_options(df_options)) if len(df_securities) and self._on_securities: self._on_securities(helper.process_securities(df_securities)) except Exception as ex: if self._on_error: try: # Catch user exceptions inside the except block (Inception Mode Activated :D) self._on_error(ex) except: pass def __internal_order_book(self, data): try: # Handle any exception processing the information or triggered by the user code if self._on_order_book and data: symbol = data['Symbol'] settlement = data['Term'] if data['StockDepthBox'] and data['StockDepthBox']['PriceDepthBox']: df_buy = pd.DataFrame(data['StockDepthBox']['PriceDepthBox']['BuySide']) df_sell = pd.DataFrame(data['StockDepthBox']['PriceDepthBox']['SellSide']) else: df_buy = pd.DataFrame() df_sell = pd.DataFrame() self._on_order_book(helper.process_order_book(symbol, settlement, df_buy, df_sell)) except Exception as ex: if self._on_error: try: # Catch user exceptions inside the except block (Inception Mode Activated :D) self._on_error(ex) except: pass def __on_internal_exception(self, exception_type, value, traceback): if self._on_error: self._on_error(exception_type(value))
class ProcessData(threading.Thread): def __init__(self): super().__init__() self.dic = {} self.last_transform_time = self.now self.vibData_cache = [] self.raw_vibData_cache = [] self.load_cache = [] self.pre_data = None self.user_settings = {} self.feed = 0 self.rspeed = 0 self.tool_num = 0 self.load = 0 self.tool_hp = 0 @property def now(self): return datetime.datetime.now() @property def now_str(self): return self.now.strftime(settings.DATETIME_PATTERN) def clothes(blanking_time, flag=False): """ 限制函数的执行间隔 参数 blanking_time: 间隔时间 flag: 如果为True 将在指定时间后执行 否则立马执行 """ def decorate(func): @wraps(func) def ware(self, *args, **kwargs): last_time = self.dic.get(func) if not last_time: ret = None if not flag: ret = func(self, *args, **kwargs) self.dic[func] = self.now return ret elif (self.now - last_time) >= timedelta(milliseconds=blanking_time): self.dic[func] = self.now return func(self, *args, **kwargs) return ware return decorate def setup(self): print("正在准备中。。。") try: self.get_mangodb_connect() # self.get_mysql_connect() # self.get_signalr_hub() self.ready = True except Exception as e: print(e) self.ready = False def get_mangodb_connect(self): """ 获取mongodb连接 """ self.mangodb_connect = pymongo.MongoClient( settings.mangodb_info['host'], serverSelectionTimeoutMS=settings.mangodb_info['connect_timeoutMS'] ) dblist = self.mangodb_connect.list_database_names() def get_mysql_connect(self): """ 获取上传刀具健康度的mysql连接 """ self.mysql_connect = pymysql.connect(**settings.hp_mysql_info) self.cursor = self.mysql_connect.cursor() 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() @clothes(settings.VIBDATA_DB_GET_BLANKING_TIME) def prepare_vibrationData(self): """ 每个一秒钟从数据库中获取一次振动数据并处理成相应格式 """ origin_data = self.get_origin_vibrationData() self.process_vibrationData(origin_data) self.make_vibDate_cache() def get_origin_vibrationData(self, limit=settings.VIBDATA_COUNT): """ 从数据库中获得原始数据 """ cols = self.mangodb_connect["VibrationData"]["Sensor01"].find( {}, sort=[('_id', pymongo.DESCENDING)], limit=limit) return list(cols)[::-1] def process_vibrationData(self, db_data): """ 把数据库请求得到的数据处理成对应结果 通过self.pre_data存放 """ data = [] for item in db_data: data.extend(item['zdata']) self.pre_data = data return data @clothes(200) def prepare_machineInfo(self): origin_machineinfo = self.get_origin_machineinfo() self.set_machineinfo(origin_machineinfo) self.make_load_cache() def make_load_cache(self): self.load_cache.append(self.load) @clothes(3000, flag=True) def 发送负载数据到云端(self): print("发送负载到云端%s" % self.load_cache) self.load_cache = [] def get_origin_machineinfo(self): return {"Feed": 6000, "RSpeed": 8000, "tool_num": "T01", 'load': 0.5} def set_machineinfo(self, origin_machineinfo): self.feed = origin_machineinfo["Feed"] self.rspeed = origin_machineinfo["RSpeed"] self.tool_num = origin_machineinfo["tool_num"] self.load = origin_machineinfo["load"] self.set_machineinfo_from_file() def set_machineinfo_from_file(self): """ 获取并设定用户提供的机台刀具信息 """ self.user_settings = { "T01": { "feed": 6000, "rspeed": 8000, "model": 1, "var1": 8000, "var2": 8000, }, "T02": { "feed": 8000, "rspeed": 8000, "model": 2, "var1": 8000, "var2": 8000, } } def make_vibDate_cache(self): """ 把振动数据缓存起来 """ if not self.判断刀具是否转向(): self.vibData_cache.append(self.pre_data) self.raw_vibData_cache.extend(self.pre_data) def 判断刀具是否转向(self): if self.tool_num in self.user_settings and ( self.user_settings[self.tool_num]["feed"] != self.feed or self.user_settings[self.tool_num]["rspeed"] != self.rspeed): return True pass @clothes(settings.RAWVIBDATA_UPLOAD_BLANKING_TIME) def 发送振动数据到云端(self): self.处理振动数据() print("发送振动数据到云端%s" % self.processed_raw_vibData) self.raw_vibData_cache = [] def 处理振动数据(self): self.processed_raw_vibData = self.raw_vibData_cache[:60] @clothes(settings.TOOLHEALTH_COMPUTE_BLANKING_TIME, True) def 处理健康度(self): self.运行对应算法计算健康度() self.发送健康度到云端() self.健康度报警() self.clean_vibdata_cache() pass def 健康度报警(self): print("健康度报警") def 运行对应算法计算健康度(self): model = self.user_settings[self.tool_num]["model"] ret = self.计算健康度(self.vibData_cache) self.tool_hp = ret def 计算健康度(self, data): return 1 def 发送健康度到云端(self): print("发送到云端:健康度->%s,刀具->%s" % (self.tool_hp, self.tool_num)) def clean_vibdata_cache(self): self.vibData_cache = [] @clothes(1000) def show_info(self): """ 显示当前算法运行状况 """ print( "当前时间:{0},上次计算健康度时间时间:{1},当前机台->加工刀具:{2},转速:{3},进给:{4},负载:{5},当前健康度:{6},当前振动数据:{7},当前振动缓存数据{8},当前健康度缓存数据{9}" .format(self.now_str, self.last_transform_time, self.tool_num, self.rspeed, self.feed, self.load, self.tool_hp, len(self.pre_data), len(self.raw_vibData_cache), self.vibData_cache[0])) def run(self) -> None: """ 每1秒获取一次数据 每次10条 间隔100毫秒 """ while 1: self.setup() while self.ready: self.prepare_vibrationData() self.prepare_machineInfo() self.处理健康度() self.发送振动数据到云端() self.发送负载数据到云端() self.show_info() time.sleep(0.1) if not self.ready: print("五秒后重试") time.sleep(5)
class ProcessVibData(threading.Thread): def __init__(self, machine_num, tool_num): super().__init__() self.machine_num = machine_num self.ready = False self.tool_num = tool_num self.last_computed_time = self.now def setup(self): print("正在准备中。。。") self.get_mangodb_connect() self.get_mysql_connect() self.get_signalr_hub() self.ready = True pass def get_mangodb_connect(self): try: self.mangodb_connect = pymongo.MongoClient( settings2.mangodb_info['host'], serverSelectionTimeoutMS=settings2. mangodb_info['connect_timeoutMS']) except Exception as e: print(e) self.ready = False def get_mysql_connect(self): """ 获取上传刀具健康度的mysql连接 """ try: self.mysql_connect = pymysql.connect(**settings2.hp_mysql_info) self.cursor = self.mysql_connect.cursor() except Exception as e: print(e) self.ready = False 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 input_vibration(self): """ 输入振动数据 """ pass def get_vibdata_from_database(self, limit=10): ''' 获取振动数据 return: {'_id': ObjectId('601147a535483a2b907e8670'), 'time': '2021-01-27-18-59-49-562', 'xdata': [400个点], 'ydata': [400个点], 'zdata': [400个点]} ''' cols = self.mangodb_connect["VibrationData"]["Sensor01"].find( {}, sort=[('_id', pymongo.DESCENDING)], limit=limit) return list(cols)[::-1] def process_data(self): """ 处理输入数据 """ pass def process_origin_vibdata(self, data): """ 处理振动数据 把数据库中振动数据,转换为矩阵形式输出 [[x1,y1,z1],[x2,y2,z2]...[xn,yn,zn]] """ xdata = [] ydata = [] zdata = [] for i in data: xdata.extend(i['xdata']) ydata.extend(i['ydata']) zdata.extend(i['zdata']) return xdata, ydata, zdata def reduce_vibdata_fre(self, zdata): """ 降低振动数据频率 """ return zdata[:60] @property def now(self): return datetime.datetime.now() def now_str(self): return self.now.strftime(settings2.OUTPUT_FILENAME_PATTERN) def put_vibdata_to_cloud(self, data): companyNo = "CMP20210119001" deviceNo = '0001' try: self.hub.server.invoke( "broadcastDJJK_Working", companyNo, deviceNo, self.now.strftime(settings2.OUTPUT_FILENAME_PATTERN), data) print("发送%s数据到云端" % data) except Exception as e: print(e) self.ready = False def compute_tool_hp(self): self.last_computed_time = self.now db_data = self.get_vibdata_from_database(limit=60) data = [] for item in db_data: fline = np.array(item['zdata']) tem = sqrt(np.sum(fline**2) / len(fline)) data.append(tem) data = np.array(data) data = 1 / (1 + log(data.mean(), 10e12)) return data def test_put_hp_to_mysql(self, val): self.cursor.execute( "insert into test01(snap, hp) values('{0}', {1})".format( self.now_str, val)) self.mysql_connect.commit() def run(self) -> None: """ 每1秒获取一次数据 每次10条 间隔100毫秒 """ while 1: self.setup() while self.ready: data = self.get_vibdata_from_database() ret = self.process_origin_vibdata(data) reduced_ret = self.reduce_vibdata_fre(ret[2]) if (self.now - self.last_computed_time).seconds >= 2: ret = self.compute_tool_hp() self.test_put_hp_to_mysql(ret) print("健康度%s" % ret) self.put_vibdata_to_cloud("振动") self.put_vibdata_to_cloud("刀具健康") print("当前加工机台->%s, 当前加工刀具->%s, 降频振动:%s" % (self.machine_num, self.tool_num[0], reduced_ret)) time.sleep(1)
class ProcessMachineInfo(threading.Thread): def __init__(self, machine_num, tool_num): super().__init__() self.machine_num = machine_num self.load_list = [] self.tool_num = tool_num self.ready = False def setup(self): print("正在准备中。。。") self.get_mysql_connect() self.get_signalr_hub() self.ready = True 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 @property def now(self): return datetime.datetime.now() def get_mysql_connect(self): try: self.mysql_connect = pymysql.connect(**settings2.mysql_info) self.cursor = self.mysql_connect.cursor() except Exception as e: print(e) self.ready = False def get_machineinfodata_from_database(self): """ 获取和处理机台信息 """ self.cursor.execute( "select * from machine_info where machine_num={0};".format( self.machine_num)) ret = self.cursor.fetchone() self.mysql_connect.commit() tool_num = ret['tool_position'] c_pre_cut = float(ret['c_pre_cut']) c_act_cut = float(ret['c_act_cut']) load = c_pre_cut / c_act_cut return tool_num, load def set_tool_num(self, num): self.tool_num[0] = num def compute_load(self, load): self.load_list.extend([load] * 5) if len(self.load_list) >= 50: self.put_to_cloud("broadcastDJJK_FZ", self.load_list) self.load_list = [] def put_to_cloud(self, type, data): companyNo = "CMP20210119001" deviceNo = '0001' try: self.hub.server.invoke( type, companyNo, deviceNo, self.now.strftime(settings2.OUTPUT_FILENAME_PATTERN), "data") print("发送%s数据到云端" % data) except Exception as e: print(e) self.ready = False def run(self) -> None: """ 每50ms获取一次机台信息 每总计1分钟发送一次数据到云端 """ while 1: self.setup() while self.ready: tool_num, load = self.get_machineinfodata_from_database() self.set_tool_num(tool_num) self.compute_load(load) #print("当前加工机台->%s, 当前加工刀具->%s, load:%s"%(self.machine_num, tool_num, load)) time.sleep(0.1)
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)
from signalr import Connection from requests import Session with Session() as session: #create a connection connection = Connection("http://202.104.118.59:8070/signalr/", session) #get chat hub hub = connection.register_hub('dashBoardHub') #start a connection connection.start() #create error handler def print_error(error): print('error: ', error) # process errors connection.error += print_error companyNo = "CMP20210119001" deviceNo = '0001' data = "10, 10, 10" data_raw = "200, 7, 200" import time, json json_data = [ { "machine_num": "1", "data":[ "T01", "T02", "T03", ] },
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()
class SubscriptionBittrex: def __init__(self, pair_id, on_update=default_on_public, base_url=BittrexParameters.URL, hub_name=BittrexParameters.HUB): """ :param pair_id: - currency pair to be used for trading :param base_url: - web-socket subscription end points :param hub_name: - Bittrex-specific url for market update :param on_update: - idea is the following: we pass reference to method WITH initialized order book for that pair_id whenever we receive update we update order book and trigger checks for arbitrage """ self.url = base_url self.hub_name = hub_name self.pair_id = pair_id self.pair_name = get_currency_pair_to_bittrex(self.pair_id) self.on_update = on_update self.hub = None self.order_book_is_received = False self.initial_order_book = None self.should_run = False def on_public(self, args): msg = process_message(args) log_to_file(msg, "bittrex.log") order_book_delta = parse_socket_update_bittrex(msg) if order_book_delta is None: err_msg = "Bittrex - cant parse update from message: {msg}".format( msg=msg) log_to_file(err_msg, SOCKET_ERRORS_LOG_FILE_NAME) else: self.on_update(EXCHANGE.BITTREX, order_book_delta) def on_receive(self, **kwargs): """ heart beat and other stuff :param kwargs: :return: """ if 'R' in kwargs and type(kwargs['R']) is not bool: msg = process_message(kwargs['R']) log_to_file(msg, "bittrex.log") if msg is not None: self.order_book_is_received = True self.initial_order_book = parse_socket_order_book_bittrex( msg, self.pair_id) else: try: msg = process_message(str(kwargs)) except: msg = kwargs log_to_file(msg, "bittrex.log") 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 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() def disconnect(self): self.should_run = False # FIXME NOTE: due to implementation of bittrex order book retrieval # dedicated method that create and destroy new instance of bittrex subscription # we are not really relying on this flag anywhere # self.order_book_is_received = False try: self.connection.close() except Exception as e: log_websocket_disconnect("Bittrex", e) def is_running(self): return self.should_run
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)
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
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 BoongalooGroupsActivityHub hub boongalooGroupsActivityHub = connection.register_hub('BoongalooGroupsActivityHub') #create new chat message handler def group_was_left_by_user(leftGroupId): print('OMG! Group that was left: ', leftGroupId) #create error handler def print_error(error): print('error: ', error) #receive new chat messages from the hub boongalooGroupsActivityHub.client.on('groupWasLeftByUser', group_was_left_by_user) #process errors connection.error += print_error #start a connection connection.qs = {'userId':'5b8e69b6-fc13-494d-9228-4215de85254f'} print("Connection was started") with connection: connection.wait(13)
def centralview_toggleTamperInfo(exists): print("TOGGLE TROUBLES INFO: ",exists) def centralview_toggleServiceInfo(exists): print("TOGGLE TROUBLES INFO: ",exists) def centralview_setVersion(version,name): print('SET VERSION: ', version+ name) #https://cntctbx.satel.pl:3030/ #"AES/ECB/PKCS5Padding" #plainEncryptionKey connection = Connection("http://mojaversa.pl/signalr", session) loading = connection.register_hub('Loading') loading.client.on('redirect', loading_redirect) loading.client.on('showNoAccess', loading_showNoAccess) loading.client.on('error', loading_error) loading.client.on('errorwithdata', loading_errorwithdata) loading.client.on('update', loading_update) loading.client.on('setVersion', loading_setVersion) loading.client.on('writtenToServer',loading_writtenToServer) #get chat hub centralview = connection.register_hub('CentralView') centralview.client.on('updateClearTrouble',centralview_updateClearTrouble) centralview.client.on('initialDataFetched',centralview_initialDataFetched) centralview.client.on('setUsername',centralview_setUsername)