### Initialize and Start Watchdog Source: https://ib-api-reloaded.github.io/ib_async/api.html Example of initializing IBC and IB instances, setting up a connection event handler, and starting the Watchdog to manage the connection. Ensure the IB instance is not connected before passing it to Watchdog. ```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() ``` -------------------------------- ### Install Everything with Poetry Source: https://ib-api-reloaded.github.io/ib_async/index.html Install all dependencies for ib_async, including those for documentation and development testing, using Poetry. ```bash poetry install --with=docs,dev ``` -------------------------------- ### Watchdog Example Usage Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ibcontroller.html Demonstrates how to initialize and start the Watchdog to manage the TWS or gateway application. This includes setting up event handlers 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() ``` -------------------------------- ### Install All Dependencies for Development Source: https://ib-api-reloaded.github.io/ib_async/readme.html Installs all dependencies required for local development, including development, documentation, and testing tools. ```bash poetry install --with=dev,docs ``` -------------------------------- ### Install ib_async with Poetry Source: https://ib-api-reloaded.github.io/ib_async/index.html Install the ib_async library using Poetry. This command installs only the library dependencies. ```bash poetry install ``` -------------------------------- ### Install ib_async Source: https://ib-api-reloaded.github.io/ib_async/index.html Install the ib_async library using pip. Requires Python 3.10 or higher. ```bash pip install ib_async ``` -------------------------------- ### Basic ib_async Setup and Report Usage Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/flexreport.html Demonstrates basic setup for logging and using the FlexReport class to download and print available topics from a report. ```python if __name__ == "__main__": util.logToConsole() report = FlexReport("945692423458902392892687", "272555") print(report.topics()) ``` -------------------------------- ### Basic Connection Example Source: https://ib-api-reloaded.github.io/ib_async/index.html A simple example to establish a connection to TWS or IB Gateway and print a confirmation message. Includes disconnecting after the operation. ```python from ib_async import * # Connect to TWS or IB Gateway ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) print("Connected") # Disconnect when done ib.disconnect() ``` -------------------------------- ### Install Development Dependencies Source: https://ib-api-reloaded.github.io/ib_async/readme.html Installs the necessary dependencies for development, including testing tools. ```bash poetry install --with=dev ``` -------------------------------- ### Bracket Order Setup Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Initiates the setup for a bracket order, specifying the action, quantity, and potentially other parameters for the main order and its accompanying stop-limit orders. ```python def bracketOrder( self, action: str, quantity: float, ``` -------------------------------- ### Submit Bracket Order Example Source: https://ib-api-reloaded.github.io/ib_async/api.html Example of how to submit a bracket order created by the bracketOrder function. ```python for o in bracket: ib.placeOrder(contract, o) ``` -------------------------------- ### Install All Dependencies with Poetry Source: https://ib-api-reloaded.github.io/ib_async/index.html Installs all project dependencies, including those for development and documentation, using Poetry. This command is used after cloning the repository. ```bash poetry install --with=dev,docs ``` -------------------------------- ### Install Development Dependencies Source: https://ib-api-reloaded.github.io/ib_async/index.html Installs project dependencies including development tools using Poetry. This command is used for setting up the development environment. ```bash poetry install --with=dev ``` -------------------------------- ### Example Usage Source: https://ib-api-reloaded.github.io/ib_async/api.html Demonstrates how to initialize and use the Watchdog class within an event-driven application. ```APIDOC ```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() ``` ``` -------------------------------- ### Example Contract Instantiations Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/contract.html Illustrates various ways to create contract objects using keyword arguments or specialized constructors. Examples cover stocks, forex, options, futures, and bonds, demonstrating the flexibility in defining contract details. ```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') ``` -------------------------------- ### Start TWS/Gateway using IBC Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ibcontroller.html The start method launches the TWS or Gateway client. It internally uses an asynchronous method to manage the process. ```python util.run(self.startAsync()) ``` -------------------------------- ### Initialize and Start IBC Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ibcontroller.html Instantiate the IBC class with necessary parameters and start the TWS/Gateway client. Ensure IB.run() is called to process events. ```python ibc = IBC(976, gateway=True, tradingMode='live', userid='edemo', password='demouser') ibc.start() IB.run() ``` -------------------------------- ### Generate Documentation with Poetry Source: https://ib-api-reloaded.github.io/ib_async/index.html Install documentation dependencies and build the HTML documentation for ib_async using Poetry and Sphinx. ```bash poetry install --with=docs poetry run sphinx-build -b html docs html ``` -------------------------------- ### Install Poetry Source: https://ib-api-reloaded.github.io/ib_async/index.html Install or upgrade Poetry, a dependency management tool for Python. This is a prerequisite for building the library manually. ```bash pip install poetry -U ``` -------------------------------- ### Jupyter Notebook Connection Pattern Source: https://ib-api-reloaded.github.io/ib_async/index.html Specific setup for using ib_async within a Jupyter Notebook environment. Requires starting the asyncio event loop using `util.startLoop()`. ```python from ib_async import * util.startLoop() # Required for notebooks ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Your code here - no need to call ib.run() ``` -------------------------------- ### Asynchronous Start for IBC Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ibcontroller.html This asynchronous method prepares and executes the command to start the TWS/Gateway client. It constructs the command-line arguments based on the instance's configuration. ```python if self._proc: return self._logger.info("Starting") # map from field names to cmd arguments; key=(UnixArg, WindowsArg) 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)) ``` -------------------------------- ### Watchdog Start - Watchdog.start() Source: https://ib-api-reloaded.github.io/ib_async/_sources/changelog.rst.txt Starts the watchdog. In version 0.9.42, this method was rewritten to not require util.patchAsyncio and is no longer blocking. ```python Watchdog.start() ``` -------------------------------- ### Application Initialization and Startup Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ibcontroller.html Initializes the IBC, IB, and Watchdog components and starts the application's main loop. Requires IB.run() to be called. ```python if __name__ == "__main__": ibc = IBC(1012, gateway=True, tradingMode="paper") ib = IB() app = Watchdog(ibc, ib, appStartupTime=15) app.start() IB.run() ``` -------------------------------- ### Start API Connection Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/client.html Initiates the API connection. Requires client ID and optional capabilities. ```python def startApi(self): self.send(71, 2, self.clientId, self.optCapab) ``` -------------------------------- ### Basic Script Connection and Disconnection Source: https://ib-api-reloaded.github.io/ib_async/index.html A fundamental example demonstrating how to initialize the IB object, connect to the API, perform operations, and then disconnect cleanly. ```python from ib_async import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Your code here ib.disconnect() ``` -------------------------------- ### Upload Package to PyPI with Poetry Source: https://ib-api-reloaded.github.io/ib_async/index.html Install dependencies, configure your PyPI token, and publish the ib_async package to PyPI using Poetry. ```bash poetry install poetry config pypi-token.pypi your-api-token poetry publish --build ``` -------------------------------- ### Start Watchdog Service Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ibcontroller.html Initiates the Watchdog's monitoring process by scheduling its asynchronous run method. Emits a 'startingEvent' before starting the background task. ```python self._logger.info("Starting") self.startingEvent.emit(self) self._runner = asyncio.ensure_future(self.runAsync()) return self._runner ``` -------------------------------- ### Specialized Contract Examples Source: https://ib-api-reloaded.github.io/ib_async/api.html Examples of creating specialized contract objects for different financial instrument types. ```APIDOC ## Specialized Contract Creation Examples ```python # Stock Stock('AMD', 'SMART', 'USD') Stock('INTC', 'SMART', 'USD', primaryExchange='NASDAQ') # Forex Forex('EURUSD') # CFD CFD('IBUS30') # Future Future('ES', '20180921', 'GLOBEX') # Option Option('SPY', '20170721', 240, 'C', 'SMART') # Bond Bond(secIdType='ISIN', secId='US03076KAA60') # Crypto Crypto('BTC', 'PAXOS', 'USD') ``` ``` -------------------------------- ### IB Async API - Startup Fetch Options Source: https://ib-api-reloaded.github.io/ib_async/api.html Defines the available options for the StartupFetch functionality in the IB Async API. ```APIDOC ## StartupFetch Options ### Description Enumerates the types of data that can be fetched during the startup process. ### Options - **POSITIONS**: Fetch account positions. - **ORDERS_OPEN**: Fetch open orders. - **ORDERS_COMPLETE**: Fetch completed orders. - **ACCOUNT_UPDATES**: Fetch account updates. - **SUB_ACCOUNT_UPDATES**: Fetch sub-account updates. - **EXECUTIONS**: Fetch executed trades. ``` -------------------------------- ### Add util.useQtAlt for Nested Event Loops on Windows Source: https://ib-api-reloaded.github.io/ib_async/_sources/changelog.rst.txt Introduces `util.useQtAlt()` for using nested event loops on Windows with Qt. ```python util.useQtAlt() ``` -------------------------------- ### Start Asyncio Event Loop for Jupyter Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/util.html Initializes and starts the asyncio event loop, specifically designed for use within Jupyter notebooks. It ensures proper patching for asynchronous operations in this environment. ```python def startLoop(): """Use nested asyncio event loop for Jupyter notebooks.""" patchAsyncio() ``` -------------------------------- ### Build Package with Poetry Source: https://ib-api-reloaded.github.io/ib_async/index.html Build the distribution package for ib_async using Poetry. ```bash poetry build ``` -------------------------------- ### Get All Tickers Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Returns a list of all available tickers. ```python def tickers(self) -> list[Ticker]: """Get a list of all tickers.""" return list(self.wrapper.tickers.values()) ``` -------------------------------- ### Get All Fills Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Returns a list of all fills from the current session. ```python def fills(self) -> list[Fill]: """List of all fills from this session.""" return list(self.wrapper.fills.values()) ``` -------------------------------- ### Logging Utilities Source: https://ib-api-reloaded.github.io/ib_async/api.html Utilities for setting up logging. ```APIDOC ## ib_async.util.logToFile ### Description Create a log handler that logs to the given file. ### Method N/A ### Endpoint N/A ### Parameters #### Query Parameters - **path** (str) - Required - The path to the log file. - **level** (int) - Optional - The logging level, defaults to 20 (INFO). ``` ```APIDOC ## ib_async.util.logToConsole ### Description Create a log handler that logs to the console. ### Method N/A ### Endpoint N/A ### Parameters #### Query Parameters - **level** (int) - Optional - The logging level, defaults to 20 (INFO). ``` -------------------------------- ### TradingSession NamedTuple Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/contract.html Represents a trading session with start and end datetimes. ```python class TradingSession(NamedTuple): start: dt.datetime end: dt.datetime ``` -------------------------------- ### Get User Info Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Retrieves the White Branding ID of the user. ```python return self._run(self.reqUserInfoAsync()) ``` -------------------------------- ### Initiate What-If Order Asynchronously Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Creates a copy of the provided order and prepares it for a 'what-if' simulation. This is useful for checking order validity and potential outcomes without actually placing the order. ```python def whatIfOrderAsync( self, contract: Contract, order: Order ) -> Awaitable[OrderState]: whatIfOrder = copy.copy(order) ``` -------------------------------- ### Get News Bulletins Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Returns a list of IB news bulletins. ```python def newsBulletins(self) -> list[NewsBulletin]: """List of IB news bulletins.""" return list(self.wrapper.msgId2NewsBulletin.values()) ``` -------------------------------- ### Place Order (What-If) Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Initiates an order with the 'whatIf' flag set to true, allowing simulation without actual placement. ```APIDOC ## POST /api/orders/whatIf ### Description Simulates placing an order without executing it. Useful for checking order validity and potential impact. ### Method POST ### Endpoint /api/orders/whatIf ### Parameters #### Request Body - **contract** (Contract) - Required - The contract details for the order. - **whatIfOrder** (object) - Required - Order details with `whatIf` set to `True`. ### Request Example ```json { "contract": { "symbol": "AAPL", "secType": "STK", "exchange": "SMART", "currency": "USD" }, "whatIfOrder": { "action": "BUY", "totalQuantity": 100, "orderType": "MKT", "whatIf": true } } ``` ### Response #### Success Response (200) - **future** (Awaitable) - An awaitable object that resolves to the result of the simulated order placement. #### Response Example ```json { "future": "" } ``` ``` -------------------------------- ### Initialize FlexReport with Token and Query ID Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/flexreport.html Instantiate FlexReport to download a report using a provided token and query ID. Ensure the token and queryId are valid for the Interactive Brokers account. ```python report = FlexReport("945692423458902392892687", "272555") ``` -------------------------------- ### Get All Trades Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Returns a list of all order trades from the current session. ```python def trades(self) -> list[Trade]: """List of all order trades from this session.""" return list(self.wrapper.trades.values()) ``` -------------------------------- ### HistoricalSession Object Source: https://ib-api-reloaded.github.io/ib_async/api.html Represents a historical trading session with a start and end date/time. ```APIDOC ## HistoricalSession Object ### Description Represents a historical trading session with a start and end date/time. ### Fields - **startDateTime** (str) - The start date and time of the session. Defaults to ''. - **endDateTime** (str) - The end date and time of the session. Defaults to ''. - **refDate** (str) - The reference date for the session. Defaults to ''. ### Methods - **dict()**: Returns the dataclass values as a dictionary. - **nonDefaults()**: Returns fields that differ from default values as a dictionary. - **tuple()**: Returns the dataclass values as a tuple. - **update(\*srcObjs, \*\*kwargs)**: Updates fields of the dataclass object from source objects or keyword arguments. ``` -------------------------------- ### Initialize VolumeBars Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ticker.html Initializes VolumeBars to aggregate ticks into bars based on a specified volume. Requires a source for tick data. ```python class VolumeBars(Op): __slots__ = ("_volume", "bars") __doc__ = Tickfilter.volumebars.__doc__ bars: BarList def __init__(self, volume, source=None): Op.__init__(self, source) self._volume = volume self.bars = BarList() ``` -------------------------------- ### Get FlexReport Topics Source: https://ib-api-reloaded.github.io/ib_async/api.html Retrieves the set of available topics that can be extracted from a FlexReport. ```python topics() ``` -------------------------------- ### Connect to IB API Async Source: https://ib-api-reloaded.github.io/ib_async/api.html Asynchronously establishes a connection to the IB API. Allows configuration of host, port, client ID, timeout, and other connection parameters. ```python _async _connectAsync(_host='127.0.0.1'_ , _port=7497_ , _clientId=1_ , _timeout=4_ , _readonly=False_ , _account=''_ , _raiseSyncErrors=False_ , _fetchFields= _) ``` -------------------------------- ### Get Positions Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Retrieves a list of positions for a specified account, or for all accounts if no account is specified. ```python def positions(self, account: str = "") -> list[Position]: """ List of positions for the given account, or of all accounts if account is left blank. Args: account: If specified, filter for this account name. """ if account: return list(self.wrapper.positions[account].values()) return [v for d in self.wrapper.positions.values() for v in d.values()] ``` -------------------------------- ### Integrate Qt Event Loop with Asyncio Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/util.html Combines Qt's event loop with asyncio for seamless integration. Supports multiple Qt bindings (PyQt5, PyQt6, PySide2, PySide6) and allows configuration of the polling period. Requires importing Qt modules and setting up a QApplication instance. ```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") global qApp qApp = ( qw.QApplication.instance() or qw.QApplication(sys.argv) # type: ignore ) # type: ignore loop = getLoop() stack: list = [] qt_step() ``` -------------------------------- ### ConnectionStats Object Source: https://ib-api-reloaded.github.io/ib_async/api.html Represents connection statistics, including start time, duration, and message/byte counts. ```APIDOC ## ConnectionStats Object ### Description Provides statistics about a network connection. ### 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. ### Methods - **dict()**: Returns dataclass values as a dictionary. - **nonDefaults()**: Returns fields that differ from default values as a dictionary. - **tuple()**: Returns dataclass values as a tuple. - **update(\*srcObjs, \*\*kwargs)**: Updates fields of the object from source objects or keyword arguments. ``` -------------------------------- ### Client Class Initialization Source: https://ib-api-reloaded.github.io/ib_async/api.html Initializes the asynchronous client for Interactive Brokers. It supports request throttling and version compatibility. ```APIDOC ## Client Class ### Description Socket client for communicating with Interactive Brokers, designed as an asynchronous replacement for `ibapi.client.EClient`. ### Parameters - **MaxRequests** (int) - Throttle the number of requests to `MaxRequests` per `RequestsInterval` seconds. Set to 0 to disable throttling. (Default: 45) - **RequestsInterval** (float) - Time interval (in seconds) for request throttling. (Default: 1) - **MinClientVersion** (int) - Minimum client protocol version. (Default: 157) - **MaxClientVersion** (int) - Maximum client protocol version. (Default: 178) ### Events - `apiStart` () - `apiEnd` () - `apiError` (errorMsg: str) - `throttleStart` () - `throttleEnd` () ``` -------------------------------- ### Use Qt Event Loop - util.useQt() Source: https://ib-api-reloaded.github.io/ib_async/_sources/changelog.rst.txt Rewritten utility to work with any asyncio event loop, supporting PyQt5 and PySide2 without quamash. This change was part of version 0.9.31. ```python util.useQt() ``` -------------------------------- ### Request Head Time Stamp Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Gets the datetime of the earliest available historical data for the contract. ```APIDOC ## POST /api/historical/headtimestamp ### Description Gets the datetime of the earliest available historical data for the contract. ### Method POST ### Endpoint /api/historical/headtimestamp ### Parameters #### Request Body - **contract** (Contract) - Required - Contract of interest. - **whatToShow** (str) - Required - Specifies the type of data to show (e.g., 'Bid_Ask', 'Midpoint', 'Trades'). - **useRTH** (bool) - Required - If True then only show data from within Regular Trading Hours, if False then show all data. - **formatDate** (int) - Optional - If set to 2 then the result is returned as a timezone-aware datetime.datetime with UTC timezone. Defaults to 1. ### Request Example ```json { "contract": { "symbol": "MSFT", "secType": "STK", "exchange": "SMART" }, "whatToShow": "Midpoint", "useRTH": true, "formatDate": 2 } ``` ### Response #### Success Response (200) - **headTimestamp** (datetime.datetime) - The datetime of the earliest available historical data. #### Response Example ```json { "headTimestamp": "2023-01-01T09:30:00Z" } ``` ``` -------------------------------- ### Clone ib_async Repository Source: https://ib-api-reloaded.github.io/ib_async/index.html Clones the `ib_async` project repository from GitHub to a local machine. This is the first step in setting up the project for local development. ```bash git clone https://github.com/ib-api-reloaded/ib_async.git cd ib_async ``` -------------------------------- ### Create a Bracket Order Source: https://ib-api-reloaded.github.io/ib_async/index.html Illustrates the setup for a bracket order, which includes a parent order and associated stop-loss and take-profit orders. Note that `transmit=False` is used for parent and child orders, requiring explicit transmission. ```python from ib_async import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Create a bracket order (entry + stop loss + take profit) contract = Stock('TSLA', 'SMART', 'USD') # Parent order parent = LimitOrder('BUY', 100, 250.00) parent.orderId = ib.client.getReqId() parent.transmit = False # Stop loss stopLoss = StopOrder('SELL', 100, 240.00) stopLoss.orderId = ib.client.getReqId() stopLoss.parentId = parent.orderId stopLoss.transmit = False ``` -------------------------------- ### Get All Executions Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Returns a list of all executions from the current session, extracting the execution object from each 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()) ``` -------------------------------- ### Get All Orders Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Returns a list of all orders from the current session, extracting the order object from each trade. ```python def orders(self) -> list[Order]: """List of all orders from this session.""" return list(trade.order for trade in self.wrapper.trades.values()) ``` -------------------------------- ### Initialize ib_async Client Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/client.html Initializes the asynchronous client with a wrapper object. It sets up event handlers and internal state for connection management and request throttling. ```python class Client: """ 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. Compared to the standard EClient this client has the following additional features: * ``client.connect()`` will block until the client is ready to serve requests; It is not necessary to wait for ``nextValidId`` to start requests as the client has already done that. The reqId is directly available with :py:meth:`.getReqId()`. * ``client.connectAsync()`` is a coroutine for connecting asynchronously. * When blocking, ``client.connect()`` can be made to time out with the timeout parameter (default 2 seconds). * Optional ``wrapper.priceSizeTick(reqId, tickType, price, size)`` that combines price and size instead of the two wrapper methods priceTick and sizeTick. * Automatic request throttling. * Optional ``wrapper.tcpDataArrived()`` method; If the wrapper has this method it is invoked directly after a network packet has arrived. A possible use is to timestamp all data in the packet with the exact same time. * Optional ``wrapper.tcpDataProcessed()`` method; If the wrapper has this method it is invoked after the network packet's data has been handled. A possible use is to write or evaluate the newly arrived data in one batch instead of item by item. 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. Events: * ``apiStart`` () * ``apiEnd`` () * ``apiError`` (errorMsg: str) * ``throttleStart`` () * ``throttleEnd`` () """ events = ("apiStart", "apiEnd", "apiError", "throttleStart", "throttleEnd") MaxRequests = 45 RequestsInterval = 1 MinClientVersion = 157 MaxClientVersion = 178 DISCONNECTED, CONNECTING, CONNECTED = range(3) def __init__(self, wrapper): self.wrapper = wrapper self.decoder = Decoder(wrapper, 0) self.apiStart = Event("apiStart") self.apiEnd = Event("apiEnd") self.apiError = Event("apiError") self.throttleStart = Event("throttleStart") self.throttleEnd = Event("throttleEnd") self._logger = logging.getLogger("ib_async.client") self.conn = Connection() self.conn.hasData += self._onSocketHasData self.conn.disconnected += self._onSocketDisconnected # extra optional wrapper methods self._priceSizeTick = getattr(wrapper, "priceSizeTick", None) self._tcpDataArrived = getattr(wrapper, "tcpDataArrived", None) self._tcpDataProcessed = getattr(wrapper, "tcpDataProcessed", None) self.host = "" self.port = -1 self.clientId = -1 self.optCapab = "" self.connectOptions = b"" self.reset() ``` -------------------------------- ### Connect and Disconnect IB API Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Basic example demonstrating how to connect to the IB API, set debug mode, log to console, and then disconnect. Ensure the IB Gateway or TWS is running and accessible. ```python if __name__ == "__main__": loop = util.getLoop() loop.set_debug(True) util.logToConsole(logging.DEBUG) ib = IB() ib.connect("127.0.0.1", 7497, clientId=1) ib.disconnect() ``` -------------------------------- ### Event Class Replacement Source: https://ib-api-reloaded.github.io/ib_async/_sources/changelog.rst.txt The 'Event' class has been replaced with the one from the 'eventkit' library, starting in version 0.9.46. ```python Event ``` -------------------------------- ### Initialize FlexReport from File Path Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/flexreport.html Load an existing Flex report from a specified XML file path. This is useful for processing previously downloaded statements. ```python report = FlexReport(path="path/to/your/report.xml") ``` -------------------------------- ### Get Account Summary Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Asynchronously retrieves a summary of account information, optionally filtered by account ID. ```APIDOC ## GET /api/accountSummary ### Description Provides a comprehensive summary of account financial details. If no account is specified, it returns summaries for all accessible accounts. ### Method GET ### Endpoint /api/accountSummary ### Parameters #### Query Parameters - **account** (str) - Optional - The specific account ID to retrieve the summary for. If omitted, all account summaries are returned. ### Response #### Success Response (200) - **list[AccountValue]** - A list of AccountValue objects containing the summary details for the specified or all accounts. #### Response Example ```json [ { "account": "DU12345", "NetLiquidation": 100000.0, "TotalCashValue": 50000.0 // ... other fields } ] ``` ``` -------------------------------- ### Get User Info Async Source: https://ib-api-reloaded.github.io/ib_async/api.html Retrieves the White Branding ID of the current user. This function is asynchronous. ```python reqUserInfo() ``` -------------------------------- ### Get Pending Tickers Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Returns a list of tickers that have pending ticks or DOM (Depth of Market) ticks. ```python def pendingTickers(self) -> list[Ticker]: """Get a list of all tickers that have pending ticks or domTicks.""" return list(self.wrapper.pendingTickers) ``` -------------------------------- ### Downloading a Flex Report Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/flexreport.html Demonstrates how to download a Flex Report using a token and query ID. ```APIDOC ## POST /AccountManagement/FlexWebService/SendRequest ### Description Initiates the download of a Flex Report from Interactive Brokers using provided credentials. ### Method POST (Implicitly via `urlopen` in the `download` method) ### Endpoint `https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?t={token}&q={queryId}&v=3` ### Parameters #### Query Parameters - **t** (string) - Required - The authentication token for the Flex Web Service. - **q** (string) - Required - The query ID for the specific report requested. - **v** (string) - Required - The API version, typically '3'. ### Request Example ```python from ib_async import FlexReport token = "YOUR_TOKEN" queryId = "YOUR_QUERY_ID" try: report = FlexReport(token=token, queryId=queryId) print("Report downloaded successfully.") except Exception as e: print(f"Error downloading report: {e}") ``` ### Response #### Success Response (200) Upon successful initiation, the service prepares the report. The `download` method then polls for the report's availability. #### Response Example (Status Check) ```xml Success ... ... ``` #### Error Response - **ErrorCode** (string) - The error code. - **ErrorMessage** (string) - A description of the error. #### Error Response Example ```xml Error 1234 Invalid token or query ID ``` ``` -------------------------------- ### Initialize Index Contract - Python Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/contract.html Represents an index contract. Requires symbol, exchange, and currency. ```python class Index(Contract): def __init__(self, symbol: str = "", exchange: str = "", currency: str = "", **kwargs): """ Index. Args: symbol: Symbol name. exchange: Destination exchange. currency: Underlying currency. """ Contract.__init__( self, "IND", symbol=symbol, exchange=exchange, currency=currency, **kwargs ) ``` -------------------------------- ### Get Forex Pair Name - Python Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/contract.html Returns the combined symbol and currency as the currency pair name. ```python def pair(self) -> str: """Short name of pair.""" return self.symbol + self.currency ``` -------------------------------- ### Get Account Values Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ib.html Retrieves a list of account values for a specified account, or for all accounts if no account is specified. ```python def accountValues(self, account: str = "") -> list[AccountValue]: """ List of account values for the given account, or of all accounts if account is left blank. Args: account: If specified, filter for this account name. """ if account: return [ v for v in self.wrapper.accountValues.values() if v.account == account ] return list(self.wrapper.accountValues.values()) ``` -------------------------------- ### TimeBars Initialization and Timer Connection Source: https://ib-api-reloaded.github.io/ib_async/_modules/ib_async/ticker.html Initializes TimeBars, connecting to a timer event for bar creation. Manages a BarList and emits updates. ```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() ``` -------------------------------- ### Import Order Conditions Source: https://ib-api-reloaded.github.io/ib_async/_sources/changelog.rst.txt Order conditions are now imported into the `ib_async` namespace. ```python Import order conditions ``` -------------------------------- ### IB Async API - Account and Portfolio Methods Source: https://ib-api-reloaded.github.io/ib_async/api.html Covers methods for retrieving account details, portfolio information, and PnL data. ```APIDOC ## Account and Portfolio Methods ### Description Methods for querying account information, portfolio holdings, and profit/loss details. ### Methods - **IB.managedAccounts()**: Retrieves a list of managed accounts. - **IB.accountValues()**: Fetches account values. - **IB.accountSummary()**: Retrieves an account summary. - **IB.accountSummaryAsync()**: Retrieves an account summary asynchronously. - **IB.portfolio()**: Fetches portfolio details. - **IB.positions()**: Retrieves current positions. - **IB.pnl()**: Fetches profit and loss data. - **IB.pnlSingle()**: Fetches single PnL data. - **IB.cancelPnL()**: Cancels PnL requests. - **IB.reqPnLSingle()**: Requests single PnL data. - **IB.cancelPnLSingle()**: Cancels single PnL requests. - **IB.reqAccountUpdates()**: Requests account updates. - **IB.reqAccountUpdatesAsync()**: Requests account updates asynchronously. - **IB.reqAccountUpdatesMulti()**: Requests multi-account updates. - **IB.reqAccountUpdatesMultiAsync()**: Requests multi-account updates asynchronously. - **IB.reqAccountSummary()**: Requests an account summary. - **IB.reqAccountSummaryAsync()**: Requests an account summary asynchronously. - **IB.reqPositions()**: Requests current positions. - **IB.reqPositionsAsync()**: Requests current positions asynchronously. - **IB.reqPnL()**: Requests profit and loss data. - **IB.reqPnLSingle()**: Requests single PnL data. - **IB.qualifyContracts()**: Qualifies contracts. - **IB.qualifyContractsAsync()**: Qualifies contracts asynchronously. ``` -------------------------------- ### HistoricalSchedule Object Source: https://ib-api-reloaded.github.io/ib_async/api.html Represents a historical schedule, including start and end times, timezone, and a list of historical sessions. ```APIDOC ## HistoricalSchedule Object ### Description Represents a historical schedule, including start and end times, timezone, and a list of historical sessions. ### Fields - **startDateTime** (str) - The overall start date and time for the schedule. Defaults to ''. - **endDateTime** (str) - The overall end date and time for the schedule. Defaults to ''. - **timeZone** (str) - The timezone of the schedule. Defaults to ''. - **sessions** (list[HistoricalSession]) - A list of historical sessions within the schedule. ### Methods - **dict()**: Returns the dataclass values as a dictionary. - **nonDefaults()**: Returns fields that differ from default values as a dictionary. - **tuple()**: Returns the dataclass values as a tuple. - **update(\*srcObjs, \*\*kwargs)**: Updates fields of the dataclass object from source objects or keyword arguments. ``` -------------------------------- ### Fetch Historical Data with ib_async Source: https://ib-api-reloaded.github.io/ib_async/readme.html Fetches historical stock data for different timeframes (daily and 5-minute) and calculates a 20-day Simple Moving Average. Requires connection to IB TWS/Gateway. ```python from ib_async import * import pandas as pd ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Get multiple timeframes contract = Stock('SPY', 'SMART', 'USD') # Daily bars for 1 year daily_bars = ib.reqHistoricalData( contract, endDateTime='', durationStr='1 Y', barSizeSetting='1 day', whatToShow='TRADES', useRTH=True) # 5-minute bars for last 5 days intraday_bars = ib.reqHistoricalData( contract, endDateTime='', durationStr='5 D', barSizeSetting='5 mins', whatToShow='TRADES', useRTH=True) # Convert to DataFrames daily_df = util.df(daily_bars) intraday_df = util.df(intraday_bars) print(f"Daily bars: {len(daily_df)} rows") print(f"Intraday bars: {len(intraday_df)} rows") # Calculate simple moving average daily_df['SMA_20'] = daily_df['close'].rolling(20).mean() print(daily_df[['date', 'close', 'SMA_20']].tail()) ib.disconnect() ```