### Initialize and Start Watchdog Source: https://ib-insync.readthedocs.io/api.html Example of how to initialize and start the Watchdog to monitor the IB connection. This includes setting up an event handler for connection events and running the IB instance. ```python def onConnected(): print(ib.accountValues()) ibc = IBC(974, gateway=True, tradingMode='paper') ib = IB() ib.connectedEvent += onConnected watchdog = Watchdog(ibc, ib, port=4002) watchdog.start() ib.run() ``` -------------------------------- ### Initialize and Start IBC Source: https://ib-insync.readthedocs.io/api.html Initialize the IBC controller with account details and start TWS/Gateway. Ensure the correct event loop is set for Windows. ```python import asyncio asyncio.set_event_loop(asyncio.ProactorEventLoop()) from ib_insync import * ibc = IBC(976, gateway=True, tradingMode='live', userid='edemo', password='demouser') ibc.start() IB.run() ``` -------------------------------- ### Watchdog Example Usage Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html Demonstrates how to use the Watchdog class to manage the connection and health of the IB TWS or Gateway application. It includes setting up event handlers and starting the watchdog. ```python .. code-block:: python def onConnected(): print(ib.accountValues()) ibc = IBC(974, gateway=True, tradingMode='paper') ib = IB() ib.connectedEvent += onConnected watchdog = Watchdog(ibc, ib, port=4002) watchdog.start() ib.run() ``` -------------------------------- ### IB Connection and Disconnection Example Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Demonstrates connecting to the IB TWS API on localhost and then disconnecting. This is a basic setup for testing connectivity. ```python loop = util.getLoop() loop.set_debug(True) util.logToConsole(logging.DEBUG) ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) ib.disconnect() ``` -------------------------------- ### startApi Source: https://ib-insync.readthedocs.io/api.html Starts the API. This method initializes the API connection. ```APIDOC ## startApi ### Description Starts the API. ### Method startApi() ``` -------------------------------- ### Install ib-insync Source: https://ib-insync.readthedocs.io/ Install the ib-insync library using pip. Ensure Python 3.6+ and a running TWS or IB Gateway (v1023+) with API port enabled. ```bash pip install ib_insync ``` -------------------------------- ### Start API Source: https://ib-insync.readthedocs.io/_modules/ib_insync/client.html Initiates the connection and startup sequence for the IB API client. ```python self.send() ``` -------------------------------- ### Start Watchdog Runner Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html Initiates the Watchdog's asynchronous run loop, logging the start event and returning the created asyncio task. ```python def start(self): self._logger.info('Starting') self.startingEvent.emit(self) self._runner = asyncio.ensure_future(self.runAsync()) return self._runner ``` -------------------------------- ### Asynchronous Start TWS/Gateway Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html Asynchronously starts the TWS or IB Gateway client. This is the underlying method called by `start()`. ```python await ibc.startAsync() ``` -------------------------------- ### startApi Source: https://ib-insync.readthedocs.io/_modules/ib_insync/client.html Starts the API connection. This method initiates the connection to the Interactive Brokers API. ```APIDOC ## startApi ### Description Starts the API connection. ### Method `startApi(self)` ``` -------------------------------- ### reqPnLSingle Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Starts a subscription for single PnL events. This method is blocking. ```APIDOC ## reqPnLSingle ### Description Starts a subscription for single PnL events. This method is blocking. ### Method `reqPnLSingle(account: str, modelCode: str, conId: int)` ### Parameters #### Path Parameters - **account** (str) - Required - Subscribe to this account. - **modelCode** (str) - Required - If specified, filter for this account model. - **conId** (int) - Required - Contract identifier. ``` -------------------------------- ### startLoop Source: https://ib-insync.readthedocs.io/_modules/ib_insync/util.html Initializes and starts a nested asyncio event loop, specifically designed for use within Jupyter notebooks. ```APIDOC ## startLoop() ### Description Use nested asyncio event loop for Jupyter notebooks. ``` -------------------------------- ### Start a Live Subscription Source: https://ib-insync.readthedocs.io/_modules/ib_insync/wrapper.html Registers a new live subscription, associating a request ID with a subscriber object and optionally a contract. ```python def startSubscription(self, reqId, subscriber, contract=None): """Register a live subscription.""" self._reqId2Contract[reqId] = contract self.reqId2Subscriber[reqId] = subscriber ``` -------------------------------- ### PnLSingle Subscription Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Starts a subscription for profit and loss events for single positions. Returns a PnLSingle object that is kept live updated. ```APIDOC ## reqPnLSingle ### Description Start a subscription for profit and loss events for single positions. Returns a :class:`.PnLSingle` object that is kept live updated. The result can also be queried from :meth:`.pnlSingle`. ### Method (Implicitly POST or similar, as it initiates a subscription) ### Endpoint (Not applicable for SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python ib.reqPnLSingle(account='...', modelCode='...', conId=123) ``` ### Response #### Success Response (200) - **PnLSingle** (object) - A PnLSingle object that is kept live updated. #### Response Example (PnLSingle object structure not detailed in source) ``` -------------------------------- ### Start TWS/Gateway with IBC Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html Starts the TWS or IB Gateway client application managed by IBC. This method is blocking and will run until the client is terminated. ```python ibc.start() ``` -------------------------------- ### IBC Command Line Construction Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html Illustrates how the command line arguments are constructed for starting IBC, mapping dataclass fields to command-line options based on the operating system. ```python args = dict( twsVersion=('', ''), gateway=('--gateway', '/Gateway'), tradingMode=('--mode=', '/Mode:'), twsPath=('--tws-path=', '/TwsPath:'), twsSettingsPath=('--tws-settings-path=', ''), ibcPath=('--ibc-path=', '/IbcPath:'), ibcIni=('--ibc-ini=', '/Config:'), javaPath=('--java-path=', '/JavaPath:'), userid=('--user=', '/User:'), password=('--pw=', '/PW:'), fixuserid=('--fix-user=', '/FIXUser:'), fixpassword=('--fix-pw=', '/FIXPW:'), on2fatimeout=('--on2fatimeout=', '/On2FATimeout:'), ) # create shell command cmd = [ f'{self.ibcPath}\scripts\StartIBC.bat' if self._isWindows else f'{self.ibcPath}/scripts/ibcstart.sh'] for k, v in util.dataclassAsDict(self).items(): arg = args[k][self._isWindows] if v: if arg.endswith('=') or arg.endswith(':'): cmd.append(f'{arg}{v}') elif arg: cmd.append(arg) else: cmd.append(str(v)) ``` -------------------------------- ### IBC Source: https://ib-insync.readthedocs.io/api.html Programmatic control over starting and stopping TWS/Gateway using IBC. ```APIDOC ## IBC Programmatic control over starting and stopping TWS/Gateway using IBC. ### Parameters - **twsVersion** (int) - Required - The major version number for TWS or gateway. - **gateway** (bool) - Optional - True for gateway, False for TWS. - **tradingMode** (str) - Optional - 'live' or 'paper'. - **userid** (str) - Optional - IB account username. - **password** (str) - Optional - IB account password. - **twsPath** (str) - Optional - Path to the TWS installation folder. - **twsSettingsPath** (str) - Optional - Path to the TWS settings folder. - **ibcPath** (str) - Optional - Path to the IBC installation folder. - **ibcIni** (str) - Optional - Path to the IBC configuration file. - **javaPath** (str) - Optional - Path to Java executable. - **fixuserid** (str) - Optional - FIX account user id (gateway only). - **fixpassword** (str) - Optional - FIX account password (gateway only). - **on2fatimeout** (str) - Optional - What to do if 2-factor authentication times out; Can be 'restart' or 'exit'. ### Methods - **start()**: Launch TWS/IBG. - **terminate()**: Terminate TWS/IBG. - **startAsync()**: Asynchronously launch TWS/IBG. - **terminateAsync()**: Asynchronously terminate TWS/IBG. - **monitorAsync()**: Asynchronously monitor TWS/IBG. - **dict()**: Return dataclass values as dict. - **nonDefaults()**: Get fields that are different from default values and return as dict. - **tuple()**: Return dataclass values as tuple. - **update(\*srcObjs, **kwargs)**: Update fields of the given dataclass object. ``` -------------------------------- ### reqPnLSingle Source: https://ib-insync.readthedocs.io/api.html Starts a subscription for profit and loss events for single positions. Returns a `PnLSingle` object that is kept live updated. The result can also be queried from `pnlSingle()`. ```APIDOC ## reqPnLSingle(_account_ , _modelCode_ , _conId_) ### Description Start a subscription for profit and loss events for single positions. Returns a `PnLSingle` object that is kept live updated. The result can also be queried from `pnlSingle()`. https://interactivebrokers.github.io/tws-api/pnl.html ### Parameters #### Query Parameters - **account** (str) - Required - Subscribe to this account. - **modelCode** (str) - Required - Filter for this account model. - **conId** (int) - Required - Filter for this contract ID. ### Return Type `PnLSingle` ``` -------------------------------- ### Get Account Summary Async Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves account summary data. If no account is specified, it returns summaries for all accounts. Data is loaded on demand. ```python if not self.wrapper.acctSummary: # loaded on demand since it takes ca. 250 ms await self.reqAccountSummaryAsync() if account: return [v for v in self.wrapper.acctSummary.values() if v.account == account] else: return list(self.wrapper.acctSummary.values()) ``` -------------------------------- ### Set Connection Options Source: https://ib-insync.readthedocs.io/_modules/ib_insync/client.html Sets additional connection options for the client. For example, use '+PACEAPI' to enable request-pacing in TWS/gateway 974+. ```python self.connectOptions = connectOptions.encode() ``` -------------------------------- ### reqPnL Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Starts a subscription for profit and loss events. Returns a :class:`.PnL` object that is kept live updated. The result can also be queried from `.pnl`. ```APIDOC ## reqPnL ### Description Starts a subscription for profit and loss events. Returns a :class:`.PnL` object that is kept live updated. The result can also be queried from :meth:`.pnl`. https://interactivebrokers.github.io/tws-api/pnl.html ### Method `reqPnL(account: str, modelCode: str = '')` ### Parameters #### Path Parameters - **account** (str) - Required - Subscribe to this account. - **modelCode** (str) - Optional - If specified, filter for this account model. ``` -------------------------------- ### startTicker Source: https://ib-insync.readthedocs.io/_modules/ib_insync/wrapper.html Starts a tick request for a given contract and tick type, returning a Ticker object to receive tick data. ```APIDOC ## startTicker ### Description Start a tick request that has the reqId associated with the contract. Return the ticker. ### Method wrapper.startTicker(reqId: int, contract: Contract, tickType: Union[int, str]) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - Ticker: The Ticker object associated with the request. ``` -------------------------------- ### Start a New Request Source: https://ib-insync.readthedocs.io/_modules/ib_insync/wrapper.html Initiates a new request and returns an asyncio.Future object associated with the request key and container. Used for tracking asynchronous operations. ```python def startReq(self, key, contract=None, container=None): """ Start a new request and return the future that is associated with the key and container. The container is a list by default. """ future: asyncio.Future = asyncio.Future() self._futures[key] = future self._results[key] = container if container is not None else [] if contract: self._reqId2Contract[key] = contract return future ``` -------------------------------- ### Download Historical Data - IB-insync Source: https://ib-insync.readthedocs.io/ Connect to IB Gateway/TWS, define a contract, and request historical data. The data can be converted to a pandas DataFrame for analysis. Ensure pandas is installed. ```python from ib_insync import * # util.startLoop() # uncomment this line when in a notebook ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) contract = Forex('EURUSD') bars = ib.reqHistoricalData( contract, endDateTime='', durationStr='30 D', barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True) # convert to pandas dataframe (pandas needs to be installed): df = util.df(bars) print(df) ``` -------------------------------- ### Get Scanner Data (Streaming) Source: https://ib-insync.readthedocs.io/recipes.html Sets up a streaming scanner subscription and processes incoming data through an event handler. The subscription is cancelled after a specified sleep duration. ```python def onScanData(scanData): print(scanData[0]) print(len(scanData)) sub = ScannerSubscription( instrument='FUT.US', locationCode='FUT.GLOBEX', scanCode='TOP_PERC_GAIN') scanData = ib.reqScannerSubscription(sub) scanData.updateEvent += onScanData ib.sleep(60) ib.cancelScannerSubscription(scanData) ``` -------------------------------- ### ib_insync.util.useQt Source: https://ib-insync.readthedocs.io/api.html Set the Qt binding to use. ```APIDOC ## ib_insync.util.useQt ### Description Set the Qt binding to use. ### Parameters #### Path Parameters - **qtLib** (str) - The Qt library to use (e.g., 'PyQt5', 'PyQt6', 'PySide2', 'PySide6'). - **period** (float) - The period for Qt event loop processing. ### Signature `useQt(_qtLib ='PyQt5'_, _period =0.01_)` ``` -------------------------------- ### Start Nested Event Loop - ib_insync.util Source: https://ib-insync.readthedocs.io/_modules/ib_insync/util.html Initializes a nested asyncio event loop, primarily intended for use within Jupyter notebooks. It calls `patchAsyncio()` to enable nested loop execution. ```python def startLoop(): """Use nested asyncio event loop for Jupyter notebooks.""" patchAsyncio() ``` -------------------------------- ### useQt Source: https://ib-insync.readthedocs.io/_modules/ib_insync/util.html Configures and runs a combined Qt and asyncio event loop, supporting various Qt libraries. ```APIDOC ## useQt(qtLib: str = 'PyQt5', period: float = 0.01) ### Description Run combined Qt5/asyncio event loop. ### Parameters * `qtLib` (str): Name of Qt library to use: * PyQt5 * PyQt6 * PySide2 * PySide6 * `period` (float): Period in seconds to poll Qt. ``` -------------------------------- ### Start a Ticker Request Source: https://ib-insync.readthedocs.io/_modules/ib_insync/wrapper.html Initializes a ticker object for a given contract and tick type, associating it with a request ID. Handles creation of new tickers if they don't exist. ```python def startTicker( self, reqId: int, contract: Contract, tickType: Union[int, str]): """ Start a tick request that has the reqId associated with the contract. Return the ticker. """ ticker = self.tickers.get(id(contract)) if not ticker: ticker = Ticker( contract=contract, ticks=[], tickByTicks=[], domBids=[], domAsks=[], domTicks=[]) self.tickers[id(contract)] = ticker self.reqId2Ticker[reqId] = ticker self._reqId2Contract[reqId] = contract self.ticker2ReqId[tickType][ticker] = reqId return ticker ``` -------------------------------- ### FlexReport Initialization Source: https://ib-insync.readthedocs.io/_modules/ib_insync/flexreport.html Initialize a FlexReport object by downloading a report using a token and queryId, or by loading an existing report from a file path. ```python report = FlexReport(token='945692423458902392892687', queryId='272555') ``` -------------------------------- ### TradingSession Source: https://ib-insync.readthedocs.io/api.html Represents a trading session with start and end times. ```APIDOC ## TradingSession ### Description Represents a trading session with start and end times. ### Fields - **start** (type) - **end** (type) ### Methods N/A ``` -------------------------------- ### ib_insync.util.getLoop Source: https://ib-insync.readthedocs.io/api.html Get the asyncio event loop for the current thread. ```APIDOC ## ib_insync.util.getLoop ### Description Get the asyncio event loop for the current thread. ### Signature `getLoop()` ``` -------------------------------- ### Client Initialization Source: https://ib-insync.readthedocs.io/api.html Initialize the asynchronous client with optional parameters for request throttling and client version. ```APIDOC ## Client Class Socket client for communicating with Interactive Brokers. ### Description Replacement for `ibapi.client.EClient` that uses asyncio. The client is fully asynchronous and has its own event-driven networking code that replaces the networking code of the standard EClient. It also replaces the infinite loop of `EClient.run()` with the asyncio event loop. It can be used as a drop-in replacement for the standard EClient as provided by IBAPI. ### Parameters * **MaxRequests** (_int_) – Throttle the number of requests to `MaxRequests` per `RequestsInterval` seconds. Set to 0 to disable throttling. * **RequestsInterval** (_float_) – Time interval (in seconds) for request throttling. * **MinClientVersion** (_int_) – Client protocol version. * **MaxClientVersion** (_int_) – Client protocol version. ``` -------------------------------- ### Context Manager for IBC Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html Use the IBC controller as a context manager to automatically start and terminate the TWS/Gateway client. Ensure the correct event loop is set for Windows. ```python import asyncio asyncio.set_event_loop(asyncio.ProactorEventLoop()) with IBC(976, gateway=True, tradingMode='live', userid='edemo', password='demouser') as ibc: IB.run() ``` -------------------------------- ### startSubscription Source: https://ib-insync.readthedocs.io/_modules/ib_insync/wrapper.html Registers a live subscription with a request ID and an optional contract. ```APIDOC ## startSubscription ### Description Register a live subscription. ### Method wrapper.startSubscription(reqId, subscriber, contract=None) ``` -------------------------------- ### getReqId Source: https://ib-insync.readthedocs.io/_modules/ib_insync/client.html Get a new unique request ID for API requests. ```APIDOC ## getReqId ### Description Get a new unique request ID for API requests. ### Signature getReqId() -> int ``` -------------------------------- ### Connect to IB API Async Source: https://ib-insync.readthedocs.io/api.html Asynchronously establishes a connection to the IB API. Allows configuration of host, port, client ID, and other connection parameters. ```python _async _connectAsync(_host ='127.0.0.1'_, _port =7497_, _clientId =1_, _timeout =4_, _readonly =False_, _account =''_, _raiseSyncErrors =False_) ``` -------------------------------- ### HistoricalSession Source: https://ib-insync.readthedocs.io/api.html Represents a historical trading session with start and end times, and a reference date. ```APIDOC ## HistoricalSession ### Description Represents a historical trading session. ### Attributes - **startDateTime** (datetime) - The start time of the session. - **endDateTime** (datetime) - The end time of the session. - **refDate** (date) - The reference date for the session. ### Methods - **dict()**: Returns a dictionary representation of the session. - **nonDefaults()**: Returns attributes that are not set to their default values. - **tuple()**: Returns a tuple representation of the session. - **update()**: Updates the session with new data. ``` -------------------------------- ### _endReq Source: https://ib-insync.readthedocs.io/_modules/ib_insync/wrapper.html Completes a previously started request by setting the result or exception on its associated future. ```APIDOC ## _endReq ### Description Finish the future of corresponding key with the given result. If no result is given then it will be popped of the general results. ### Method wrapper._endReq(key, result=None, success=True) ``` -------------------------------- ### reqContractDetails Source: https://ib-insync.readthedocs.io/api.html Gets a list of contract details that match the given contract. This method is blocking. ```APIDOC ## reqContractDetails(_contract_) ### Description Get a list of contract details that match the given contract. If the returned list is empty then the contract is not known; If the list has multiple values then the contract is ambiguous. The fully qualified contract is available in the the ContractDetails.contract attribute. This method is blocking. https://interactivebrokers.github.io/tws-api/contract_details.html ### Parameters #### Query Parameters - **contract** (Contract) - Required - The contract to get details for. ### Return Type `List`[`ContractDetails`] ``` -------------------------------- ### FlexReport Load from File Source: https://ib-insync.readthedocs.io/api.html Load a FlexReport from a local XML file path. ```python report.load('path/to/report.xml') ``` -------------------------------- ### Get User Info Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves the White Branding ID of the user. This is a blocking method. ```python ib.reqUserInfo() ``` -------------------------------- ### Request Account Summary Async Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Initiates a request for account summary details. This method fetches a comprehensive list of account tags. ```python tags = ( 'AccountType,NetLiquidation,TotalCashValue,SettledCash,AccruedCash,BuyingPower,EquityWithLoanValue,PreviousDayEquityWithLoanValue,GrossPositionValue,RegTEquity,RegTMargin,SMA,InitMarginReq,MaintMarginReq,AvailableFunds,ExcessLiquidity,Cushion,FullInitMarginReq,FullMaintMarginReq,FullAvailableFunds,FullExcessLiquidity,LookAheadNextChange,LookAheadInitMarginReq,LookAheadMaintMarginReq,LookAheadAvailableFunds,LookAheadExcessLiquidity,HighestSeverity,DayTradesRemaining,DayTradesRemainingT+1,DayTradesRemainingT+2,DayTradesRemainingT+3,DayTradesRemainingT+4,Leverage,$LEDGER:ALL') self.client.reqAccountSummary(reqId, 'All', tags) return future ``` -------------------------------- ### reqMktDepthExchanges Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Get those exchanges that have have multiple market makers (and have ticks returned with marketMaker info). ```APIDOC ## reqMktDepthExchanges ### Description Get those exchanges that have have multiple market makers (and have ticks returned with marketMaker info). ### Parameters None ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ``` -------------------------------- ### Get All Tickers Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves a list of all available tickers. This includes tickers for all contracts that have been requested. ```python def tickers(self) -> List[Ticker]: """Get a list of all tickers.""" return list(self.wrapper.tickers.values()) ``` -------------------------------- ### TimeBars Initialization Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ticker.html Initializes TimeBars with a timer event and an optional source. It connects to the timer and initializes an empty BarList. ```python def __init__(self, timer, source=None): Op.__init__(self, source) self._timer = timer self._timer.connect(self._on_timer, None, self._on_timer_done) self.bars = BarList() ``` -------------------------------- ### Get All Executions Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves a list of all executions from the current session. Each execution is derived from a fill. ```python def executions(self) -> List[Execution]: """List of all executions from this session.""" return list(fill.execution for fill in self.wrapper.fills.values()) ``` -------------------------------- ### Create Specialized Contracts with Contract Source: https://ib-insync.readthedocs.io/_modules/ib_insync/contract.html Demonstrates creating various specialized contract types (Stock, Forex, Future, Option, Bond, Crypto) using the generic Contract class with keyword arguments. This is useful for initializing contracts when the specific type is known. ```python Contract(conId=270639) Stock('AMD', 'SMART', 'USD') Stock('INTC', 'SMART', 'USD', primaryExchange='NASDAQ') Forex('EURUSD') CFD('IBUS30') Future('ES', '20180921', 'GLOBEX') Option('SPY', '20170721', 240, 'C', 'SMART') Bond(secIdType='ISIN', secId='US03076KAA60') Crypto('BTC', 'PAXOS', 'USD') ``` -------------------------------- ### IBC Dataclass Non-Default Fields Source: https://ib-insync.readthedocs.io/api.html Get IBC fields that differ from their default values as a dictionary. ```python ibc.nonDefaults() ``` -------------------------------- ### startReq Source: https://ib-insync.readthedocs.io/_modules/ib_insync/wrapper.html Initiates a new request to the broker and returns an asyncio.Future object that will be resolved when the request is completed. ```APIDOC ## startReq ### Description Start a new request and return the future that is associated with the key and container. The container is a list by default. ### Method wrapper.startReq(key, contract=None, container=None) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - asyncio.Future: A future object associated with the request key. ``` -------------------------------- ### Get All Orders Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves a list of all orders from the current session. This includes both open and closed orders. ```python def orders(self) -> List[Order]: """List of all orders from this session.""" return list( trade.order for trade in self.wrapper.trades.values()) ``` -------------------------------- ### Account Download End Source: https://ib-insync.readthedocs.io/_modules/ib_insync/wrapper.html Placeholder method called when account data download is complete. It currently does nothing. ```python def accountDownloadEnd(self, _account: str): pass ``` -------------------------------- ### dataclassNonDefaults(obj) Source: https://ib-insync.readthedocs.io/_modules/ib_insync/util.html For a dataclass instance, get the fields that are different from the default values and return them as a dictionary. ```APIDOC ## dataclassNonDefaults(obj) ### Description For a ``dataclass`` instance get the fields that are different from the default values and return as ``dict``. ### Parameters #### Arguments * **obj**: The dataclass instance to inspect. ``` -------------------------------- ### ConnectionStats Source: https://ib-insync.readthedocs.io/api.html Provides statistics about an active connection, including start time, duration, and data transfer counts. ```APIDOC ## ConnectionStats ### Description Provides statistics about an active connection, including start time, duration, and data transfer counts. ### Attributes - **startTime** (float) - The start time of the connection in seconds since epoch. - **duration** (float) - The duration of the connection in seconds. - **numBytesRecv** (int) - The total number of bytes received. - **numBytesSent** (int) - The total number of bytes sent. - **numMsgRecv** (int) - The total number of messages received. - **numMsgSent** (int) - The total number of messages sent. ``` -------------------------------- ### ib_insync.util.logToConsole Source: https://ib-insync.readthedocs.io/api.html Create a log handler that logs to the console. ```APIDOC ## ib_insync.util.logToConsole ### Description Create a log handler that logs to the console. ### Parameters #### Path Parameters - **level** (int) - The logging level. ### Signature `logToConsole(_level =20_)` ``` -------------------------------- ### Initialize IBC Controller Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html Instantiate the IBC controller with required parameters like TWS version and gateway settings. It's recommended to set sensitive credentials in a secured IBC config file. ```python ibc = IBC(976, gateway=True, tradingMode='live', userid='edemo', password='demouser') ``` -------------------------------- ### IBC Class Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html The IBC class provides methods to start and terminate TWS/IBG. It can be used as a context manager. ```APIDOC ## Class IBC Programmatic control over starting and stopping TWS/Gateway using IBC. ### Parameters * **twsVersion** (int): Required. The major version number for TWS or gateway. * **gateway** (bool): Optional. True for gateway, False for TWS. Defaults to False. * **tradingMode** (str): Optional. 'live' or 'paper'. * **userid** (str): Optional. IB account username. * **password** (str): Optional. IB account password. * **twsPath** (str): Optional. Path to the TWS installation folder. * **twsSettingsPath** (str): Optional. Path to the TWS settings folder. * **ibcPath** (str): Optional. Path to the IBC installation folder. * **ibcIni** (str): Optional. Path to the IBC configuration file. * **javaPath** (str): Optional. Path to Java executable. * **fixuserid** (str): Optional. FIX account user id (gateway only). * **fixpassword** (str): Optional. FIX account password (gateway only). * **on2fatimeout** (str): Optional. What to do if 2-factor authentication times out; Can be 'restart' or 'exit'. ### Methods #### `start()` Launches TWS/IBG. #### `terminate()` Terminates TWS/IBG. #### `startAsync()` Asynchronous method to launch TWS/IBG. #### `__enter__()` Enters the runtime context related to this object. Calls `start()`. #### `__exit__(*_exc)` Exits the runtime context related to this object. Calls `terminate()`. ### Example Usage ```python import asyncio # For Windows, set the event loop if sys.platform == 'win32': asyncio.set_event_loop(asyncio.ProactorEventLoop()) from ib_insync import IBC, IB # Initialize IBC ibc = IBC(976, gateway=True, tradingMode='live', userid='edemo', password='demouser') # Start TWS/Gateway ibc.start() # Connect to IB IB.run() # When done, terminate TWS/Gateway ibc.terminate() ``` ``` -------------------------------- ### Get WSH Meta Data Async Source: https://ib-insync.readthedocs.io/api.html Asynchronously retrieves metadata for WSH (presumably a WebSocket handler). ```python _async _getWshMetaDataAsync() ``` -------------------------------- ### IBC and Watchdog Initialization Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html This snippet shows how to initialize the IBC (Interactive Brokers Controller) and the Watchdog class for managing IB connections. It's used to set up a connection with specific parameters like client ID, gateway usage, and trading mode. This is typically the entry point for applications using the controller. ```python if __name__ == '__main__': ibc = IBC(1012, gateway=True, tradingMode='paper') ib = IB() app = Watchdog(ibc, ib, appStartupTime=15) app.start() IB.run() ``` -------------------------------- ### Request Contract Details Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Gets a list of contract details that match the given contract. This method is blocking. ```APIDOC ## reqContractDetails ### Description Get a list of contract details that match the given contract. If the returned list is empty then the contract is not known; If the list has multiple values then the contract is ambiguous. The fully qualified contract is available in the the ContractDetails.contract attribute. This method is blocking. ### Method (Implicitly GET or similar, as it retrieves data) ### Endpoint (Not applicable for SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python contract_details = ib.reqContractDetails(contract=my_contract) ``` ### Response #### Success Response (200) - **List[ContractDetails]** (list) - A list of contract details. #### Response Example (ContractDetails object structure not detailed in source) ``` -------------------------------- ### Get All Fills Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves a list of all fills from the current session. A fill represents a completed part of an order. ```python def fills(self) -> List[Fill]: """List of all fills from this session.""" return list(self.wrapper.fills.values()) ``` -------------------------------- ### Connect to IB Gateway/TWS (Async) Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Asynchronously connects to the Interactive Brokers TWS or Gateway. Allows specifying host, port, clientId, timeout, readonly mode, and account. ```python await ib.connectAsync(host='127.0.0.1', port=7497, clientId=1, timeout=4, readonly=False, account='', raiseSyncErrors=False) ``` -------------------------------- ### Get Open Orders Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves a list of all currently open orders. Orders that are in a 'Done' state are excluded. ```python def openOrders(self) -> List[Order]: """List of all open orders.""" return [trade.order for trade in self.wrapper.trades.values() if trade.orderStatus.status not in OrderStatus.DoneStates] ``` -------------------------------- ### Use Qt with Asyncio - ib_insync.util Source: https://ib-insync.readthedocs.io/_modules/ib_insync/util.html Combines a Qt event loop with the asyncio event loop, allowing both to run concurrently. It supports various Qt bindings (PyQt5, PyQt6, PySide2, PySide6) and allows configuration of the polling period. ```python def useQt(qtLib: str = 'PyQt5', period: float = 0.01): """ Run combined Qt5/asyncio event loop. Args: qtLib: Name of Qt library to use: * PyQt5 * PyQt6 * PySide2 * PySide6 period: Period in seconds to poll Qt. """ def qt_step(): loop.call_later(period, qt_step) if not stack: qloop = qc.QEventLoop() timer = qc.QTimer() timer.timeout.connect(qloop.quit) stack.append((qloop, timer)) qloop, timer = stack.pop() timer.start(0) qloop.exec() if qtLib == 'PyQt6' else qloop.exec_() timer.stop() stack.append((qloop, timer)) qApp.processEvents() # type: ignore if qtLib not in ('PyQt5', 'PyQt6', 'PySide2', 'PySide6'): raise RuntimeError(f'Unknown Qt library: {qtLib}') from importlib import import_module qc = import_module(qtLib + '.QtCore') qw = import_module(qtLib + '.QtWidgets') ``` -------------------------------- ### TickBars Initialization Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ticker.html Initializes TickBars with a tick count and an optional source. It sets up the bar count and an empty BarList. ```python def __init__(self, count, source=None): Op.__init__(self, source) self._count = count self.bars = BarList() ``` -------------------------------- ### TimeBars _on_timer method Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ticker.html Handles timer events to finalize the current bar, emit it, and start a new one. ```python def _on_timer(self, time): if self.bars: bar = self.bars[-1] if isNan(bar.close) and len(self.bars) > 1: bar.open = bar.high = bar.low = bar.close = \ self.bars[-2].close self.bars.updateEvent.emit(self.bars, True) self.emit(bar) self.bars.append(Bar(time)) ``` -------------------------------- ### Get Wall Street Horizon Metadata Source: https://ib-insync.readthedocs.io/api.html Retrieves metadata for Wall Street Horizon. Must be called before getWshEventData(). ```python meta = ib.getWshMetaData() print(meta) ``` -------------------------------- ### Get News Bulletins Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves a list of IB news bulletins. These are official announcements and news from Interactive Brokers. ```python def newsBulletins(self) -> List[NewsBulletin]: """List of IB news bulletins.""" return list(self.wrapper.msgId2NewsBulletin.values()) ``` -------------------------------- ### run Source: https://ib-insync.readthedocs.io/_modules/ib_insync/util.html Runs the asyncio event loop. ```APIDOC ## run(*awaitables: Awaitable, timeout: Optional[float] = None) ### Description By default run the event loop forever. When awaitables (like Tasks, Futures or coroutines) are given then run the event loop until each has completed and return their results. An optional timeout (in seconds) can be given that will raise asyncio.TimeoutError if the awaitables are not ready within the timeout period. ### Method N/A (Python function) ### Parameters * **awaitables** (Awaitable) - One or more awaitable objects (Tasks, Futures, coroutines) to run. * **timeout** (Optional[float], optional) - A timeout in seconds. Defaults to None. ### Returns - If no awaitables are provided, runs the event loop forever (or until interrupted). - If awaitables are provided, returns the results of the completed awaitables. ``` -------------------------------- ### Request Smart Components Async Source: https://ib-insync.readthedocs.io/api.html Asynchronously requests smart components for a given BBO exchange. This is likely related to market data. ```python reqSmartComponentsAsync(_bboExchange_) ``` -------------------------------- ### Request Account Summary Async Source: https://ib-insync.readthedocs.io/api.html Asynchronously requests a summary of account information. This is a one-time request. ```python reqAccountSummaryAsync() ``` -------------------------------- ### Get WSH Event Data Async Source: https://ib-insync.readthedocs.io/api.html Asynchronously retrieves WSH event data. Requires a data object for filtering. ```python _async _getWshEventDataAsync(_data_) ``` -------------------------------- ### Request Smart Components - ib_insync Client Source: https://ib-insync.readthedocs.io/_modules/ib_insync/client.html Requests smart component information for a given BBO (Best Bid Offer) exchange. Requires a request ID and the exchange identifier. ```python self.send(83, reqId, bboExchange) ``` -------------------------------- ### Get User Info Async Source: https://ib-insync.readthedocs.io/api.html Asynchronously retrieves the White Branding ID of the user. This method is useful for identifying user-specific configurations. ```python reqUserInfoAsync() ``` -------------------------------- ### Request News Providers - ib_insync Client Source: https://ib-insync.readthedocs.io/_modules/ib_insync/client.html Requests a list of available news providers. This is a simple request with no parameters. ```python self.send(85) ``` -------------------------------- ### Get News Ticks Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves a list of ticks containing headline news. The full article content can be fetched using `reqNewsArticle`. ```python def newsTicks(self) -> List[NewsTick]: """ List of ticks with headline news. The article itself can be retrieved with :meth:`.reqNewsArticle`. """ return self.wrapper.newsTicks ``` -------------------------------- ### ib_insync.util.timeit Source: https://ib-insync.readthedocs.io/api.html Context manager for timing. ```APIDOC ## ib_insync.util.timeit ### Description Context manager for timing. ### Parameters #### Path Parameters - **title** (str) - The title for the timing output. ### Signature `timeit(_title ='Run'_)` ``` -------------------------------- ### ib_insync.util.logToFile Source: https://ib-insync.readthedocs.io/api.html Create a log handler that logs to the given file. ```APIDOC ## ib_insync.util.logToFile ### Description Create a log handler that logs to the given file. ### Parameters #### Path Parameters - **path** (str) - The path to the log file. - **level** (int) - The logging level. ### Signature `logToFile(_path_ , _level =20_)` ``` -------------------------------- ### Get Pending Tickers Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves a list of tickers that have pending ticks or depth of market (DOM) ticks. These are tickers that are actively updating. ```python def pendingTickers(self) -> List[Ticker]: """Get a list of all tickers that have pending ticks or domTicks.""" return list(self.wrapper.pendingTickers) ``` -------------------------------- ### exerciseOptions Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Exercises an options contract. This method is blocking. ```APIDOC ## exerciseOptions ### Description Exercise an options contract. ### Method Signature ```python exerciseOptions(contract: Contract, exerciseAction: int, exerciseQuantity: int, account: str, override: int) ``` ### Parameters * **contract** (Contract) - The option contract to be exercised. * **exerciseAction** (int) - * 1 = exercise the option * 2 = let the option lapse * **exerciseQuantity** (int) - Number of contracts to be exercised. * **account** (str) - Destination account. * **override** (int) - * 0 = no override * 1 = override the system's natural action ### External Documentation https://interactivebrokers.github.io/tws-api/options.html ``` -------------------------------- ### Get Realtime Bars Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Retrieves a list of all live updated bars. This includes both 5-second real-time bars and live updated historical bars. ```python def realtimeBars(self) -> List[Union[BarDataList, RealTimeBarList]]: """ Get a list of all live updated bars. These can be 5 second realtime bars or live updated historical bars. """ return list(self.wrapper.reqId2Subscriber.values()) ``` -------------------------------- ### Request All Open Orders Async Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Fetches all open orders, potentially including those not directly managed by the current client session. Use with caution. ```python future = self.wrapper.startReq('openOrders') self.client.reqAllOpenOrders() return future ``` -------------------------------- ### Get Managed Account Names Source: https://ib-insync.readthedocs.io/_modules/ib_insync/client.html Retrieves the list of account names that are currently under management. Requires an active connection to the IB gateway or TWS. ```python return self._accounts ``` -------------------------------- ### Asynchronous Connection and Event Handling Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ibcontroller.html This snippet demonstrates the core logic for maintaining an asynchronous connection to the IB gateway. It includes event handlers for timeouts, errors, and disconnections, along with a mechanism for probing the connection to detect hard timeouts. Use this for applications requiring continuous, resilient connectivity. ```python def onTimeout(idlePeriod): if not waiter.done(): waiter.set_result(None) def onError(reqId, errorCode, errorString, contract): if errorCode in {100, 1100} and not waiter.done(): waiter.set_exception(Warning(f'Error {errorCode}')) def onDisconnected(): if not waiter.done(): waiter.set_exception(Warning('Disconnected')) while self._runner: try: await self.controller.startAsync() await asyncio.sleep(self.appStartupTime) await self.ib.connectAsync( self.host, self.port, self.clientId, self.connectTimeout, self.readonly, self.account, self.raiseSyncErrors) self.startedEvent.emit(self) self.ib.setTimeout(self.appTimeout) self.ib.timeoutEvent += onTimeout self.ib.errorEvent += onError self.ib.disconnectedEvent += onDisconnected while self._runner: waiter: asyncio.Future = asyncio.Future() await waiter # soft timeout, probe the app with a historical request self._logger.debug('Soft timeout') self.softTimeoutEvent.emit(self) probe = self.ib.reqHistoricalDataAsync( self.probeContract, '', '30 S', '5 secs', 'MIDPOINT', False) bars = None with suppress(asyncio.TimeoutError): bars = await asyncio.wait_for(probe, self.probeTimeout) if not bars: self.hardTimeoutEvent.emit(self) raise Warning('Hard timeout') self.ib.setTimeout(self.appTimeout) except ConnectionRefusedError: pass except Warning as w: self._logger.warning(w) except Exception as e: self._logger.exception(e) finally: self.ib.timeoutEvent -= onTimeout self.ib.errorEvent -= onError self.ib.disconnectedEvent -= onDisconnected await self.controller.terminateAsync() self.stoppedEvent.emit(self) if self._runner: await asyncio.sleep(self.retryDelay) ``` -------------------------------- ### Get New Request ID Source: https://ib-insync.readthedocs.io/_modules/ib_insync/client.html Generates and returns a new unique request ID for API calls. Raises a ConnectionError if the client is not connected. ```python return self._reqIdSeq ``` -------------------------------- ### reqUserInfoAsync Source: https://ib-insync.readthedocs.io/_modules/ib_insync/ib.html Requests user information. Returns an awaitable that resolves to the user information. ```APIDOC ## reqUserInfoAsync ### Description Requests user information. Returns an awaitable that resolves to the user information. ### Method `def reqUserInfoAsync(self) ` ### Returns - An awaitable that resolves to the user information. ``` -------------------------------- ### Get Scanner Parameters and Data (Blocking) Source: https://ib-insync.readthedocs.io/recipes.html Retrieves all available scanner parameters and then fetches scanner data for a specific subscription. This method is blocking. ```python allParams = ib.reqScannerParameters() print(allParams) sub = ScannerSubscription( instrument='FUT.US', locationCode='FUT.GLOBEX', scanCode='TOP_PERC_GAIN') scanData = ib.reqScannerData(sub) print(scanData) ``` -------------------------------- ### FlexReport Download Source: https://ib-insync.readthedocs.io/api.html Download a FlexReport using a valid token and query ID. ```python report.download(token='your_token', queryId='your_query_id') ``` -------------------------------- ### FlexReport Topics Extraction Source: https://ib-insync.readthedocs.io/_modules/ib_insync/flexreport.html Get the set of topics that can be extracted from a loaded FlexReport. This helps in identifying available data categories within the report. ```python print(report.topics()) ``` -------------------------------- ### reqUserInfoAsync Source: https://ib-insync.readthedocs.io/api.html Asynchronously requests the user information, including the White Branding ID. ```APIDOC ## reqUserInfoAsync ### Description Asynchronously requests the user information. ### Response #### Success Response (200) - **user_info** (Awaitable[str]) - An awaitable that resolves to the user information string. ``` -------------------------------- ### connectAsync Source: https://ib-insync.readthedocs.io/api.html Asynchronously connects to the IB API. Allows configuration of host, port, client ID, timeout, read-only status, account, and sync error handling. ```APIDOC ## connectAsync ### Description Asynchronously connects to the IB API. ### Parameters #### Path Parameters - **_host** (str) - Optional - The host address to connect to. Defaults to '127.0.0.1'. - **_port** (int) - Optional - The port number to connect to. Defaults to 7497. - **_clientId** (int) - Optional - The client ID for the connection. Defaults to 1. - **_timeout** (int) - Optional - The connection timeout in seconds. Defaults to 4. - **_readonly** (bool) - Optional - Whether to establish a read-only connection. Defaults to False. - **_account** (str) - Optional - The account to connect with. - **_raiseSyncErrors** (bool) - Optional - Whether to raise synchronous errors. Defaults to False. ``` -------------------------------- ### timeit Source: https://ib-insync.readthedocs.io/_modules/ib_insync/util.html A context manager for timing code execution. ```APIDOC ## timeit(title='Run') ### Description Context manager for timing. ### Method N/A (Python class) ### Parameters * **title** (str, optional) - A title for the timing output. Defaults to 'Run'. ### Usage ```python with timeit('My Operation'): # Code to time ``` ### Returns None (prints timing to console upon exiting the context) ```