class RealtimeData(Settings):

    last_price = 0

    def __init__(self):
        super().__init__()
        self.c = PNConfiguration()
        self.c.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f'
        self.c.reconnect_policy = PNReconnectionPolicy.LINEAR
        self.pubnub = PubNubTornado(self.c)
        channels = [
            self.realtime_product,
        ]
        self.main(channels)
        self.pubnub.start()

    @gen.coroutine
    def main(self, channels):
        class Callback(SubscribeCallback):
            def message(self, pubnub, message):
                RealtimeData.last_price = message.message['ltp']
                pubnub.stop()  # 必要なデータを取得したら一度停止する

        s = Callback()
        self.pubnub.add_listener(s)
        self.pubnub.subscribe().channels(channels).execute()

    def stop(self):
        self.pubnub.stop()

    def get_current_data(self):
        self.pubnub.start()
示例#2
0
class TestPubNubAsyncWhereNow(AsyncTestCase):
    def setUp(self):
        super(TestPubNubAsyncWhereNow, self).setUp()
        self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/where_now/single_channel.yaml',
        filter_query_parameters=['uuid', 'pnsdk'])
    @tornado.testing.gen_test(timeout=15)
    def test_where_now_single_channel(self):
        ch = "where-now-tornado-ch"
        uuid = "where-now-tornado-uuid"
        self.pubnub.config.uuid = uuid

        yield connect_to_channel(self.pubnub, ch)
        yield gen.sleep(10)
        env = yield self.pubnub.where_now() \
            .uuid(uuid) \
            .future()

        channels = env.result.channels

        assert len(channels) == 1
        assert channels[0] == ch

        yield disconnect_from_channel(self.pubnub, ch)
        self.pubnub.stop()
        self.stop()

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/where_now/multiple_channels.yaml',
        filter_query_parameters=['uuid', 'pnsdk'])
    @tornado.testing.gen_test(timeout=15)
    def test_multiple_channels(self):
        ch1 = "where-now-tornado-ch1"
        ch2 = "where-now-tornado-ch2"
        uuid = "where-now-tornado-uuid"
        self.pubnub.config.uuid = uuid

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch1).execute()
        yield callback_messages.wait_for_connect()

        self.pubnub.subscribe().channels(ch2).execute()
        yield gen.sleep(5)

        env = yield self.pubnub.where_now() \
            .uuid(uuid) \
            .future()

        channels = env.result.channels

        assert len(channels) == 2
        assert ch1 in channels
        assert ch2 in channels

        yield disconnect_from_channel(self.pubnub, [ch1, ch2])
        self.pubnub.stop()
        self.stop()
示例#3
0
def sfd_process(sfd):
    FX_CHANNEL = "lightning_ticker_FX_BTC_JPY"
    BTC_CHANNEL = "lightning_ticker_BTC_JPY"
    class BitflyerSubscriberCallback(SubscribeCallback):
        def message(self, pubnub, message):
            tick = message.message
            timestamp = dateutil.parser.parse(tick["timestamp"])
            with sfd.lock:
                changed = False
                if message.channel == FX_CHANNEL:
                    if sfd.fx_ltp != tick["ltp"]:
                        sfd.fx_ltp = tick["ltp"]
                        changed = True
                elif message.channel == BTC_CHANNEL:
                    if sfd.btc_ltp != tick["ltp"]:
                        sfd.btc_ltp = tick["ltp"]
                        changed = True
                if sfd.ready and changed:
                    sfd.disparity = (sfd.fx_ltp / sfd.btc_ltp) * 100 - 100
                    if (sfd.fx_ltp > sfd.btc_ltp and sfd.disparity >= 10.0) or \
                       (sfd.fx_ltp < sfd.btc_ltp and sfd.disparity <= -10.0):
                        sfd.last_sfd_at = timestamp
                    sfd.updated_at = timestamp
                    sfd.event.set()

    config = PNConfiguration()
    config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f'
    config.reconnect_policy = PNReconnectionPolicy.LINEAR
    config.ssl = False
    config.set_presence_timeout(60)
    pubnub = PubNubTornado(config)
    listener = BitflyerSubscriberCallback()
    pubnub.add_listener(listener)
    pubnub.subscribe().channels([FX_CHANNEL, BTC_CHANNEL]).execute()
    pubnub.start()
class TestChannelSubscription(AsyncTestCase, SubscriptionTest):
    def setUp(self):
        super(TestChannelSubscription, self).setUp()
        self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop)
        self.pubnub_listener = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop)

    @tornado.testing.gen_test
    async def test_subscribe_publish_unsubscribe(self):
        ch = helper.gen_channel("subscribe-test")
        message = "hey"

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch).execute()
        await callback_messages.wait_for_connect()

        sub_env, pub_env = await tornado.gen.multi([
            callback_messages.wait_for_message_on(ch),
            self.pubnub.publish().channel(ch).message(message).future()])

        assert pub_env.status.original_response[0] == 1
        assert pub_env.status.original_response[1] == 'Sent'

        assert sub_env.channel == ch
        assert sub_env.subscription is None
        assert sub_env.message == message

        self.pubnub.unsubscribe().channels(ch).execute()
        await callback_messages.wait_for_disconnect()
class TestChannelSubscription(AsyncTestCase, SubscriptionTest):
    def setUp(self):
        super(TestChannelSubscription, self).setUp()
        self.pubnub = PubNubTornado(pnconf_sub_copy(),
                                    custom_ioloop=self.io_loop)
        self.pubnub_listener = PubNubTornado(pnconf_sub_copy(),
                                             custom_ioloop=self.io_loop)

    @tornado.testing.gen_test
    async def test_subscribe_publish_unsubscribe(self):
        ch = helper.gen_channel("subscribe-test")
        message = "hey"

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch).execute()
        await callback_messages.wait_for_connect()

        sub_env, pub_env = await tornado.gen.multi([
            callback_messages.wait_for_message_on(ch),
            self.pubnub.publish().channel(ch).message(message).future()
        ])

        assert pub_env.status.original_response[0] == 1
        assert pub_env.status.original_response[1] == 'Sent'

        assert sub_env.channel == ch
        assert sub_env.subscription is None
        assert sub_env.message == message

        self.pubnub.unsubscribe().channels(ch).execute()
        await callback_messages.wait_for_disconnect()
    def test_reconnection(self):
        pnconf = PNConfiguration()
        pnconf.publish_key = "demo"
        pnconf.subscribe_key = "demo"
        pnconf.origin = "localhost:8089"
        pnconf.subscribe_request_timeout = 10
        pnconf.reconnect_policy = PNReconnectionPolicy.LINEAR
        pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop)
        time_until_open_again = 10

        @gen.coroutine
        def close_soon():
            yield gen.sleep(3)
            pubnub.http.close()
            pubnub.http = None
            print(">>> connection is broken")

        @gen.coroutine
        def open_again():
            yield gen.sleep(time_until_open_again)
            pubnub.http = tornado.httpclient.AsyncHTTPClient(
                max_clients=PubNubTornado.MAX_CLIENTS)
            print(">>> connection is open again")

        @gen.coroutine
        def countdown():
            yield gen.sleep(2)
            opened = False
            count = time_until_open_again

            while not opened:
                print(">>> %ds to open again" % count)
                count -= 1
                if count <= 0:
                    break
                yield gen.sleep(1)

        my_listener = MySubscribeCallback()
        pubnub.add_listener(my_listener)
        pubnub.subscribe().channels('my_channel').execute()

        yield gen.sleep(1000)
示例#7
0
class BfAsyncSubscriber:
    def __init__(self, channels):
        self.channels = channels
        pnc = PNConfiguration()
        pnc.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f'
        pnc.reconnect_policy = PNReconnectionPolicy.LINEAR
        self.pubnub = PubNubTornado(pnc)

    @gen.coroutine
    def subscribe(self):
        return self.pubnub.subscribe().channels(self.channels).execute()
示例#8
0
    def test_reconnection(self):
        pnconf = PNConfiguration()
        pnconf.publish_key = "demo"
        pnconf.subscribe_key = "demo"
        pnconf.origin = "localhost:8089"
        pnconf.subscribe_request_timeout = 10
        pnconf.reconnect_policy = PNReconnectionPolicy.LINEAR
        pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop)
        time_until_open_again = 10

        @gen.coroutine
        def close_soon():
            yield gen.sleep(3)
            pubnub.http.close()
            pubnub.http = None
            print(">>> connection is broken")

        @gen.coroutine
        def open_again():
            yield gen.sleep(time_until_open_again)
            pubnub.http = tornado.httpclient.AsyncHTTPClient(max_clients=PubNubTornado.MAX_CLIENTS)
            print(">>> connection is open again")

        @gen.coroutine
        def countdown():
            yield gen.sleep(2)
            opened = False
            count = time_until_open_again

            while not opened:
                print(">>> %ds to open again" % count)
                count -= 1
                if count <= 0:
                    break
                yield gen.sleep(1)

        my_listener = MySubscribeCallback()
        pubnub.add_listener(my_listener)
        pubnub.subscribe().channels('my_channel').execute()

        yield gen.sleep(1000)
示例#9
0
class BitcoinTickServer():

    def __init__(self, fxevents, tick_interval):
        self.fxevents = fxevents
        self.tick_interval = tick_interval
        self.instruments = 'lightning_ticker_BTC_JPY'
        config = PNConfiguration()
        config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f'
        config.reconnect_policy = PNReconnectionPolicy.LINEAR
        self.pubnub = PubNubTornado(config)
        self.run = True
    
    def get_ticks(self):
        ticks = self.listener.get_ticks()
        return ticks
    
    def get_time(self):
        time = self.listener.get_time()
        return time
    
    @gen.coroutine
    def thread(self):
        self.listener = BitflyerSubscriberCallback(self.tick_interval)
        self.pubnub.add_listener(self.listener)
        self.pubnub.subscribe().channels(self.instruments).execute()
        self.pubnub.start()
        try:
            while self.run:
                self.do_unsubscribe()
        except:
            print('@BitcoinTickServerThread : exception raised.')
            traceback.print_exc()
            self.fxevents.put(event_thread.EventContainer(name='exception', value=[]))
    
    def thread_close(self):
        self.run = False
    
    def do_unsubscribe(self):
        if self.run==False:
            self.pubnub.unsubscribe({'channel': self.instruments})
            raise Exception
示例#10
0
    def executionsProcess(self):
        """
        pubnubで価格を取得する場合の処理(基本的に不要.)
        """
        channels = ["lightning_executions_FX_BTC_JPY"]
        executions = self.executions
        class BFSubscriberCallback(SubscribeCallback):
            def message(self, pubnub, message):
                execution = message.message
                for i in execution:
                    executions.append(i)

        config = PNConfiguration()
        config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f'
        config.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL
        config.ssl = False
        config.set_presence_timeout(60)
        pubnub = PubNubTornado(config)
        listener = BFSubscriberCallback()
        pubnub.add_listener(listener)
        pubnub.subscribe().channels(channels).execute()
        pubnubThread = threading.Thread(target=pubnub.start)
        pubnubThread.start()
示例#11
0
class TestChannelSubscription(AsyncTestCase, SubscriptionTest):
    def setUp(self):
        super(TestChannelSubscription, self).setUp()

        messenger_config = pnconf_sub_copy()
        messenger_config.set_presence_timeout(8)
        messenger_config.uuid = "heartbeat-tornado-messenger"

        listener_config = pnconf_sub_copy()
        listener_config.uuid = "heartbeat-tornado-listener"

        self.pubnub = PubNubTornado(messenger_config, custom_ioloop=self.io_loop)
        self.pubnub_listener = PubNubTornado(listener_config, custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/heartbeat/timeout.yaml',
        filter_query_parameters=['uuid', 'pnsdk'],
        match_on=['method', 'scheme', 'host', 'port', 'string_list_in_path', 'query'],
        match_on_kwargs={
            'string_list_in_path': {
                'positions': [4]
            }
        })
    @tornado.testing.gen_test(timeout=20)
    def test_timeout_event_on_broken_heartbeat(self):
        ch = "heartbeat-tornado-ch"

        # - connect to :ch-pnpres
        callback_presence = SubscribeListener()
        self.pubnub_listener.add_listener(callback_presence)
        self.pubnub_listener.subscribe().channels(ch).with_presence().execute()
        yield callback_presence.wait_for_connect()

        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert ch == envelope.channel
        assert 'join' == envelope.event
        assert self.pubnub_listener.uuid == envelope.uuid

        # - connect to :ch
        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch).execute()

        # - assert join event
        useless, prs_envelope = yield [
            callback_messages.wait_for_connect(),
            callback_presence.wait_for_presence_on(ch)]
        assert ch == prs_envelope.channel
        assert 'join' == prs_envelope.event
        assert self.pubnub.uuid == prs_envelope.uuid

        # wait for one heartbeat call
        yield gen.sleep(8)

        # - break messenger heartbeat loop
        self.pubnub._subscription_manager._stop_heartbeat_timer()

        # - assert for timeout
        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert ch == envelope.channel
        assert 'timeout' == envelope.event
        assert self.pubnub.uuid == envelope.uuid

        # - disconnect from :ch-pnpres
        self.pubnub_listener.unsubscribe().channels(ch).execute()
        yield callback_presence.wait_for_disconnect()
示例#12
0
class TestChannelGroupSubscription(AsyncTestCase, SubscriptionTest):
    def setUp(self):
        super(TestChannelGroupSubscription, self).setUp()
        self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop)
        self.pubnub_listener = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/group_sub_unsub.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk'])
    @tornado.testing.gen_test(timeout=60)
    def test_group_subscribe_unsubscribe(self):
        ch = "subscribe-unsubscribe-channel"
        gr = "subscribe-unsubscribe-group"

        envelope = yield self.pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

        yield gen.sleep(1)

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channel_groups(gr).execute()
        yield callback_messages.wait_for_connect()

        self.pubnub.unsubscribe().channel_groups(gr).execute()
        yield callback_messages.wait_for_disconnect()

        envelope = yield self.pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/group_sub_pub_unsub.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk'])
    @tornado.testing.gen_test(timeout=60)
    def test_group_subscribe_publish_unsubscribe(self):
        ch = "subscribe-unsubscribe-channel"
        gr = "subscribe-unsubscribe-group"
        message = "hey"

        envelope = yield self.pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

        yield gen.sleep(1)

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channel_groups(gr).execute()
        yield callback_messages.wait_for_connect()

        sub_envelope, pub_envelope = yield [
            callback_messages.wait_for_message_on(ch),
            self.pubnub.publish().channel(ch).message(message).future()]

        assert pub_envelope.status.original_response[0] == 1
        assert pub_envelope.status.original_response[1] == 'Sent'

        assert sub_envelope.channel == ch
        assert sub_envelope.subscription == gr
        assert sub_envelope.message == message

        self.pubnub.unsubscribe().channel_groups(gr).execute()
        yield callback_messages.wait_for_disconnect()

        envelope = yield self.pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/group_join_leave.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk'])
    @tornado.testing.gen_test(timeout=60)
    def test_group_join_leave(self):
        self.pubnub.config.uuid = "test-subscribe-messenger"
        self.pubnub_listener.config.uuid = "test-subscribe-listener"

        ch = "subscribe-test-channel"
        gr = "subscribe-test-group"

        envelope = yield self.pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

        yield gen.sleep(1)

        callback_messages = SubscribeListener()
        callback_presence = SubscribeListener()

        self.pubnub_listener.add_listener(callback_presence)
        self.pubnub_listener.subscribe().channel_groups(gr).with_presence().execute()
        yield callback_presence.wait_for_connect()

        prs_envelope = yield callback_presence.wait_for_presence_on(ch)
        assert prs_envelope.event == 'join'
        assert prs_envelope.uuid == self.pubnub_listener.uuid
        assert prs_envelope.channel == ch
        assert prs_envelope.subscription == gr

        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channel_groups(gr).execute()

        useless, prs_envelope = yield [
            callback_messages.wait_for_connect(),
            callback_presence.wait_for_presence_on(ch)
        ]

        assert prs_envelope.event == 'join'
        assert prs_envelope.uuid == self.pubnub.uuid
        assert prs_envelope.channel == ch
        assert prs_envelope.subscription == gr

        self.pubnub.unsubscribe().channel_groups(gr).execute()

        useless, prs_envelope = yield [
            callback_messages.wait_for_disconnect(),
            callback_presence.wait_for_presence_on(ch)
        ]

        assert prs_envelope.event == 'leave'
        assert prs_envelope.uuid == self.pubnub.uuid
        assert prs_envelope.channel == ch
        assert prs_envelope.subscription == gr

        self.pubnub_listener.unsubscribe().channel_groups(gr).execute()
        yield callback_presence.wait_for_disconnect()

        envelope = yield self.pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/subscribe_tep_by_step.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk'])
    @tornado.testing.gen_test(timeout=30)
    def test_subscribe_step_by_step(self):
        ch1 = 'test-here-now-channel1'
        ch2 = 'test-here-now-channel2'
        ch3 = 'test-here-now-channel3'
        self.pubnub.config.uuid = 'test-here-now-uuid'
        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        print("connecting to the first...")
        self.pubnub.subscribe().channels(ch1).execute()
        yield callback_messages.wait_for_connect()
        print("...connected to the first")
        yield gen.sleep(1)
        print("connecting to the second...")
        self.pubnub.subscribe().channels(ch2).execute()
        self.pubnub.subscribe().channels(ch3).execute()
        self.pubnub.subscribe().channels(ch3).execute()
        self.pubnub.subscribe().channels(ch2).execute()
        print("...connected to the second")
        yield gen.sleep(5)
        env = yield self.pubnub.here_now() \
            .channels([ch1, ch2]) \
            .future()

        assert env.result.total_channels == 2
        assert env.result.total_occupancy >= 1

        channels = env.result.channels

        assert len(channels) == 2
        assert channels[0].occupancy >= 1
        assert channels[0].occupants[0].uuid == self.pubnub.uuid
        assert channels[1].occupancy >= 1
        assert channels[1].occupants[0].uuid == self.pubnub.uuid

        self.pubnub.unsubscribe().channels([ch1, ch2]).execute()
        yield callback_messages.wait_for_disconnect()

        self.pubnub.unsubscribe().channels(ch3).execute()

        self.pubnub.stop()
        self.stop()
示例#13
0
class TestChannelSubscription(AsyncTestCase, SubscriptionTest):
    def setUp(self):
        super(TestChannelSubscription, self).setUp()
        self.pubnub = PubNubTornado(pnconf_sub_copy(),
                                    custom_ioloop=self.io_loop)
        self.pubnub_listener = PubNubTornado(pnconf_sub_copy(),
                                             custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/sub_unsub.yaml',
        filter_query_parameters=['uuid', 'seqn'])
    @tornado.testing.gen_test(timeout=300)
    def test_subscribe_unsubscribe(self):
        ch = "subscribe-tornado-ch"

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)

        self.pubnub.subscribe().channels(ch).execute()
        assert ch in self.pubnub.get_subscribed_channels()
        assert len(self.pubnub.get_subscribed_channels()) == 1

        yield callback_messages.wait_for_connect()
        assert ch in self.pubnub.get_subscribed_channels()
        assert len(self.pubnub.get_subscribed_channels()) == 1

        self.pubnub.unsubscribe().channels(ch).execute()
        assert ch not in self.pubnub.get_subscribed_channels()
        assert len(self.pubnub.get_subscribed_channels()) == 0

        yield callback_messages.wait_for_disconnect()
        assert ch not in self.pubnub.get_subscribed_channels()
        assert len(self.pubnub.get_subscribed_channels()) == 0

        self.pubnub.stop()
        self.stop()

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/sub_pub_unsub.yaml',
        filter_query_parameters=['uuid', 'seqn'])
    @tornado.testing.gen_test(timeout=30)
    def test_subscribe_publish_unsubscribe(self):
        ch = "subscribe-tornado-ch"
        message = "hey"

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch).execute()
        yield callback_messages.wait_for_connect()

        sub_env, pub_env = yield [
            callback_messages.wait_for_message_on(ch),
            self.pubnub.publish().channel(ch).message(message).future()
        ]

        assert pub_env.status.original_response[0] == 1
        assert pub_env.status.original_response[1] == 'Sent'

        assert sub_env.channel == ch
        assert sub_env.subscription is None
        assert sub_env.message == message

        self.pubnub.unsubscribe().channels(ch).execute()
        yield callback_messages.wait_for_disconnect()

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/join_leave.yaml',
        filter_query_parameters=['uuid', 'seqn'])
    @tornado.testing.gen_test(timeout=15)
    def test_join_leave(self):
        ch = "subscribe-tornado-ch"

        self.pubnub.config.uuid = "subscribe-tornado-messenger"
        self.pubnub_listener.config.uuid = "subscribe-tornado-listener"
        callback_presence = SubscribeListener()
        self.pubnub_listener.add_listener(callback_presence)
        self.pubnub_listener.subscribe().channels(ch).with_presence().execute()
        yield callback_presence.wait_for_connect()

        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert envelope.channel == ch
        assert envelope.event == 'join'
        assert envelope.uuid == self.pubnub_listener.uuid

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch).execute()
        yield callback_messages.wait_for_connect()

        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert envelope.channel == ch
        assert envelope.event == 'join'
        assert envelope.uuid == self.pubnub.uuid

        self.pubnub.unsubscribe().channels(ch).execute()
        yield callback_messages.wait_for_disconnect()

        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert envelope.channel == ch
        assert envelope.event == 'leave'
        assert envelope.uuid == self.pubnub.uuid

        self.pubnub_listener.unsubscribe().channels(ch).execute()
        yield callback_presence.wait_for_disconnect()
        self.pubnub.stop()
        self.stop()
示例#14
0
class FastTrader(Settings):

    last_price = 0
    hd = ConditionChecker()
    hd.market_reader()  # マーケットの流れを確認
    hd.board_status_checker()  # サーバー状態を確認
    hd.sfd_status_checker()  # SFDを確認
    rec = Recorder()
    count = 0
    count2 = 0
    last_balance = 0
    order = OrderMaker()

    def __init__(self):
        super().__init__()
        self.c = PNConfiguration()
        self.c.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f'
        self.c.reconnect_policy = PNReconnectionPolicy.LINEAR
        self.pubnub = PubNubTornado(self.c)
        channels = [
            self.realtime_product,
        ]
        self.main(channels)
        self.pubnub.start()

    @gen.coroutine
    def main(self, channels):
        class Callback(SubscribeCallback):
            def message(self, pubnub, message):
                current_price = message.message['ltp']
                FastTrader.hd.child_order_checker()
                FastTrader.hd.position_checker()
                if FastTrader.count == 0:
                    FastTrader.hd.market_reader()
                print(current_price)

                if FastTrader.hd.positioning and not FastTrader.hd.ordering:
                    FastTrader.hd.position_checker_for_market_ordering(
                        current_price)
                    print('aiming to place execution order')
                FastTrader.count += 1

                if FastTrader.hd.signal:
                    print('aiming to place a new order')
                    FastTrader.hd.order_information_checker("MARKET")

                if FastTrader.count == 40:
                    FastTrader.count2 += 1
                    FastTrader.hd.sfd_status_checker()
                    if FastTrader.count2 == 10:
                        FastTrader.rec.balance_recorder(
                            FastTrader.hd.balance, current_price)
                        FastTrader.count2 = 0
                    FastTrader.count = 0

        s = Callback()
        self.pubnub.add_listener(s)
        self.pubnub.subscribe().channels(channels).execute()

    def stop(self):
        self.pubnub.stop()

    def get_current_data(self):
        self.pubnub.start()
示例#15
0
class TestChannelGroupSubscription(AsyncTestCase, SubscriptionTest):
    def setUp(self):
        super(TestChannelGroupSubscription, self).setUp()
        self.pubnub = PubNubTornado(pnconf_sub_copy(),
                                    custom_ioloop=self.io_loop)
        self.pubnub_listener = PubNubTornado(pnconf_sub_copy(),
                                             custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/group_sub_unsub.yaml',
        filter_query_parameters=['uuid', 'seqn'])
    @tornado.testing.gen_test(timeout=60)
    def test_group_subscribe_unsubscribe(self):
        ch = "subscribe-unsubscribe-channel"
        gr = "subscribe-unsubscribe-group"

        envelope = yield self.pubnub.add_channel_to_channel_group(
        ).channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

        yield gen.sleep(1)

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channel_groups(gr).execute()
        yield callback_messages.wait_for_connect()

        self.pubnub.unsubscribe().channel_groups(gr).execute()
        yield callback_messages.wait_for_disconnect()

        envelope = yield self.pubnub.remove_channel_from_channel_group(
        ).channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/group_sub_pub_unsub.yaml',
        filter_query_parameters=['uuid', 'seqn'])
    @tornado.testing.gen_test(timeout=60)
    def test_group_subscribe_publish_unsubscribe(self):
        ch = "subscribe-unsubscribe-channel"
        gr = "subscribe-unsubscribe-group"
        message = "hey"

        envelope = yield self.pubnub.add_channel_to_channel_group(
        ).channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

        yield gen.sleep(1)

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channel_groups(gr).execute()
        yield callback_messages.wait_for_connect()

        sub_envelope, pub_envelope = yield [
            callback_messages.wait_for_message_on(ch),
            self.pubnub.publish().channel(ch).message(message).future()
        ]

        assert pub_envelope.status.original_response[0] == 1
        assert pub_envelope.status.original_response[1] == 'Sent'

        assert sub_envelope.channel == ch
        assert sub_envelope.subscription == gr
        assert sub_envelope.message == message

        self.pubnub.unsubscribe().channel_groups(gr).execute()
        yield callback_messages.wait_for_disconnect()

        envelope = yield self.pubnub.remove_channel_from_channel_group(
        ).channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/group_join_leave.yaml',
        filter_query_parameters=['uuid', 'seqn'])
    @tornado.testing.gen_test(timeout=60)
    def test_group_join_leave(self):
        self.pubnub.config.uuid = "test-subscribe-messenger"
        self.pubnub_listener.config.uuid = "test-subscribe-listener"

        ch = "subscribe-test-channel"
        gr = "subscribe-test-group"

        envelope = yield self.pubnub.add_channel_to_channel_group(
        ).channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

        yield gen.sleep(1)

        callback_messages = SubscribeListener()
        callback_presence = SubscribeListener()

        self.pubnub_listener.add_listener(callback_presence)
        self.pubnub_listener.subscribe().channel_groups(
            gr).with_presence().execute()
        yield callback_presence.wait_for_connect()

        prs_envelope = yield callback_presence.wait_for_presence_on(ch)
        assert prs_envelope.event == 'join'
        assert prs_envelope.uuid == self.pubnub_listener.uuid
        assert prs_envelope.channel == ch
        assert prs_envelope.subscription == gr

        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channel_groups(gr).execute()

        useless, prs_envelope = yield [
            callback_messages.wait_for_connect(),
            callback_presence.wait_for_presence_on(ch)
        ]

        assert prs_envelope.event == 'join'
        assert prs_envelope.uuid == self.pubnub.uuid
        assert prs_envelope.channel == ch
        assert prs_envelope.subscription == gr

        self.pubnub.unsubscribe().channel_groups(gr).execute()

        useless, prs_envelope = yield [
            callback_messages.wait_for_disconnect(),
            callback_presence.wait_for_presence_on(ch)
        ]

        assert prs_envelope.event == 'leave'
        assert prs_envelope.uuid == self.pubnub.uuid
        assert prs_envelope.channel == ch
        assert prs_envelope.subscription == gr

        self.pubnub_listener.unsubscribe().channel_groups(gr).execute()
        yield callback_presence.wait_for_disconnect()

        envelope = yield self.pubnub.remove_channel_from_channel_group(
        ).channel_group(gr).channels(ch).future()
        assert envelope.status.original_response['status'] == 200

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/subscribe_tep_by_step.yaml',
        filter_query_parameters=['uuid', 'seqn'])
    @tornado.testing.gen_test(timeout=30)
    def test_subscribe_step_by_step(self):
        ch1 = 'test-here-now-channel1'
        ch2 = 'test-here-now-channel2'
        ch3 = 'test-here-now-channel3'
        self.pubnub.config.uuid = 'test-here-now-uuid'
        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        print("connecting to the first...")
        self.pubnub.subscribe().channels(ch1).execute()
        yield callback_messages.wait_for_connect()
        print("...connected to the first")
        yield gen.sleep(1)
        print("connecting to the second...")
        self.pubnub.subscribe().channels(ch2).execute()
        self.pubnub.subscribe().channels(ch3).execute()
        self.pubnub.subscribe().channels(ch3).execute()
        self.pubnub.subscribe().channels(ch2).execute()
        print("...connected to the second")
        yield gen.sleep(5)
        env = yield self.pubnub.here_now() \
            .channels([ch1, ch2]) \
            .future()

        assert env.result.total_channels == 2
        assert env.result.total_occupancy >= 1

        channels = env.result.channels

        assert len(channels) == 2
        assert channels[0].occupancy >= 1
        assert channels[0].occupants[0].uuid == self.pubnub.uuid
        assert channels[1].occupancy >= 1
        assert channels[1].occupants[0].uuid == self.pubnub.uuid

        self.pubnub.unsubscribe().channels([ch1, ch2]).execute()
        yield callback_messages.wait_for_disconnect()

        self.pubnub.unsubscribe().channels(ch3).execute()

        self.pubnub.stop()
        self.stop()
示例#16
0
class TestPubNubAsyncHereNow(AsyncTestCase):
    def setUp(self):
        super(TestPubNubAsyncHereNow, self).setUp()
        self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/here_now/single.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pres'])
    @tornado.testing.gen_test(timeout=15)
    def test_here_now_single_channel(self):
        ch = 'test-here-now-channel'
        self.pubnub.config.uuid = 'test-here-now-uuid'
        yield connect_to_channel(self.pubnub, ch)
        yield tornado.gen.sleep(10)
        env = yield self.pubnub.here_now() \
            .channels(ch) \
            .include_uuids(True) \
            .future()

        assert env.result.total_channels == 1
        assert env.result.total_occupancy >= 1

        channels = env.result.channels

        assert len(channels) == 1
        assert channels[0].occupancy == 1
        assert channels[0].occupants[0].uuid == self.pubnub.uuid

        yield disconnect_from_channel(self.pubnub, ch)
        self.pubnub.stop()
        self.stop()

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/here_now/multiple.yaml',
        filter_query_parameters=['uuid', 'tt', 'tr', 'pnsdk', 'l_pres'])
    @tornado.testing.gen_test(timeout=120)
    def test_here_now_multiple_channels(self):
        ch1 = 'test-here-now-channel1'
        ch2 = 'test-here-now-channel2'
        self.pubnub.config.uuid = 'test-here-now-uuid'
        # print("connecting to the first...")
        yield connect_to_channel(self.pubnub, ch1)
        # print("...connected to the first")
        yield gen.sleep(1)
        # print("connecting to the second...")
        self.pubnub.subscribe().channels(ch2).execute()
        # print("...connected to the second")
        yield gen.sleep(5)
        env = yield self.pubnub.here_now() \
            .channels([ch1, ch2]) \
            .future()

        assert env.result.total_channels == 2
        assert env.result.total_occupancy >= 1

        channels = env.result.channels

        assert len(channels) == 2
        assert channels[0].occupancy >= 1
        assert channels[0].occupants[0].uuid == self.pubnub.uuid
        assert channels[1].occupancy >= 1
        assert channels[1].occupants[0].uuid == self.pubnub.uuid

        yield disconnect_from_channel(self.pubnub, [ch1, ch2])
        self.pubnub.stop()
        self.stop()

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/here_now/global.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pres'])
    @tornado.testing.gen_test(timeout=15)
    def test_here_now_global(self):
        ch1 = 'test-here-now-channel1'
        ch2 = 'test-here-now-channel2'
        self.pubnub.config.uuid = 'test-here-now-uuid'

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch1).execute()
        yield callback_messages.wait_for_connect()

        self.pubnub.subscribe().channels(ch2).execute()
        yield gen.sleep(6)

        env = yield self.pubnub.here_now().future()

        assert env.result.total_channels >= 2
        assert env.result.total_occupancy >= 1

        yield disconnect_from_channel(self.pubnub, [ch1, ch2])

        self.pubnub.stop()
        self.stop()
示例#17
0
class TestPubNubAsyncWhereNow(AsyncTestCase):
    def setUp(self):
        super(TestPubNubAsyncWhereNow, self).setUp()
        self.pubnub = PubNubTornado(pnconf_sub_copy(),
                                    custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/where_now/single_channel.yaml',
        filter_query_parameters=['uuid'])
    @tornado.testing.gen_test(timeout=15)
    def test_where_now_single_channel(self):
        ch = "where-now-tornado-ch"
        uuid = "where-now-tornado-uuid"
        self.pubnub.config.uuid = uuid

        yield connect_to_channel(self.pubnub, ch)
        yield gen.sleep(10)
        env = yield self.pubnub.where_now() \
            .uuid(uuid) \
            .future()

        channels = env.result.channels

        assert len(channels) == 1
        assert channels[0] == ch

        yield disconnect_from_channel(self.pubnub, ch)
        self.pubnub.stop()
        self.stop()

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/where_now/multiple_channels.yaml',
        filter_query_parameters=['uuid'])
    @tornado.testing.gen_test(timeout=15)
    def test_multiple_channels(self):
        ch1 = "where-now-tornado-ch1"
        ch2 = "where-now-tornado-ch2"
        uuid = "where-now-tornado-uuid"
        self.pubnub.config.uuid = uuid

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch1).execute()
        yield callback_messages.wait_for_connect()

        self.pubnub.subscribe().channels(ch2).execute()
        yield gen.sleep(5)

        env = yield self.pubnub.where_now() \
            .uuid(uuid) \
            .future()

        channels = env.result.channels

        assert len(channels) == 2
        assert ch1 in channels
        assert ch2 in channels

        yield disconnect_from_channel(self.pubnub, [ch1, ch2])
        self.pubnub.stop()
        self.stop()
示例#18
0
class TestChannelSubscription(AsyncTestCase, SubscriptionTest):
    def setUp(self):
        super(TestChannelSubscription, self).setUp()

        messenger_config = pnconf_sub_copy()
        messenger_config.set_presence_timeout(8)
        messenger_config.uuid = "heartbeat-tornado-messenger"

        listener_config = pnconf_sub_copy()
        listener_config.uuid = "heartbeat-tornado-listener"

        self.pubnub = PubNubTornado(messenger_config, custom_ioloop=self.io_loop)
        self.pubnub_listener = PubNubTornado(listener_config, custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/heartbeat/timeout.yaml',
        filter_query_parameters=['uuid'],
        match_on=['method', 'scheme', 'host', 'port', 'string_list_in_path', 'query'],
        match_on_kwargs={
            'string_list_in_path': {
                'positions': [4]
            }
        })
    @tornado.testing.gen_test(timeout=20)
    def test_timeout_event_on_broken_heartbeat(self):
        ch = "heartbeat-tornado-ch"

        # - connect to :ch-pnpres
        callback_presence = SubscribeListener()
        self.pubnub_listener.add_listener(callback_presence)
        self.pubnub_listener.subscribe().channels(ch).with_presence().execute()
        yield callback_presence.wait_for_connect()

        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert ch == envelope.channel
        assert 'join' == envelope.event
        assert self.pubnub_listener.uuid == envelope.uuid

        # - connect to :ch
        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch).execute()

        # - assert join event
        useless, prs_envelope = yield [
            callback_messages.wait_for_connect(),
            callback_presence.wait_for_presence_on(ch)]
        assert ch == prs_envelope.channel
        assert 'join' == prs_envelope.event
        assert self.pubnub.uuid == prs_envelope.uuid

        # wait for one heartbeat call
        yield gen.sleep(8)

        # - break messenger heartbeat loop
        self.pubnub._subscription_manager._stop_heartbeat_timer()

        # - assert for timeout
        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert ch == envelope.channel
        assert 'timeout' == envelope.event
        assert self.pubnub.uuid == envelope.uuid

        # - disconnect from :ch-pnpres
        self.pubnub_listener.unsubscribe().channels(ch).execute()
        yield callback_presence.wait_for_disconnect()
示例#19
0
class TestChannelSubscription(AsyncTestCase, SubscriptionTest):
    def setUp(self):
        super(TestChannelSubscription, self).setUp()
        self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop)
        self.pubnub_listener = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/sub_unsub.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk'])
    @tornado.testing.gen_test(timeout=300)
    def test_subscribe_unsubscribe(self):
        ch = "subscribe-tornado-ch"

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)

        self.pubnub.subscribe().channels(ch).execute()
        assert ch in self.pubnub.get_subscribed_channels()
        assert len(self.pubnub.get_subscribed_channels()) == 1

        yield callback_messages.wait_for_connect()
        assert ch in self.pubnub.get_subscribed_channels()
        assert len(self.pubnub.get_subscribed_channels()) == 1

        self.pubnub.unsubscribe().channels(ch).execute()
        assert ch not in self.pubnub.get_subscribed_channels()
        assert len(self.pubnub.get_subscribed_channels()) == 0

        yield callback_messages.wait_for_disconnect()
        assert ch not in self.pubnub.get_subscribed_channels()
        assert len(self.pubnub.get_subscribed_channels()) == 0

        self.pubnub.stop()
        self.stop()

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/sub_pub_unsub.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk'])
    @tornado.testing.gen_test(timeout=30)
    def test_subscribe_publish_unsubscribe(self):
        ch = "subscribe-tornado-ch"
        message = "hey"

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch).execute()
        yield callback_messages.wait_for_connect()

        sub_env, pub_env = yield [
            callback_messages.wait_for_message_on(ch),
            self.pubnub.publish().channel(ch).message(message).future()]

        assert pub_env.status.original_response[0] == 1
        assert pub_env.status.original_response[1] == 'Sent'

        assert sub_env.channel == ch
        assert sub_env.subscription is None
        assert sub_env.message == message

        self.pubnub.unsubscribe().channels(ch).execute()
        yield callback_messages.wait_for_disconnect()

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/subscribe/join_leave.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk'])
    @tornado.testing.gen_test(timeout=30)
    def test_join_leave(self):
        ch = "subscribe-tornado-ch"

        # HINT: use random generated uuids to test without VCR
        # rnd = gen_string(4)
        # self.pubnub.config.uuid = "subscribe-tornado-messenger-%s" % rnd
        # self.pubnub_listener.config.uuid = "subscribe-tornado-listener-%s" % rnd

        self.pubnub.config.uuid = "subscribe-tornado-messenger-3"
        self.pubnub_listener.config.uuid = "subscribe-tornado-listener-3"

        callback_presence = SubscribeListener()
        self.pubnub_listener.add_listener(callback_presence)
        self.pubnub_listener.subscribe().channels(ch).with_presence().execute()
        yield callback_presence.wait_for_connect()

        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert envelope.channel == ch
        assert envelope.event == 'join'
        assert envelope.uuid == self.pubnub_listener.uuid

        callback_messages = SubscribeListener()
        self.pubnub.add_listener(callback_messages)
        self.pubnub.subscribe().channels(ch).execute()
        yield callback_messages.wait_for_connect()

        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert envelope.channel == ch
        assert envelope.event == 'join'
        assert envelope.uuid == self.pubnub.uuid

        self.pubnub.unsubscribe().channels(ch).execute()
        yield callback_messages.wait_for_disconnect()

        envelope = yield callback_presence.wait_for_presence_on(ch)
        assert envelope.channel == ch
        assert envelope.event == 'leave'
        assert envelope.uuid == self.pubnub.uuid

        self.pubnub_listener.unsubscribe().channels(ch).execute()
        yield callback_presence.wait_for_disconnect()
        self.pubnub.stop()
        self.stop()