Exemplo n.º 1
0
async def on_debug(**msg):
    # In case of 'queryExchangeState'
    print(msg)
    if 'R' in msg and type(msg['R']) is not bool:
        # decoded_msg = process_message(msg['R'])
        # print(decoded_msg);

        # session.headers.update({'Authorization': 'Bearer {token}'.format(token=token)})
        token = msg['R']

        print('Token is: ', token)

        print('-------------------------')
        # session = Session();
        server_url = server_url + "?token=${token}".format(token=token)
        conn = Connection(server_url, session)
        # conn.session.headers.update({'Authorization': 'Bearer {token}'.format(token=token)})

        appHub = conn.register_hub('omsclienthub')
        conn.received += on_recieved
        conn.error += on_error
        companies = appHub.server.invoke('GetInstrumentList')

        connection.close()

        conn.start()
Exemplo n.º 2
0
    def run(self):

        # setup SSL context construction if required
        if self.kwargs["CertFile"]:
            self._setup_websockets_ssl_certs()

        # setup SignalR connection (w/ authentication)
        connection = SignalRConnection(f"{self.kwargs['APIDomain']}/signalr", session=None)
        connection.qs = {'access_token': self.kwargs['access_token']}

        hub = connection.register_hub('TradingHub')

        self._hub = hub
        self._connection = connection

        # Set event handlers
        hub.client.on('MarketTradesRefreshed', lambda x: None)
        hub.client.on('MarketOrdersRefreshed', self.on_market_tick_received)
        hub.client.on('tradeCreated', self.on_execution_received)
        hub.client.on('createTradeOrderResult', self.on_place_order_received)
        hub.client.on('cancelTradeOrderResult', self.on_cancel_order_received)
        hub.client.on('cancelAllTradeOrdersResult', self.on_cancel_all_orders_received)

        connection.received += self.on_raw_msg_received
        connection.error += self.on_error_received

        connection.start()
        pass
Exemplo n.º 3
0
def main():
    # Create connection
    # Users can optionally pass a session object to the client, e.g a cfscrape session to bypass cloudflare.
    connection = Connection('https://beta.bittrex.com/signalr', session=None)

    # Register hub
    hub = connection.register_hub('c2')

    # Assign debug message handler. It streams unfiltered data, uncomment it to test.
    # connection.received += on_debug

    # Assign error handler
    connection.error += on_error

    # Assign hub message handler
    # Public callbacks
    hub.client.on('uE', on_message)
    hub.client.on('uS', on_message)
    # Private callbacks
    hub.client.on('uB', on_private)
    hub.client.on('uO', on_private)

    # Send a message
    # hub.server.invoke('SubscribeToExchangeDeltas', 'BTC-ETH')  # Invoke 0
    hub.server.invoke('SubscribeToSummaryDeltas')  # Invoke 1
    # hub.server.invoke('queryExchangeState', 'BTC-NEO')  # Invoke 2

    # Private methods
    # API_KEY, API_SECRET = '### API KEY ###', '### API SECRET ###'
    # hub.server.invoke('GetAuthContext', API_KEY) # Invoke 3

    # Start the client
    connection.start()
Exemplo n.º 4
0
def main():
    # Setup REST API connection
    trade_api = BlockExTradeApi(USERNAME, PASSWORD, API_URL, API_ID)
    _ = trade_api.login() # That's just a example we don't need access_token

    # Setup SignalR connecton
    connection = Connection(f"{API_URL}/signalr", session=None)
    hub = connection.register_hub('TradingHub')

    # Set event handlers
    hub.client.on('MarketOrdersRefreshed', on_message)

    trader_instruments = trade_api.get_trader_instruments()

    # Pick an instrument to work with
    instrument_id = trader_instruments[0]['id']

    # Cancel all orders for instrument 0
    trade_api.cancel_all_orders(instrument_id=instrument_id)

    lowest_ask_order(trade_api, instrument_id)
    highest_bid_order(trade_api, instrument_id)

    # Run the event loop
    connection.start()
Exemplo n.º 5
0
async def connect():
    global HUB
    connection = Connection(URL)
    HUB = connection.register_hub('c3')
    connection.received += on_message
    connection.error += on_error
    connection.start()
    print('Connected')
Exemplo n.º 6
0
    async def exchange_client(self, loop, tag):
        print('Exchange: Bittrex | Connection to {} has opened'.format(
            sstream[tag]))
        connection = Connection(ws_url, session=None, loop=loop)
        hub = connection.register_hub('c2')

        connection.received += self.on_debug
        connection.error += self.on_error

        if sstream[tag][1]:
            hub.client.on(sstream[tag][1], self.parse_data)

        if tag != 'SummaryDelta':
            for i in self.tickers:
                hub.server.invoke(sstream[tag][0], i)
        else:
            hub.server.invoke(sstream[tag][0])

        #hub.server.invoke('SubscribeToSummaryDeltas')
        #hub.server.invoke('queryExchangeState', 'BTC-NEO')

        connection.start()
Exemplo n.º 7
0
if __name__ == "__main__":
    # Create connection
    # Users can optionally pass a session object to the client, e.g a cfscrape session to bypass cloudflare.
    # connection = Connection('https://beta.bittrex.com/signalr', session=None)
    connection = Connection('http://localhost:5001', session=None)

    # Register hub
    # hub = connection.register_hub('c2')
    hub = connection.register_hub('chatHub')

    # Assign debug message handler. It streams unfiltered data, uncomment it to test.
    connection.received += on_debug

    # Assign error handler
    connection.error += on_error

    # Assign hub message handler
    hub.client.on('ReceiveMessage', on_message)
    # hub.client.on('uS', on_message)

    # Send a message
    hub.server.invoke('SendMessage1', 'BTC-ETH')
    # hub.server.invoke('SubscribeToSummaryDeltas')
    # hub.server.invoke('queryExchangeState', 'BTC-NEO')

    print(connection.hub)
    print(connection.url)
    # Start the client
    connection.start()
Exemplo n.º 8
0
class MyBittrex:
    def __init__(self):
        self.url = 'https://socket-v3.bittrex.com/signalr'
        self.trade = 0.0
        self.ticker = 0.0
        self.tickers = -1
        self.book = -1
        self.summary = 0.0
        self.summaries = -1
        self.candle = -1
        self.last_state = self.current_time()
        self.last_date = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
        self.last_message = ""

        # Schedule three calls *concurrently*:
        # Create connection
        # Users can optionally pass a session object to the client, e.g a cfscrape session to bypass cloudflare.
        self.con_master = Connection(self.url, session=None)

        # Register hub
        self.hub_master = self.con_master.register_hub('c3')

        # Assign debug message handler. It streams unfiltered data, uncomment it to test.
        # self.con_master.received += self.on_debug

        # Assign Time of last packet
        self.con_master.received += self.on_time

        # Assign error handler
        self.con_master.error += self.on_error

        # Assign hub message handler
        self.public_methods = [
            {
                'method': 'candle',
                'routine': self.on_candle,
                'subscribe': 'candle_ETH-BTC_HOUR_1'
            },
            {
                'method': 'heartbeat',
                'routine': self.on_heartbeat,
                'subscribe': 'heartbeat'
            },
            {
                'method': 'marketSummaries',
                'routine': self.on_summaries,
                'subscribe': 'market_summaries'
            },
            {
                'method': 'marketSummary',
                'routine': self.on_summary,
                'subscribe': 'market_summary_LTC-BTC'
            },
            {
                'method': 'orderBook',
                'routine': self.on_book,
                'subscribe': 'orderbook_ADA-BTC_1'
            },
            {
                'method': 'tickers',
                'routine': self.on_tickers,
                'subscribe': 'tickers'
            },
            {
                'method': 'ticker',
                'routine': self.on_ticker,
                'subscribe': 'ticker_TRX-BTC'
            },
            {
                'method': 'trade',
                'routine': self.on_trade,
                'subscribe': 'trade_BTC-USD'
            },
        ]

        for method in self.public_methods:
            self.hub_master.client.on(method['method'], method['routine'])
            self.hub_master.server.invoke('Subscribe', [[method['subscribe']]])

        # Start the client
        self.con_master.start()

    @staticmethod
    async def process_message(message):
        try:
            deflated_msg = decompress(b64decode(message), -MAX_WBITS)
            return json.loads(deflated_msg.decode())
        except Exception as ChoCho:
            print(ChoCho.args)
            return message

    # Create time handler.
    async def on_time(self, **msg):
        self.last_message = msg
        self.last_date = datetime.today().strftime("%Y-%m-%d %H:%M:%S")

    # Create debug message handler.
    @staticmethod
    async def on_debug(**msg):
        print("Debug information: ", end='')
        print(str(msg))

    # Create error handler
    @staticmethod
    async def on_error(msg):
        if 'E' in msg:
            print('Error: ' + msg['E'])
        if 'M' in msg:
            print('Received method: ' + str(msg['M']))
        if 'A' in msg:
            print('Received message: ' + str(msg['A']))

    @staticmethod
    def current_time():
        return (Decimal.from_float(datetime.now().timestamp()) *
                1000).quantize(Decimal("1"), ROUND_HALF_UP)

    async def on_message(self, msg):
        decoded_msg = await self.process_message(msg[0])
        print(decoded_msg)

    async def on_candle(self, msg):
        decoded_msg = await self.process_message(msg[0])
        self.candle = decoded_msg['sequence']

    async def on_heartbeat(self, msg):
        self.last_message = msg
        # print('.', end='')
        self.last_state = self.current_time()

    async def on_summaries(self, msg):
        decoded_msg = await self.process_message(msg[0])
        self.summaries = decoded_msg['sequence']

    async def on_summary(self, msg):
        decoded_msg = await self.process_message(msg[0])
        self.summary = decoded_msg['percentChange']

    async def on_book(self, msg):
        decoded_msg = await self.process_message(msg[0])
        self.book = decoded_msg['sequence']

    async def on_tickers(self, msg):
        decoded_msg = await self.process_message(msg[0])
        self.tickers = decoded_msg['sequence']

    async def on_ticker(self, msg):
        decoded_msg = await self.process_message(msg[0])
        self.ticker = decoded_msg['lastTradeRate']

    async def on_trade(self, msg):
        decoded_msg = await self.process_message(msg[0])
        self.trade = decoded_msg['deltas'][0]['rate']

    def restart(self):
        for method in self.public_methods:
            self.hub_master.server.invoke('Subscribe', [[method['subscribe']]])
        self.con_master.start()
        self.last_state = self.current_time()
Exemplo n.º 9
0
class BittrexSocket:
    __hub = None
    __invoke_event = None
    __invoke_resp = None
    __watchdog: Optional[Watchdog]
    __invoke_lock = Optional[asyncio.Lock]
    __connection: Optional[Connection]

    def __init__(self, api_key=None, api_secret=None):
        self.api_key = api_key
        self.api_secret = api_secret

    async def listen(self, channels: list[str], callbacks: dict[str,
                                                                Callable]):
        self.__watchdog = Watchdog(HEARTBEAT_TIMEOUT)
        self.__invoke_lock = asyncio.Lock()
        await self.__connect()
        if self.api_key is not None:
            await self.__auth()

        assert 'heartbeat' not in channels
        channels.append('heartbeat')
        callbacks['heartbeat'] = self.__on_heartbeat
        await self.__subscribe(channels, callbacks)
        await self.__watchdog.loop()
        self.__connection.close()

    async def __on_heartbeat(self, _):
        self.__watchdog.reset()

    async def __connect(self):
        self.__connection = Connection(URL)
        self.__hub = self.__connection.register_hub('c3')
        self.__connection.received += self.__on_message
        self.__connection.error += self.__on_error
        self.__connection.start()
        log.info(f'Connected')

    async def __on_message(self, **msg):
        if 'R' in msg:
            self.__invoke_resp = msg['R']
            self.__invoke_event.set()

    def stop(self):
        self.__watchdog.stop()

    async def __on_error(self, msg):
        log.error(str(msg))
        self.stop()

    async def __auth(self):
        timestamp = str(int(time.time()) * 1000)
        random_content = str(uuid.uuid4())
        content = timestamp + random_content
        signed_content = hmac.new(self.api_secret.encode(), content.encode(),
                                  hashlib.sha512).hexdigest()
        response = await self.__invoke('Authenticate', self.api_key, timestamp,
                                       random_content, signed_content)

        if response['Success']:
            log.info(f'Authenticated')

            async def reauth(_):
                asyncio.create_task(self.__auth())

            self.__hub.client.on('authenticationExpiring', reauth)
        else:
            log.error(f'Authentication failed: {response["ErrorCode"]}')

    async def __subscribe(self, channels, callbacks):
        for method, callback in callbacks.items():
            self.__hub.client.on(
                method,
                corotools.wraptry(corotools.wrapfunc(callback,
                                                     self.__decode_message),
                                  msg='BittrexSocket callback exception'))

        response = await self.__invoke('Subscribe', channels)
        for i in range(len(channels)):
            if response[i]['Success']:
                log.info(f'Subscription to "{channels[i]}" successful')
            else:
                log.error(
                    f'Subscription to "{channels[i]}" failed: {response[i]["ErrorCode"]}'
                )
                self.stop()

    async def __invoke(self, method, *args):
        async with self.__invoke_lock:
            self.__invoke_event = asyncio.Event()
            self.__hub.server.invoke(method, *args)
            await self.__invoke_event.wait()
            return self.__invoke_resp

    @staticmethod
    def __decode_message(msg):
        if not len(msg):
            return None
        else:
            msg = msg[0]
        try:
            decompressed_msg = decompress(b64decode(msg, validate=True),
                                          -MAX_WBITS)
        except SyntaxError:
            decompressed_msg = decompress(b64decode(msg, validate=True))
        return json.loads(decompressed_msg.decode())