async def _simulate_account_updates(self, account_id: str): self._manager.account_updates_queue.put( models.RawAccountValueData(account=account_id, currency="BASE", key="AvailableFunds", val="25000")) self._manager.account_updates_queue.put( models.RawPortfolioData(account=account_id, contract=ib_contract.Contract(), position=1, market_price=10.5, market_val=10.5, avg_cost=8, unrealised_pnl=2.5, realised_pnl=0)) self._manager.account_updates_queue.put("10:07") self._manager.account_updates_queue.put("10:10") second_contract = ib_contract.Contract() second_contract.conId = 412888950 self._manager.account_updates_queue.put( models.RawPortfolioData(account=account_id, contract=second_contract, position=1, market_price=20689, market_val=20689, avg_cost=20600, unrealised_pnl=89, realised_pnl=0)) self._manager.account_updates_queue.put("10:11") self._manager.account_updates_queue.put(fq.Status.FINISHED)
async def get_us_stock_contract(self, symbol: str) -> ib_contract.Contract: """Resolve the IB US stock contract. Args: symbol (:obj:`str`): Symbol of the target instrument. Returns: ibapi.contract.Contract: Corresponding `Contract` object returned from IB. Raises: ibpy_native.error.IBError: If there is connection issue, or it failed to get additional contract details for the specified symbol. """ contract = ib_contract.Contract() contract.currency = 'USD' contract.exchange = 'SMART' contract.secType = 'STK' contract.symbol = symbol try: result = await self._client.resolve_contract( req_id=self._wrapper.next_req_id, contract=contract) except error.IBError as err: raise err return result
async def test_resolve_contracts_err_1(self): """Test function `resolve_contracts`. * Error returned from IB for an non-resolvable `Contract`. """ with self.assertRaises(error.IBError): # Expect `IBError` await self._client.resolve_contracts(req_id=self._req_id, contract=contract.Contract())
async def test_search_detailed_contracts_err(self): """Test function `search_detailed_contracts`. * Should raise `IBError` for non-resolveable `Contract """ with self.assertRaises(error.IBError): await self._bridge.search_detailed_contracts( contract=contract.Contract())
async def test_get_earliest_data_point_err(self): """Test function `get_earliest_data_point`. * Should raise `IBError` for invalid `Contract`. """ with self.assertRaises(error.IBError): await self._bridge.get_earliest_data_point( contract=contract.Contract(), data_type=datatype.EarliestDataPoint.BID)
def get_contract(self, symbol, secType='STK', currency='USD', exchange='SMART', futures_month=None): sec_contract = contract.Contract() sec_contract.includeExpired = True sec_contract.symbol = symbol sec_contract.secType = secType sec_contract.currency = currency sec_contract.exchange = exchange sec_contract.lastTradeDateOrContractMonth = futures_month return sec_contract
def gbp_usd_fx() -> ib_contract.Contract: """FX GBP.USD""" contract = ib_contract.Contract() contract.symbol = "GBP" contract.secType = "CASH" contract.currency = "USD" contract.exchange = "IDEALPRO" return contract
def us_stock() -> ib_contract.Contract: """US stock - AAPL""" contract = ib_contract.Contract() contract.symbol = "AAPL" contract.secType = "STK" contract.exchange = "ISLAND" contract.currency = "USD" return contract
def appl_contract(): c = contract.Contract() c.conId = 265598 c.symbol = 'AAPL' c.secType = 'STK' c.exchange = 'SMART' c.currency = 'USD' c.localSymbol = 'AAPL' c.tradingClass = 'NMS' return c
def us_future() -> ib_contract.Contract: """US future - YM""" contract = ib_contract.Contract() contract.symbol = "YM" contract.secType = "FUT" contract.exchange = "ECBOT" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "202009" return contract
async def test_resolve_head_timestamp_err_1(self): """Test function `resolve_head_timestamp`. * Error returned from IB for non-resolvable `Contract`. """ with self.assertRaises(error.IBError): await self._client.resolve_head_timestamp( req_id=self._req_id, contract=contract.Contract(), show=datatype.EarliestDataPoint.ASK)
def ibkr_contract(): c = contract.Contract() c.conId = 43645865 c.symbol = 'IBKR' c.secType = 'STK' c.exchange = 'SMART' c.currency = 'USD' c.localSymbol = 'IBKR' c.tradingClass = 'NMS' return c
async def main(): """Entry point""" gbp_usd_fx = contract.Contract() gbp_usd_fx.symbol = "GBP" gbp_usd_fx.secType = "CASH" gbp_usd_fx.currency = "USD" gbp_usd_fx.exchange = "IDEALPRO" connection_listener = ConnectionListener() bridge = ibpy_native.IBBridge(port=int(os.getenv("IB_PORT", "4002")), connection_listener=connection_listener, notification_listener=NotificationListener()) while not connection_listener.connected: await asyncio.sleep(1) contract_results = await bridge.search_detailed_contracts( contract=gbp_usd_fx) gbp_usd_fx = contract_results[0].contract print(f"Contract - {gbp_usd_fx}") tickers = [] try: async for data in bridge.req_historical_ticks( contract=gbp_usd_fx, start=datetime.datetime(year=2021, month=1, day=4, hour=10), end=datetime.datetime(year=2021, month=1, day=4, hour=10, minute=5), tick_type=datatype.HistoricalTicks.BID_ASK, retry=5): print(".", end="", flush=True) for tick in data.ticks: time = (datetime.datetime.fromtimestamp(tick.time).astimezone( pytz.timezone("America/New_York"))) tickers.append({ "time": time, "bid_price": tick.priceBid, "ask_price": tick.priceAsk, "bid_size": tick.sizeBid, "ask_size": tick.sizeAsk, }) except error.IBError as err: print(err) return cols = ["time", "bid_price", "ask_price", "bid_size", "ask_size"] dataframe = pd.DataFrame(data=tickers, columns=cols) print(dataframe) bridge.disconnect()
def getContractInfo(self, stockInfo): c = contract.Contract() c.conId = 0 c.symbol = stockInfo["symbol"] c.exchange = stockInfo["exchange"] c.currency = stockInfo["currency"] c.secType = stockInfo["secType"] if "primaryExchange" in stockInfo: c.primaryExchange = stockInfo["primaryExchange"] c.includeExpired = stockInfo["includeExpired"] return c
def us_future_expired() -> ib_contract.Contract: """Expired US future - YM 2020.06""" contract = ib_contract.Contract() contract.symbol = "YM" contract.secType = "FUT" contract.exchange = "ECBOT" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "202006" contract.includeExpired = True return contract
async def test_req_historical_ticks_err_2(self): """Test function `req_historical_ticks`. * `IBError` raised due to unresolvable IB `Contract` """ 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=contract.Contract(), start_date_time=self._start.replace(tzinfo=None), show=datatype.HistoricalTicks.BID_ASK)
def us_future_expired() -> ib_contract.Contract: """Expired US future""" contract = ib_contract.Contract() contract.symbol = "YM" contract.secType = "FUT" contract.exchange = "ECBOT" contract.currency = "USD" # Targets the latest contract of last year contract.lastTradeDateOrContractMonth = ( f"{datetime.datetime.now().year-1}12") contract.includeExpired = True return contract
async def test_req_historical_ticks_err_3(self): """Test function `req_historical_ticks`. * Expect `IBError` due to unresolvable `Contract`. """ with self.assertRaises(error.IBError): async for _ in self._bridge.req_historical_ticks( contract=contract.Contract(), start=self._start, end=self._end, tick_type=datatype.HistoricalTicks.BID_ASK, retry=0): pass
def __init__(self, client: client_impl.EClient, sub_limit): self.clientObj = client self.subscription_lim = sub_limit self.under_reqId = None self.gen_opt = contract.Contract() self.permanentsub = None self.permanentsub_id = None # Permanent id go from 3000 on self.float_groups = None self.floatsub = None self.floatsub_id = None # Float id go from 4000 on self.floatsub_helper = None self.sub_exists = False self.exit_trigger = False self.active = False
def subscription(self, underlying_contract, expiration): # CONTRACTS self.underlyingcontract = underlying_contract self.under_price_ticker = 1000 self.opt_gen_contract = contract.Contract() self.opt_gen_contract.symbol = self.underlyingcontract.symbol self.opt_gen_contract.lastTradeDateOrContractMonth = expiration self.opt_gen_contract.secType = "OPT" self.opt_gen_contract.exchange = "SMART" self.opt_gen_contract.currency = self.underlyingcontract.currency self.opt_gen_contract.multiplier = "100" self.request_generic_info(self.underlyingcontract) self.request_chain_info(self.opt_gen_contract) self._run_subscription()
async def get_us_future_contract( self, symbol: str, contract_month: Optional[str] = None) -> ib_contract.Contract: """Search the US future contract from IB. Args: symbol (:obj:`str`): Symbol of the target instrument. contract_month (:obj:`str`, optional): Contract month for the target future contract in format - "YYYYMM". Defaults to None. Returns: ibapi.contract.Contract: Corresponding `Contract` object returned from IB. The current on going contract will be returned if `contract_month` is left as `None`. Raises: ibpy_native.error.IBError: If there is connection related issue, or it failed to get additional contract details for the specified symbol. """ include_expired = False if contract_month is None: contract_month = '' else: if len(contract_month) != 6 or not contract_month.isdecimal(): raise ValueError( "Value of argument `contract_month` should be in format of " "'YYYYMM'") include_expired = True contract = ib_contract.Contract() contract.currency = 'USD' contract.secType = 'FUT' contract.includeExpired = include_expired contract.symbol = symbol contract.lastTradeDateOrContractMonth = contract_month try: result = await self._client.resolve_contract( req_id=self._wrapper.next_req_id, contract=contract) except error.IBError as err: raise err return result
def us_future() -> ib_contract.Contract: """US future - YM""" # Generate contract month dynamically now = datetime.datetime.now() month = now.month for i in [3, 6, 9, 12]: if month < i: month = i break contract = ib_contract.Contract() contract.symbol = "YM" contract.secType = "FUT" contract.exchange = "ECBOT" contract.currency = "USD" contract.lastTradeDateOrContractMonth = f"{now.year}{month:02d}" return contract
async def test_fetch_historical_ticks_err(self): """Test function `fetch_historical_ticks` for the error cases.""" # Timezone of start & end are not identical with self.assertRaises(ValueError): await self._client.fetch_historical_ticks( req_id=Const.RID_FETCH_HISTORICAL_TICKS_ERR.value, contract=sample_contracts.gbp_usd_fx(), start=datetime.datetime.now()\ .astimezone(pytz.timezone('Asia/Hong_Kong')), end=datetime.datetime.now()\ .astimezone(pytz.timezone('America/New_York')) ) # Invalid contract object with self.assertRaises(error.IBError): await self._client.fetch_historical_ticks( req_id=Const.RID_FETCH_HISTORICAL_TICKS_ERR.value, contract=ib_contract.Contract(), start=datetime.datetime(2020, 5, 20, 3, 20, 0)\ .astimezone(ibpy_client._IBClient.TZ), end=datetime.datetime.now().astimezone(ibpy_client._IBClient.TZ) )
def main(): ibapi_client = IbApiClient('', _IB_GATEWAY_PROD_PORT, 123) print('Account Summary: ', ibapi_client.get_account_summary()) # positions = ibapi_client.get_positions() # print('\nPositions: ', positions) # print('\nOpen Orders: ', ibapi_client.get_open_orders()) c = contract.Contract() c.symbol = 'AAPL' c.secType = 'STK' c.exchange = 'SMART' c.currency = 'USD' c.localSymbol = 'AAPL' hd = ibapi_client.get_historical_data( contract=c, data_options=historical_data.HistoricalDataOptions( end_datetime=None, duration=historical_data.Duration( 2, historical_data.Duration.Unit.WEEK), bar_size=historical_data.BAR_SIZE_2_HOUR, type=historical_data.HistoricalDataOptions.Type.TRADES)) print('\nHistorical data ', hd)
class TestClient(EClient): def __init__(self, wrapper): EClient.__init__(self, wrapper) class TestApp(TestWrapper, TestClient): def __init__(self): TestWrapper.__init__(self) TestClient.__init__(self, wrapper=self) def contractDetails(self, reqID: int, contractDetails: contract.ContractDetails): super().contractDetails(reqID, contractDetails) printinstance(contractDetails.summary) def contractDetailsEnd(self, reqID: int): super().contractDetailsEnd(reqID) print("contractDetailsEnd. ", reqID, "\n") if __name__ == '__main__': app = TestApp() app.connect('127.0.0.1', 4002, clientId=0) # New contract. contract = contract.Contract() contract.secType = "NEWS" contract.exchange = "BT" app.reqContractDetails(213, contract)
import time from ibapi import contract import options_collector as col # MAKE SURE THE EXPIRATIONS ACTUALLY EXIST! underlying = contract.Contract() underlying.conId = 756733 underlying.symbol = "SPY" underlying.exchange = "SMART" underlying.secType = "STK" underlying.currency = "USD" collector = col.OptionsCollector() collector.subscription(underlying, 20180720) time.sleep(2) collector.disconnect_subscription() print('First chain done') collector.subscription(underlying, 20180713) time.sleep(2) print(collector.retrieve_option_chain())
import datetime import os import copy from ibapi import contract import options_collector as col local_offset = time.timezone / 3600 cst_timezone = datetime.timezone(offset=datetime.timedelta(hours=-6 - local_offset), name='CST') dateformat = "%Y%m%d%H%M%S" # info from: https://pennies.interactivebrokers.com/cstools/contract_info/ spy = contract.Contract() spy.conId = 756733 spy.symbol = "SPY" spy.exchange = "SMART" spy.secType = "STK" spy.currency = "USD" spx = contract.Contract() spx.conId = 416904 spx.symbol = "SPX" spx.exchange = "CBOE" spx.secType = "IND" spx.currency = "USD" collector = col.OptionsCollector() collector.request_contract_info(spy)