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)
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)
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)
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)
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))
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.")
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)
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
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)
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)
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))
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())
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
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)
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)
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)
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)
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)
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)
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)
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)
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
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)
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 )
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)
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
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)
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)
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)
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)