コード例 #1
0
    async def test_fetch_historical_ticks(self):
        """Test function `fetch_historical_ticks`."""
        data = await self._client.fetch_historical_ticks(
            req_id=Const.RID_FETCH_HISTORICAL_TICKS.value,
            contract=sample_contracts.gbp_usd_fx(),
            start=ibpy_client._IBClient.TZ.localize(datetime\
                .datetime(2020, 4, 29, 10, 30, 0)),
            end=ibpy_client._IBClient.TZ.localize(datetime\
                .datetime(2020, 4, 29, 10, 35, 0)),
            show=dt.HistoricalTicks.MIDPOINT
        )

        self.assertIsInstance(data['ticks'], list)
        self.assertTrue(data['completed'])
        self.assertTrue(data['ticks'])
        self.assertIsInstance(data['ticks'][0], ib_wrapper.HistoricalTick)

        data = await self._client.fetch_historical_ticks(
            req_id=Const.RID_FETCH_HISTORICAL_TICKS.value,
            contract=sample_contracts.gbp_usd_fx(),
            start=ibpy_client._IBClient.TZ.localize(datetime\
                .datetime(2020, 4, 29, 10, 30, 0)),
            end=ibpy_client._IBClient.TZ.localize(datetime\
                .datetime(2020, 4, 29, 10, 35, 0)),
            show=dt.HistoricalTicks.BID_ASK
        )

        self.assertIsInstance(data['ticks'], list)
        self.assertTrue(data['completed'])
        self.assertTrue(data['ticks'])
        self.assertIsInstance(data['ticks'][0],
                              ib_wrapper.HistoricalTickBidAsk)
コード例 #2
0
    async def test_search_detailed_contracts(self):
        """Test function `search_detailed_contracts`."""
        result = await self._bridge.search_detailed_contracts(
            contract=sample_contracts.gbp_usd_fx())

        self.assertTrue(result)
        self.assertNotEqual(result[0].contract.conId, 0)
コード例 #3
0
    async def test_cancel_live_ticks_stream(self):
        """Test function `cancel_live_ticks_stream`."""
        async def cancel_req():
            await asyncio.sleep(3)
            self._client.cancel_live_ticks_stream(
                req_id=Const.RID_CANCEL_LIVE_TICKS_STREAM.value)

        listener = utils.MockLiveTicksListener()

        stream = asyncio.create_task(
            self._client.stream_live_ticks(
                req_id=Const.RID_CANCEL_LIVE_TICKS_STREAM.value,
                contract=sample_contracts.gbp_usd_fx(),
                listener=listener,
                tick_type=dt.LiveTicks.BID_ASK))
        cancel = asyncio.create_task(cancel_req())

        try:
            await stream
            await cancel
        except error.IBError as err:
            tasks = asyncio.all_tasks()
            for task in tasks:
                task.cancel()

            raise err

        self.assertTrue(listener.finished)
コード例 #4
0
    async def test_stream_live_ticks(self):
        """Test function `stream_live_ticks`."""
        async def cancel_req():
            await asyncio.sleep(5)
            self._client.cancelTickByTickData(
                reqId=Const.RID_STREAM_LIVE_TICKS.value)

            queue = self._wrapper.get_request_queue_no_throw(
                req_id=Const.RID_STREAM_LIVE_TICKS)
            queue.put(element=fq._Status.FINISHED)

        listener = utils.MockLiveTicksListener()

        stream = asyncio.create_task(
            self._client.stream_live_ticks(
                req_id=Const.RID_STREAM_LIVE_TICKS.value,
                contract=sample_contracts.gbp_usd_fx(),
                listener=listener,
                tick_type=dt.LiveTicks.BID_ASK))
        cancel = asyncio.create_task(cancel_req())

        try:
            await stream
            await cancel
        except error.IBError as err:
            tasks = asyncio.all_tasks()
            for task in tasks:
                task.cancel()

            raise err

        self.assertTrue(listener.ticks)
        self.assertTrue(listener.finished)
コード例 #5
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
 async def _start_streaming(self, req_id: int) -> asyncio.Task:
     return asyncio.create_task(
         self._client.stream_live_ticks(
             req_id,
             contract=sample_contracts.gbp_usd_fx(),
             listener=self._listener,
             tick_type=datatype.LiveTicks.BID_ASK))
コード例 #6
0
 async def test_get_earliest_data_point(self):
     """Test function `get_earliest_data_point`."""
     try:
         await self._bridge.get_earliest_data_point(
             contract=sample_contracts.gbp_usd_fx(),
             data_type=datatype.EarliestDataPoint.BID)
     except error.IBError:
         self.fail("Test fail as unexpected `IBError` raised.")
コード例 #7
0
    async def test_resolve_contract(self):
        """Test function `resolve_contract`."""
        resolved_contract = await self._client.resolve_contract(
            req_id=Const.RID_RESOLVE_CONTRACT.value,
            contract=sample_contracts.gbp_usd_fx())

        self.assertIsNotNone(resolved_contract)
        print(resolved_contract)
コード例 #8
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
    async def test_resolve_head_timestamp(self):
        """Test function `resolve_head_timestamp`."""
        result = await self._client.resolve_head_timestamp(
            req_id=self._req_id,
            contract=sample_contracts.gbp_usd_fx(),
            show=datatype.EarliestDataPoint.ASK)

        self.assertIsInstance(result, int)  # Expect epoch returned as `int`
        self.assertGreater(result, 0)  # Expect a valid epoch value
コード例 #9
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
    async def test_resolve_contracts(self):
        """Test function `resolve_contracts`."""
        result = await self._client.resolve_contracts(
            req_id=self._req_id, contract=sample_contracts.gbp_usd_fx())

        self.assertTrue(result)  # Expect item returned from request
        # Expect a propulated `ContractDetails` received from IB
        self.assertIsInstance(result[0], contract.ContractDetails)
        self.assertNotEqual(result[0].contract.conId, 0)
コード例 #10
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
    async def test_submit_order(self):
        """Test function `submit_order`."""
        order_id = await self._client.req_next_order_id()

        await self._client.submit_order(contract=sample_contracts.gbp_usd_fx(),
                                        order=sample_orders.mkt(
                                            order_id=order_id,
                                            action=datatype.OrderAction.BUY))
        self.assertTrue(order_id in self._orders_manager.open_orders)
コード例 #11
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
    async def test_submit_order_err(self):
        """Test function `submit_order`.

        * Error returned from IB for duplicated order ID.
        """
        with self.assertRaises(error.IBError):
            await self._client.submit_order(
                contract=sample_contracts.gbp_usd_fx(),
                order=sample_orders.mkt(order_id=1,
                                        action=datatype.OrderAction.BUY))
コード例 #12
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
    async def test_resolve_contracts_err_0(self):
        """Test function `resolve_contracts`.

        * Queue associated with `_req_id` is being occupied.
        """
        # Mock queue occupation
        self._wrapper.get_request_queue(req_id=self._req_id)
        with self.assertRaises(error.IBError):  # Expect `IBError`
            await self._client.resolve_contracts(
                req_id=self._req_id, contract=sample_contracts.gbp_usd_fx())
コード例 #13
0
    async def test_cancel_order(self):
        """Test function `cancel_order`."""
        order_id = await self._client.req_next_order_id()

        order_submit_task = asyncio.create_task(self._client.submit_order(
            contract=sample_contracts.gbp_usd_fx(),
            order=sample_orders.no_transmit(order_id)
        ))
        await asyncio.sleep(0.5) # Give the order time to arrive at TWS/Gateway
        self._client.cancel_order(order_id)
        await order_submit_task
コード例 #14
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
    async def test_req_historical_ticks_err_0(self):
        """Test function `req_historical_ticks`.

        * Expect `ValueError` for aware datetime object passed in.
        """
        with self.assertRaises(ValueError):
            await self._client.req_historical_ticks(
                req_id=self._req_id,
                contract=sample_contracts.gbp_usd_fx(),
                start_date_time=self._start,
                show=datatype.HistoricalTicks.BID_ASK)
コード例 #15
0
    async def test_open_order(self):
        """Test overridden function `openOrder`."""
        order_id = await self._client.req_next_order_id()
        self._client.placeOrder(
            orderId=order_id, contract=sample_contracts.gbp_usd_fx(),
            order=sample_orders.mkt(order_id=order_id,
                                    action=datatype.OrderAction.BUY)
        )
        await asyncio.sleep(1)

        self.assertTrue(order_id in self._orders_manager.open_orders)
コード例 #16
0
    async def test_order_status(self):
        """Test overridden function `orderStatus`."""
        order_id = await self._client.req_next_order_id()
        self._client.placeOrder(
            orderId=order_id, contract=sample_contracts.gbp_usd_fx(),
            order=sample_orders.mkt(order_id=order_id,
                                    action=datatype.OrderAction.SELL)
        )
        await asyncio.sleep(1)

        self.assertTrue(self._orders_manager.open_orders[order_id].exec_rec)
コード例 #17
0
    async def test_stop_live_ticks_stream(self):
        """Test function `stop_live_ticks_stream`."""
        req_id = await self._bridge.stream_live_ticks(
            contract=sample_contracts.gbp_usd_fx(),
            listener=self._listener,
            tick_type=datatype.LiveTicks.BID_ASK)
        await asyncio.sleep(0.5)

        self._bridge.stop_live_ticks_stream(stream_id=req_id)
        await asyncio.sleep(0.5)
        self.assertTrue(self._listener.finished)
コード例 #18
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
    async def test_resolve_head_timestamp_err_0(self):
        """Test function `resolve_head_timestamp`.

        * Queue associated with `_req_id` is being occupied.
        """
        # Mock queue occupation
        self._wrapper.get_request_queue(req_id=self._req_id)
        with self.assertRaises(error.IBError):
            await self._client.resolve_head_timestamp(
                req_id=self._req_id,
                contract=sample_contracts.gbp_usd_fx(),
                show=datatype.EarliestDataPoint.ASK)
コード例 #19
0
 async def test_update_portfolio(self):
     """Test overridden function `updatePortfolio`."""
     # Mock portfolio data received from IB
     self._wrapper.updatePortfolio(
         contract=sample_contracts.gbp_usd_fx(), position=1000,
         marketPrice=1.38220, marketValue=1382.2, averageCost=1.33327,
         unrealizedPNL=48.93, realizedPNL=0, accountName="DU0000140"
     )
     self._delegate.account_updates_queue.put(element=fq.Status.FINISHED)
     results = await self._delegate.account_updates_queue.get()
     # Expect instance of `RawPortfolioData` in `account_updates_queue`
     self.assertIsInstance(results[0], models.RawPortfolioData)
コード例 #20
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
    async def test_req_historical_ticks_err_1(self):
        """Test function `req_historical_ticks`.

        * `IBError` raised due to `req_id` is being occupied by other task
        """
        self._wrapper.get_request_queue(req_id=self._req_id)
        with self.assertRaises(error.IBError):
            await self._client.req_historical_ticks(
                req_id=self._req_id,
                contract=sample_contracts.gbp_usd_fx(),
                start_date_time=self._start.replace(tzinfo=None),
                show=datatype.HistoricalTicks.BID_ASK)
コード例 #21
0
    async def test_stop_live_ticks_stream(self):
        """Test functions `stop_live_ticks_stream`."""
        listener = utils.MockLiveTicksListener()

        stream_id = await self._bridge.stream_live_ticks(
            contract=sample_contracts.gbp_usd_fx(),
            listener=listener, tick_type=dt.LiveTicks.BID_ASK
        )

        await asyncio.sleep(2)
        self._bridge.stop_live_ticks_stream(stream_id=stream_id)
        await asyncio.sleep(0.5)
        self.assertTrue(listener.finished)
コード例 #22
0
    async def test_req_historical_ticks_err_4(self):
        """Test function `req_historical_ticks`.

        * Expect `IBError` due to IB returning an error
        """
        with self.assertRaises(error.IBError):
            async for _ in self._bridge.req_historical_ticks(
                    contract=sample_contracts.gbp_usd_fx(),
                    start=self._start,
                    end=self._end,
                    tick_type=datatype.HistoricalTicks.TRADES,
                    retry=0):
                pass
コード例 #23
0
ファイル: test_bridge.py プロジェクト: jihunkim0/ibpy_native
    async def test_req_historical_ticks_1(self):
        """Test function `req_historical_ticks`.

        * Reqest tick data for `MIDPOINT`.
        """
        async for result in self._bridge.req_historical_ticks(
                contract=sample_contracts.gbp_usd_fx(),
                start=self._start,
                end=self._end,
                tick_type=datatype.HistoricalTicks.MIDPOINT,
                retry=0):
            self.assertTrue(result.ticks)
            self.assertIsInstance(result.ticks[0], wrapper.HistoricalTick)
コード例 #24
0
    async def test_stream_live_ticks_err(self):
        """Test function `stream_live_ticks`.

        * Should raise `IBError` as queue associated with `_req_id` being
          occupied.
        """
        # Mock queue occupation
        self._wrapper.get_request_queue(req_id=self._req_id)
        with self.assertRaises(error.IBError):
            await self._client.stream_live_ticks(
                req_id=self._req_id, contract=sample_contracts.gbp_usd_fx(),
                listener=self._listener, tick_type=datatype.LiveTicks.BID_ASK
            )
コード例 #25
0
ファイル: test_client.py プロジェクト: jihunkim0/ibpy_native
    async def test_req_historical_ticks_1(self):
        """Test function `req_historical_ticks`.

        * Request tick data for `MidPoint`.
        """
        result = await self._client.req_historical_ticks(
            req_id=self._req_id,
            contract=sample_contracts.gbp_usd_fx(),
            start_date_time=self._start.replace(tzinfo=None),
            show=datatype.HistoricalTicks.MIDPOINT)

        self.assertTrue(result)
        self.assertIsInstance(result, list)
        self.assertIsInstance(result[0], wrapper.HistoricalTick)
コード例 #26
0
    async def test_req_historical_ticks_err_1(self):
        """Test function `req_historical_ticks`.

        * Expect `ValueError` due to value of `end` is an aware datetime
          object.
        """
        with self.assertRaises(ValueError):
            async for _ in self._bridge.req_historical_ticks(
                    contract=sample_contracts.gbp_usd_fx(),
                    start=self._start,
                    end=_global.TZ.localize(self._end),
                    tick_type=datatype.HistoricalTicks.BID_ASK,
                    retry=0):
                pass
コード例 #27
0
    async def test_tick_by_tick_mid_point(self):
        """Test overridden function `tickByTickMidPoint`."""
        self._client.reqTickByTickData(
            reqId=self._req_id, contract=sample_contracts.gbp_usd_fx(),
            tickType=datatype.LiveTicks.MIDPOINT.value, numberOfTicks=0,
            ignoreSize=True
        )

        async for elem in self._queue.stream():
            if elem is fq.Status.FINISHED:
                continue # Let the async task finish
            if not self._received:
                # Expect `HistoricalTickLast` to be sent to queue
                self.assertIsInstance(elem, wrapper.HistoricalTick)
                await self._stop_streaming(req_id=self._req_id)
コード例 #28
0
    async def test_stream_live_ticks(self):
        """Test function `stream_live_ticks`."""
        client: ibpy_client._IBClient = self._bridge._client
        listener = utils.MockLiveTicksListener()

        req_id = await self._bridge.stream_live_ticks(
            contract=sample_contracts.gbp_usd_fx(),
            listener=listener, tick_type=dt.LiveTicks.BID_ASK
        )
        self.assertIsNotNone(req_id)

        await asyncio.sleep(5)
        self.assertTrue(listener.ticks)
        client.cancel_live_ticks_stream(req_id=req_id)
        await asyncio.sleep(0.5)
コード例 #29
0
    async def test_cancel_order(self):
        """Test function `cancel_order`.

        * This test will fail when the market is closed.
        """
        order = sample_orders.lmt(order_id=await self._bridge.next_order_id(),
                                  action=datatype.OrderAction.SELL,
                                  price=3)
        await self._bridge.place_orders(contract=sample_contracts.gbp_usd_fx(),
                                        orders=[order])
        self._bridge.cancel_order(order_id=order.orderId)
        await asyncio.sleep(0.5)  # Give time the cancel request to arrive IB
        self.assertEqual(
            self._orders_manager.open_orders[order.orderId].status,
            datatype.OrderStatus.CANCELLED)
コード例 #30
0
    async def test_contract_details(self):
        """Test overridden function `contractDetails`.

        * `contractDetailsEnd` will be invoked after `contractDetails`.
        """
        req_id = self._wrapper.next_req_id
        queue = self._wrapper.get_request_queue(req_id)

        self._client.reqContractDetails(reqId=req_id,
                                        contract=sample_contracts.gbp_usd_fx())
        await asyncio.sleep(0.5)
        result = await queue.get()

        self.assertTrue(result) # Expect item from queue
        # Expect the resolved `ContractDetails` object to be returned
        self.assertIsInstance(result[0], contract.ContractDetails)