### IB Client Connection Example - Python Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html A basic example demonstrating how to connect to the Interactive Brokers client, set the event loop to debug, log to the console, and then disconnect. This is typically used for testing or initial setup. ```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() ``` -------------------------------- ### Initialize and Start Watchdog (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/api.html This snippet demonstrates how to initialize and start the Watchdog to monitor an IB connection. It includes setting up an IBC and IB instance, defining a connection callback, and then creating and starting the Watchdog. The IB instance is then run to begin processing events. Dependencies include the IBC and IB classes from ib_insync. ```python from ib_insync import IBC, IB, Watchdog 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() ``` -------------------------------- ### Automate TWS/Gateway with IBC Source: https://context7.com/erdewit/ib_insync/llms.txt Shows how to use IBC to programmatically start and manage IB Gateway or TWS. This example includes starting the gateway, connecting to it, performing a market data request, and terminating the gateway. Requires ib_insync. ```python from ib_insync import * # Configure IBC to start IB Gateway ibc = IBC( twsVersion=1023, gateway=True, tradingMode='paper', # or 'live' userid='your_username', password='your_password', twsPath='/opt/ibc', ibcPath='/opt/ibc' ) # Start IB Gateway ibc.start() # Wait for gateway to be ready import time time.sleep(10) # Connect to gateway ib = IB() ib.connect('127.0.0.1', 4001, clientId=1) # Use as normal contracts = [Stock('AAPL', 'SMART', 'USD')] ib.qualifyContracts(*contracts) ticker = ib.reqMktData(contracts[0]) ib.sleep(5) print(f"Price: {ticker.last}") ib.disconnect() # Stop gateway ibc.terminate() ``` -------------------------------- ### Start API Connection (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/client.html Starts the API connection and initializes the client. It requires the client ID and optional capabilities. ```python def startApi(self): self.send(71, 2, self.clientId, self.optCapab) ``` -------------------------------- ### Install ib_insync Package Source: https://github.com/erdewit/ib_insync/blob/master/README.rst Installs the ib_insync library using pip. Requires Python 3.6+ and a running TWS or IB Gateway application. ```bash pip install ib_insync ``` -------------------------------- ### Watchdog Start Method (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ibcontroller.html Starts the Watchdog process by logging the start, emitting the starting event, and creating an asyncio task for the runAsync method. ```python def start(self): self._logger.info('Starting') self.startingEvent.emit(self) self._runner = asyncio.ensure_future(self.runAsync()) return self._runner ``` -------------------------------- ### IBC Initialization and Start Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/api.html This snippet demonstrates how to initialize and start the IBC (Interactive Brokers Controller) class. It requires specifying TWS version, gateway mode, trading mode, and user credentials. For Windows, a specific event loop must be set. ```python import asyncio asyncio.set_event_loop(asyncio.ProactorEventLoop()) ibc = IBC(976, gateway=True, tradingMode='live', userid='edemo', password='demouser') ibc.start() IB.run() ``` -------------------------------- ### Import ib_insync and Start Event Loop (Python) Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/basics.ipynb This code imports all components from the ib_insync library and starts an event loop, which is crucial for keeping the notebook live and responsive. Note that startLoop() is specific to notebook environments. ```python from ib_insync import * util.startLoop() ``` -------------------------------- ### Start IB Controller with Shell Command Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ibcontroller.html Constructs and executes a shell command to start the IB Controller (IBC) based on the operating system. It dynamically builds the command with arguments derived from the controller's state. Dependencies include 'asyncio' for subprocess execution. ```python 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)) # run shell command self._proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE) ``` -------------------------------- ### Utility Functions Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/api.html Provides asynchronous functions for time range iteration, waiting, patching asyncio, getting and starting event loops, and integrating with Qt. ```APIDOC ## ASYNC UTILITY FUNCTIONS ### `timeRangeAsync(start, end, step)` **Description**: Async version of `timeRange()`. Iterates through a time range. **Method**: `async def` **Endpoint**: N/A (Function Call) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body None ### `waitUntilAsync(t)` **Description**: Async version of `waitUntil()`. Waits until a specified time. **Method**: `async def` **Endpoint**: N/A (Function Call) **Parameters**: - **t** (`Union[time, datetime]`) - Required - The time to wait until. Can be a `datetime.datetime` object or a `datetime.time` object (defaults to today's date). ### `patchAsyncio()` **Description**: Patches asyncio to allow nested event loops, useful for environments like Jupyter notebooks. **Method**: `def` **Endpoint**: N/A (Function Call) **Parameters**: None ### `getLoop()` **Description**: Gets the asyncio event loop for the current thread. **Method**: `def` **Endpoint**: N/A (Function Call) **Parameters**: None ### `startLoop()` **Description**: Starts a nested asyncio event loop, primarily for use in Jupyter notebooks. **Method**: `def` **Endpoint**: N/A (Function Call) **Parameters**: None ### `useQt(qtLib='PyQt5', period=0.01)` **Description**: Runs a combined Qt5/asyncio event loop. Allows seamless integration of Qt GUI applications with asyncio. **Method**: `def` **Endpoint**: N/A (Function Call) **Parameters**: - **qtLib** (`str`) - Optional - The name of the Qt library to use. Options: 'PyQt5', 'PyQt6', 'PySide2', 'PySide6'. Defaults to 'PyQt5'. - **period** (`float`) - Optional - The polling period in seconds for the Qt event loop. Defaults to 0.01. ``` -------------------------------- ### Python: Retrieve Market Data for Multiple Option Contracts using ib_insync Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/option_chain.ipynb This code snippet illustrates fetching real-time market data (tickers) for a list of qualified option contracts in a single request. This is an efficient way to get multiple data points for analysis. ```python tickers = ib.reqTickers(*contracts) tickers[0] ``` -------------------------------- ### Connect to Interactive Brokers Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/option_chain.ipynb Establishes a connection to the Interactive Brokers TWS API. It requires the TWS/Gateway to be running and accessible at the specified IP address and port. A unique clientId is used for each connection. ```python from ib_insync import * util.startLoop() ib = IB() ib.connect('127.0.0.1', 7497, clientId=12) ``` -------------------------------- ### Get Minimum Price Increments (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_sources/recipes.rst.txt This recipe shows how to retrieve minimum price increment rules for a contract. It first fetches contract details to get `marketRuleIds` and then requests the specific market rules associated with those IDs. This is useful for understanding trading constraints. ```python usdjpy = Forex('USDJPY') cd = ib.reqContractDetails(usdjpy)[0] print(cd.marketRuleIds) rules = [ ib.reqMarketRule(ruleId) for ruleId in cd.marketRuleIds.split(',')] print(rules) ``` -------------------------------- ### Place and Update a Limit Order Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/ordering.ipynb This example creates a BUY limit order with an initially unrealistic price and places it. Subsequently, it modifies the limit price and resubmits the order, illustrating how to update and re-execute an order. ```python limitOrder = LimitOrder('BUY', 20000, 0.05) limitTrade = ib.placeOrder(contract, limitOrder) limitOrder.lmtPrice = 0.10 ib.placeOrder(contract, limitOrder) ``` -------------------------------- ### Request Option Chain Parameters Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/option_chain.ipynb Fetches a list of available option chains for a given underlying symbol. This includes details like exchange, trading class, expirations, and available strikes. ```python chains = ib.reqSecDefOptParams(spx.symbol, '', spx.secType, spx.conId) ``` -------------------------------- ### Start a Live Subscription in IB Insync (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/wrapper.html Registers a new live subscription. It associates the request ID with the subscriber object and optionally stores the contract details for the subscription. ```python def startSubscription(self, reqId, subscriber, contract=None): """Register a live subscription.""" self._reqId2Contract[reqId] = contract self.reqId2Subscriber[reqId] = subscriber ``` -------------------------------- ### Create and Qualify an Index Contract Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/option_chain.ipynb Defines an Index contract for the S&P 500 (SPX) and qualifies it with the Interactive Brokers API. Qualification fetches additional contract details, such as the conId. ```python spx = Index('SPX', 'CBOE') ib.qualifyContracts(spx) ``` -------------------------------- ### Watchdog Methods for Connection Control (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/api.html Provides methods to manage the watchdog's lifecycle and connection state. Includes functions to start, stop, and run the watchdog asynchronously. These methods are essential for establishing and maintaining a connection. ```Python start() stop() runAsync() ``` -------------------------------- ### Initialize ib_insync and Logging Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/contract_details.ipynb Initializes the ib_insync library and sets up basic logging. This is typically the first step in any script using the library. It ensures that necessary components are loaded and that logging is configured for debugging. ```python from ib_insync import * util.startLoop() import logging ``` -------------------------------- ### Request Market Depth Exchanges Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/market_depth.ipynb Fetches a list of exchanges that support market depth data. The result is a list of DepthMktDataDescription objects, which can be filtered or displayed. ```python l = ib.reqMktDepthExchanges() print(l[:5]) ``` -------------------------------- ### Subscribe to PnL Events (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html Starts a subscription for profit and loss events for a given account and optional model code. Returns a live-updated PnL object. ```python def reqPnL(self, account: str, modelCode: str = '') -> PnL: """ Start 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 Args: account: Subscribe to this account. modelCode: If specified, filter for this account model. """ key = (account, modelCode) assert key not in self.wrapper.pnlKey2ReqId reqId = self.client.getReqId() self.wrapper.pnlKey2ReqId[key] = reqId pnl = PnL(account, modelCode) self.wrapper.reqId2PnL[reqId] = pnl self.client.reqPnL(reqId, account, modelCode) return pnl ``` -------------------------------- ### Fetch Historical Tick Data (Python) Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/tick_data.ipynb Fetches historical tick data using `ib.reqHistoricalTicks`. This function retrieves a specified number of ticks (up to 1000) for a given contract between a start and end time. It requires either a start or end time to be provided. The 'BID_ASK' tick type is used in this example. ```python import datetime start = '' end = datetime.datetime.now() ticks = ib.reqHistoricalTicks(eurusd, start, end, 1000, 'BID_ASK', useRth=False) ticks[-1] ``` -------------------------------- ### Get Market Price from Ticker Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/option_chain.ipynb Extracts the current market price from a ticker object. The `marketPrice()` method provides a convenient way to access this value. ```python spxValue = ticker.marketPrice() ``` -------------------------------- ### Place and Monitor a Limit Order Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/ordering.ipynb This code shows how to place an order using ib.placeOrder, which returns a Trade object. It then demonstrates how to access the trade log to view the order's status changes, such as 'PendingSubmit' and 'Filled'. ```python trade = ib.placeOrder(contract, order) ib.sleep(1) trade.log ``` -------------------------------- ### Get Head Timestamp Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html Retrieves the datetime of the earliest available historical data for a given contract. This is useful for determining the start of historical data for analysis. ```APIDOC ## GET /api/v1/headtimestamp ### Description Get the datetime of earliest available historical data for the contract. ### Method GET ### Endpoint /api/v1/headtimestamp ### Parameters #### Query Parameters - **contract** (Contract) - Required - Contract of interest. - **whatToShow** (str) - Required - Specifies the type of data to show (e.g., "TRADES", "MIDPOINT", "BID_ASK"). - **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. ### Response #### Success Response (200) - **timestamp** (datetime.datetime) - The datetime of the earliest available historical data. ``` -------------------------------- ### Request Head Timestamp for Bar Data Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/bar_data.ipynb Retrieves the earliest available timestamp for historical bar data for a given contract. This is useful for determining the start date for data requests. It requires an active IB connection and a defined contract. ```python contract = Stock('TSLA', 'SMART', 'USD') ib.reqHeadTimeStamp(contract, whatToShow='TRADES', useRTH=True) ``` -------------------------------- ### Get Historical Bars with Real-time Updates using Python Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/bar_data.ipynb Fetches historical bar data with live updates by setting `endDateTime` to an empty string and `keepUpToDate` to True. This method allows for continuous updates of the latest bars. Requires the `ib_insync` library. ```python from ib_insync import * import matplotlib.pyplot as plt from IPython.display import display, clear_output contract = Forex('EURUSD') bars = ib.reqHistoricalData( contract, endDateTime='', durationStr='900 S', barSizeSetting='10 secs', whatToShow='MIDPOINT', useRTH=True, formatDate=1, keepUpToDate=True) def onBarUpdate(bars, hasNewBar): plt.close() plot = util.barplot(bars) clear_output(wait=True) display(plot) bars.updateEvent += onBarUpdate ib.sleep(10) ib.cancelHistoricalData(bars) ``` -------------------------------- ### Watchdog Initialization and Event Setup (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ibcontroller.html Initializes the Watchdog class, setting up various event handlers and validating controller and IB instance. It prepares the internal logger and runner. ```python probeContract: Contract = Forex('EURUSD') probeTimeout: float = 4 def __post_init__(self): self.startingEvent = Event('startingEvent') self.startedEvent = Event('startedEvent') self.stoppingEvent = Event('stoppingEvent') self.stoppedEvent = Event('stoppedEvent') self.softTimeoutEvent = Event('softTimeoutEvent') self.hardTimeoutEvent = Event('hardTimeoutEvent') if not self.controller: raise ValueError('No controller supplied') if not self.ib: raise ValueError('No IB instance supplied') if self.ib.isConnected(): raise ValueError('IB instance must not be connected') self._runner = None self._logger = logging.getLogger('ib_insync.Watchdog') ``` -------------------------------- ### Integrate ib_insync with PyQt5 GUI Source: https://context7.com/erdewit/ib_insync/llms.txt Provides a PyQt5 example for building an interactive trading application. It shows how to connect to IB, request market data for multiple tickers, and update a table with real-time bid/ask prices. Requires PyQt5 and ib_insync libraries. ```python # Qt Integration Example from ib_insync import * import PyQt5.QtWidgets as qt class TradingWindow(qt.QWidget): def __init__(self): super().__init__() self.ib = IB() self.ib.connectedEvent += self.onConnected self.ib.pendingTickersEvent += self.onPendingTickers # UI setup self.connectBtn = qt.QPushButton('Connect') self.connectBtn.clicked.connect(self.onConnect) self.table = qt.QTableWidget() layout = qt.QVBoxLayout(self) layout.addWidget(self.connectBtn) layout.addWidget(self.table) def onConnect(self): if not self.ib.isConnected(): self.ib.connect('127.0.0.1', 7497, clientId=1) self.ib.reqMarketDataType(2) # Subscribe to multiple tickers symbols = ['AAPL', 'MSFT', 'GOOGL', 'TSLA'] for symbol in symbols: contract = Stock(symbol, 'SMART', 'USD') self.ib.qualifyContracts(contract) self.ib.reqMktData(contract) def onConnected(self): print("Connected to IB") def onPendingTickers(self, tickers): # Update table with ticker data for ticker in tickers: print(f"{ticker.contract.symbol}: {ticker.bid} / {ticker.ask}") if __name__ == '__main__': util.patchAsyncio() util.useQt() app = qt.QApplication([]) window = TradingWindow() window.show() IB.run() ``` -------------------------------- ### Fetch Real-time Bars with Event Handler using Python Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/bar_data.ipynb Subscribes to real-time bars, receiving a new bar every 5 seconds. It includes setting up an event handler to print the latest bar data and demonstrates canceling the subscription after a delay. Requires the `ib_insync` library. ```python from ib_insync import * def onBarUpdate(bars, hasNewBar): print(bars[-1]) contract = Forex('EURUSD') # Assuming contract is defined elsewhere or defined here bars = ib.reqRealTimeBars(contract, 5, 'MIDPOINT', False) bars.updateEvent += onBarUpdate ib.sleep(30) ib.cancelRealTimeBars(bars) ``` -------------------------------- ### Get Historical News Headlines - Python Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html Fetches historical news headlines for a given contract. This blocking method requires the contract ID, provider codes, start and end dates, and the total number of results. It can take `datetime.date`, `datetime.datetime`, or formatted strings for dates and returns `HistoricalNews`. ```Python def reqHistoricalNews( self, conId: int, providerCodes: str, startDateTime: Union[str, datetime.date], endDateTime: Union[str, datetime.date], totalResults: int, historicalNewsOptions: List[TagValue] = []) -> HistoricalNews: """ Get historical news headline. https://interactivebrokers.github.io/tws-api/news.html This method is blocking. Args: conId: Search news articles for contract with this conId. providerCodes: A '+'-separated list of provider codes, like 'BZ+FLY'. startDateTime: The (exclusive) start of the date range. Can be given as a datetime.date or datetime.datetime, or it can be given as a string in 'yyyyMMdd HH:mm:ss' format. If no timezone is given then the TWS login timezone is used. endDateTime: The (inclusive) end of the date range. Can be given as a datetime.date or datetime.datetime, or it can be given as a string in 'yyyyMMdd HH:mm:ss' format. If no timezone is given then the TWS login timezone is used. totalResults: Maximum number of headlines to fetch (300 max). historicalNewsOptions: Unknown. """ return self._run( self.reqHistoricalNewsAsync( conId, providerCodes, startDateTime, endDateTime, totalResults, historicalNewsOptions)) ``` -------------------------------- ### IBC Class for TWS/Gateway Control (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ibcontroller.html The IBC class manages starting and stopping TWS or IB Gateway. It requires specifying TWS version and can be configured with paths, user credentials, and trading mode. Note: This class is not intended for notebook environments and requires a specific event loop setup on Windows. ```python import asyncio import logging import sys from contextlib import suppress from dataclasses import dataclass from typing import ClassVar from eventkit import Event import ib_insync.util as util from ib_insync.contract import Contract, Forex from ib_insync.ib import IB @dataclass class IBC: r""" Programmatic control over starting and stopping TWS/Gateway using IBC (https://github.com/IbcAlpha/IBC). Args: twsVersion (int): (required) The major version number for TWS or gateway. gateway (bool): * True = gateway * False = TWS tradingMode (str): 'live' or 'paper'. userid (str): IB account username. It is recommended to set the real username/password in a secured IBC config file. password (str): IB account password. twsPath (str): Path to the TWS installation folder. Defaults: * Linux: ~/Jts * OS X: ~/Applications * Windows: C:\\Jts twsSettingsPath (str): Path to the TWS settings folder. Defaults: * Linux: ~/Jts * OS X: ~/Jts * Windows: Not available ibcPath (str): Path to the IBC installation folder. Defaults: * Linux: /opt/ibc * OS X: /opt/ibc * Windows: C:\\IBC ibcIni (str): Path to the IBC configuration file. Defaults: * Linux: ~/ibc/config.ini * OS X: ~/ibc/config.ini * Windows: %%HOMEPATH%%\\Documents\IBC\\config.ini javaPath (str): Path to Java executable. Default is to use the Java VM included with TWS/gateway. fixuserid (str): FIX account user id (gateway only). fixpassword (str): FIX account password (gateway only). on2fatimeout (str): What to do if 2-factor authentication times out; Can be 'restart' or 'exit'. This is not intended to be run in a notebook. To use IBC on Windows, the proactor (or quamash) event loop must have been set: .. code-block:: python import asyncio asyncio.set_event_loop(asyncio.ProactorEventLoop()) Example usage: .. code-block:: python ibc = IBC(976, gateway=True, tradingMode='live', userid='edemo', password='demouser') ibc.start() IB.run() """ IbcLogLevel: ClassVar = logging.DEBUG twsVersion: int = 0 gateway: bool = False tradingMode: str = '' twsPath: str = '' twsSettingsPath: str = '' ibcPath: str = '' ibcIni: str = '' javaPath: str = '' userid: str = '' password: str = '' fixuserid: str = '' fixpassword: str = '' on2fatimeout: str = '' def __post_init__(self): self._isWindows = sys.platform == 'win32' if not self.ibcPath: self.ibcPath = '/opt/ibc' if not self._isWindows else 'C:\\IBC' self._proc = None self._monitor = None self._logger = logging.getLogger('ib_insync.IBC') def __enter__(self): self.start() return self def __exit__(self, *_exc): self.terminate() def start(self): """Launch TWS/IBG.""" util.run(self.startAsync()) def terminate(self): """Terminate TWS/IBG.""" util.run(self.terminateAsync()) async def startAsync(self): 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:'), ``` -------------------------------- ### Create Bracket Orders with ib_insync Source: https://context7.com/erdewit/ib_insync/llms.txt Shows how to create bracket orders, which include an entry order along with automatic take-profit and stop-loss orders. The example connects to IB, defines a contract, places a bracket order, monitors open trades, and demonstrates how to modify bracket orders. Requires a running TWS or Gateway and a client connection. ```python from ib_insync import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) contract = Stock('TSLA', 'SMART', 'USD') ib.qualifyContracts(contract) # Create bracket order: entry + take profit + stop loss bracket = ib.bracketOrder( action='BUY', quantity=100, limitPrice=150.00, takeProfitPrice=155.00, stopLossPrice=145.00 ) # bracket returns list of 3 orders: [parent, takeProfit, stopLoss] for order in bracket: trade = ib.placeOrder(contract, order) print(f"Order {order.orderId}: {order.orderType}") # Monitor all bracket trades ib.sleep(2) open_trades = ib.openTrades() for trade in open_trades: print(f"Order {trade.order.orderId}: {trade.orderStatus.status}") # Modify bracket orders parent_trade = ib.trades()[0] parent_trade.order.lmtPrice = 151.00 ib.placeOrder(contract, parent_trade.order) ib.disconnect() ``` -------------------------------- ### Connect to IBKR API and Initialize Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/market_depth.ipynb Establishes a connection to the Interactive Brokers API. It requires the host, port, and a client ID. This is a prerequisite for all subsequent market data requests. ```python from ib_insync import * util.startLoop() ib = IB() ib.connect('127.0.0.1', 7497, clientId=16) ``` -------------------------------- ### Watchdog Main Execution Block (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ibcontroller.html The main execution block demonstrates how to instantiate and use the Watchdog class. It sets up an IBC and IB instance, creates a Watchdog application, starts it, and then runs the IB instance. ```python if __name__ == '__main__': ibc = IBC(1012, gateway=True, tradingMode='paper') ib = IB() app = Watchdog(ibc, ib, appStartupTime=15) app.start() IB.run() ``` -------------------------------- ### Start Nested asyncio Event Loop (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/api.html Initializes and starts a nested asyncio event loop. This is specifically designed for use within environments like Jupyter notebooks to ensure proper asynchronous operation. ```python from ib_insync import * startLoop() print("Nested asyncio event loop started for Jupyter notebooks.") ``` -------------------------------- ### Place Limit, Stop, and Stop-Limit Orders with ib_insync Source: https://context7.com/erdewit/ib_insync/llms.txt Demonstrates how to place limit, stop, and stop-limit orders using ib_insync. It also shows how to subscribe to order status and fill events, wait for order completion, and cancel orders if necessary. Assumes a connected IB instance and a defined contract. ```python from ib_insync import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Define contract (example) contract = Stock('AAPL', 'SMART', 'USD') ib.qualifyContracts(contract) # Place limit order limit_order = LimitOrder('BUY', 100, 150.00) limit_order.tif = 'GTC' # Good Till Cancel limit_order.outsideRth = True # Allow outside regular trading hours trade = ib.placeOrder(contract, limit_order) # Place stop order stop_order = StopOrder('SELL', 100, 145.00) trade = ib.placeOrder(contract, stop_order) # Place stop-limit order stop_limit = StopLimitOrder('SELL', 100, stopPrice=145.00, lmtPrice=144.50) trade = ib.placeOrder(contract, stop_limit) # Subscribe to order events def onOrderStatus(trade): print(f"Order {trade.order.orderId}: {trade.orderStatus.status}") print(f"Filled: {trade.filled()}/{trade.order.totalQuantity}") print(f"Remaining: {trade.remaining()}") def onFill(trade, fill): print(f"Fill: {fill.execution.shares} @ {fill.execution.price}") print(f"Commission: {fill.commissionReport.commission}") trade.statusEvent += onOrderStatus trade.fillEvent += onFill # Wait for order to complete while not trade.isDone(): ib.waitOnUpdate(timeout=1) # Cancel order if still active if trade.isActive(): ib.cancelOrder(trade.order) ib.disconnect() ``` -------------------------------- ### Fetch News Articles (Python) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_sources/recipes.rst.txt This example demonstrates fetching news articles for a specific stock. It first retrieves available news providers, then fetches historical headlines for a contract, and finally requests the full content of a selected article. ```python newsProviders = ib.reqNewsProviders() print(newsProviders) codes = '+'.join(np.code for np in newsProviders) amd = Stock('AMD', 'SMART', 'USD') ib.qualifyContracts(amd) headlines = ib.reqHistoricalNews(amd.conId, codes, '', '', 10) latest = headlines[0] print(latest) article = ib.reqNewsArticle(latest.providerCode, latest.articleId) print(article) ``` -------------------------------- ### Get Wall Street Horizon Metadata (Blocking) (ib_insync) Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html A blocking convenience method to retrieve Wall Street Horizon (WSH) metadata as a JSON string. This method requires a WSH subscription and is useful for getting available filters and event types. It internally calls `getWshMetaDataAsync`. ```python def getWshMetaData(self) -> str: """ Blocking convenience method that returns the WSH metadata (that is the available filters and event types) as a JSON string. Please note that a `Wall Street Horizon subscription `_ is required. .. code-block:: python # Get the list of available filters and event types: meta = ib.getWshMetaData() print(meta) """ return self._run(self.getWshMetaDataAsync()) ``` -------------------------------- ### Connect to Interactive Brokers TWS/IBG (Python) Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/basics.ipynb This snippet shows how to instantiate the IB class and establish a connection to a running TWS or IB Gateway application. It requires specifying the host, port, and a unique client ID. Successful connection returns an IB object. ```python ib = IB() ib.connect('127.0.0.1', 7497, clientId=10) ``` -------------------------------- ### Time Range Iterator in ib_insync Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/util.html The `timeRange` function generates an iterator that yields datetime objects at specified intervals between a start and end time. It waits until each time point is reached before yielding it. The function handles `datetime.time` inputs by using the current date and ensures that the iteration starts from the current time or later. ```python def timeRange(start: Time_t, end: Time_t, step: float) -> Iterator[dt.datetime]: """ Iterator that waits periodically until certain time points are reached while yielding those time points. Args: start: Start time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date end: End time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date step (float): The number of seconds of each period """ assert step > 0 delta = dt.timedelta(seconds=step) t = _fillDate(start) tz = dt.timezone.utc if t.tzinfo else None now = dt.datetime.now(tz) while t < now: t += delta while t <= _fillDate(end): waitUntil(t) yield t t += delta ``` -------------------------------- ### GET /api/reqCurrentTime Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/api.html Requests and returns the current time from the TWS server. This method is blocking. ```APIDOC ## GET /api/reqCurrentTime ### Description Request TWS current time. This method is blocking. ### Method GET ### Endpoint /api/reqCurrentTime ### Parameters None ### Response #### Success Response (200) - **currentTime** (datetime) - The current time from the TWS server. ``` -------------------------------- ### GET /openOrders Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html Retrieves a list of all open orders. ```APIDOC ## GET /openOrders ### Description List of all open orders. ### Method GET ### Endpoint /openOrders ### Response #### Success Response (200) - **Order** (list) - A list of open Order objects. #### Response Example ```json [ { "orderId": 1, "action": "BUY", "totalQuantity": 100, "orderType": "LMT", "lmtPrice": 100.0 } ] ``` ``` -------------------------------- ### Connect to Interactive Brokers TWS API Source: https://github.com/erdewit/ib_insync/blob/master/notebooks/bar_data.ipynb Establishes a connection to the Interactive Brokers TWS API. It requires the TWS API to be running and accessible on the specified host and port. The clientId is used to identify the client connection. ```python from ib_insync import * util.startLoop() ib = IB() ib.connect('127.0.0.1', 7497, clientId=14) ``` -------------------------------- ### Place an Order using ib_insync Client Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/client.html Submits an order for execution. This method constructs a complex list of fields representing the order details, contract information, and version-specific parameters. It handles various order types, contract specifics (like 'BAG'), and advanced order settings. Requires `orderId`, `contract`, and `order` objects. ```python def placeOrder(self, orderId, contract, order): version = self.serverVersion() fields = [ 3, orderId, contract, contract.secIdType, contract.secId, order.action, order.totalQuantity, order.orderType, order.lmtPrice, order.auxPrice, order.tif, order.ocaGroup, order.account, order.openClose, order.origin, order.orderRef, order.transmit, order.parentId, order.blockOrder, order.sweepToFill, order.displaySize, order.triggerMethod, order.outsideRth, order.hidden] if contract.secType == 'BAG': legs = contract.comboLegs or [] fields += [len(legs)] for leg in legs: fields += [ leg.conId, leg.ratio, leg.action, leg.exchange, leg.openClose, leg.shortSaleSlot, leg.designatedLocation, leg.exemptCode] legs = order.orderComboLegs or [] fields += [len(legs)] for leg in legs: fields += [leg.price] params = order.smartComboRoutingParams or [] fields += [len(params)] for param in params: fields += [param.tag, param.value] fields += [ '', order.discretionaryAmt, order.goodAfterTime, order.goodTillDate, order.faGroup, order.faMethod, order.faPercentage] if version < 177: fields += [order.faProfile] fields += [ order.modelCode, order.shortSaleSlot, order.designatedLocation, order.exemptCode, order.ocaType, order.rule80A, order.settlingFirm, order.allOrNone, order.minQty, order.percentOffset, order.eTradeOnly, order.firmQuoteOnly, order.nbboPriceCap, order.auctionStrategy, order.startingPrice, order.stockRefPrice, order.delta, order.stockRangeLower, order.stockRangeUpper, order.overridePercentageConstraints, order.volatility, order.volatilityType, order.deltaNeutralOrderType, order.deltaNeutralAuxPrice] if order.deltaNeutralOrderType: fields += [ order.deltaNeutralConId, order.deltaNeutralSettlingFirm, order.deltaNeutralClearingAccount, order.deltaNeutralClearingIntent, order.deltaNeutralOpenClose, order.deltaNeutralShortSale, order.deltaNeutralShortSaleSlot, order.deltaNeutralDesignatedLocation] fields += [ order.continuousUpdate, order.referencePriceType, order.trailStopPrice, ``` -------------------------------- ### GET /api/wsh/metadata Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/api.html Requests Wall Street Horizon metadata, which includes available filters and event types. ```APIDOC ## GET /api/wsh/metadata ### Description Requests Wall Street Horizon metadata, which includes available filters and event types. ### Method GET ### Endpoint /api/wsh/metadata ### Parameters None ### Response #### Success Response (200) - **WshMetaData** (string) - The Wall Street Horizon metadata as a JSON string. #### Response Example ```json { "eventTypes": ["Earnings", "Ex-Dividend"], "filters": { "ProviderCode": ["BRFG", "DJN"], "Exchange": ["NYSE", "NASDAQ"] } } ``` ``` -------------------------------- ### Place Market and Limit Orders using Python Source: https://context7.com/erdewit/ib_insync/llms.txt Allows submission of market and limit orders for specified contracts. Provides order details including order ID and status updates upon placement. Requires prior connection to IB. ```python from ib_insync import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Define contract contract = Stock('AAPL', 'SMART', 'USD') ib.qualifyContracts(contract) # Place market order market_order = MarketOrder('BUY', 100) trade = ib.placeOrder(contract, market_order) print(f"Order ID: {trade.order.orderId}") print(f"Status: {trade.orderStatus.status}") ``` -------------------------------- ### GET /newsBulletins Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html Retrieves a list of IB news bulletins. ```APIDOC ## GET /newsBulletins ### Description List of IB news bulletins. ### Method GET ### Endpoint /newsBulletins ### Response #### Success Response (200) - **NewsBulletin** (list) - A list of NewsBulletin objects. #### Response Example ```json [ { "sequence": 1, "id": 12345, "time": "2023-10-27T09:00:00Z", "text": "IBKR announces new trading platform features." } ] ``` ``` -------------------------------- ### Configuration Parameters Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/api.html This section details the parameters used to configure the behavior of the IB Insync connection and data handling. ```APIDOC ## Configuration Parameters This section details the parameters used to configure the behavior of the IB Insync connection and data handling. ### Parameters * **RequestTimeout** (_float_) – Timeout (in seconds) to wait for a blocking request to finish before raising `asyncio.TimeoutError`. The default value of 0 will wait indefinitely. Note: This timeout is not used for the `*Async` methods. * **RaiseRequestErrors** (_bool_) – Specifies the behaviour when certain API requests fail: * `False`: Silently return an empty result; * `True`: Raise a `RequestError`. * **MaxSyncedSubAccounts** (_int_) – Do not use sub-account updates if the number of sub-accounts exceeds this number (50 by default). * **TimezoneTWS** (_str_) – Specifies what timezone TWS (or gateway) is using. The default is to assume local system timezone. ``` -------------------------------- ### GET /tickers Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html Retrieves a list of all currently available tickers. ```APIDOC ## GET /tickers ### Description Get a list of all tickers. ### Method GET ### Endpoint /tickers ### Response #### Success Response (200) - **Ticker** (list) - A list of Ticker objects. #### Response Example ```json [ { "contract": {}, "time": 1678886400000, "bid": 100.10, "ask": 100.20, "last": 100.15, "bidSize": 10, "askSize": 5, "lastSize": 8, "volume": 10000 } ] ``` ``` -------------------------------- ### GET /executions Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html Retrieves a list of all executions from the current session. ```APIDOC ## GET /executions ### Description List of all executions from this session. ### Method GET ### Endpoint /executions ### Response #### Success Response (200) - **Execution** (list) - A list of Execution objects. #### Response Example ```json [ { "orderId": 1, "execId": "string", "time": "2023-10-27T10:00:00Z", "accCode": "string", "shares": 100, "price": 100.50, "exchange": "NASDAQ", "side": "BOT" } ] ``` ``` -------------------------------- ### GET /fills Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html Retrieves a list of all fills from the current session. ```APIDOC ## GET /fills ### Description List of all fills from this session. ### Method GET ### Endpoint /fills ### Response #### Success Response (200) - **Fill** (list) - A list of Fill objects. #### Response Example ```json [ { "execution": {}, "orderId": 1 } ] ``` ``` -------------------------------- ### Run Asynchronous Code with ib_insync Source: https://context7.com/erdewit/ib_insync/llms.txt Demonstrates how to run asynchronous functions using util.run(). This is the primary method for executing your main application logic. ```python # Run async code util.run(main()) ``` -------------------------------- ### GET /orders Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/ib.html Retrieves a list of all orders from the current session. ```APIDOC ## GET /orders ### Description List of all orders from this session. ### Method GET ### Endpoint /orders ### Response #### Success Response (200) - **Order** (list) - A list of Order objects. #### Response Example ```json [ { "orderId": 1, "action": "BUY", "totalQuantity": 100, "orderType": "LMT", "lmtPrice": 100.0 } ] ``` ``` -------------------------------- ### Create Contract Instances in Python Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/api.html Demonstrates how to create various types of financial instrument contracts using the ib_insync library. It covers stocks, forex, CFDs, futures, options, and bonds, showcasing the flexibility of the Contract class and its specialized constructor functions. ```python from ib_insync import * # Connect to the IB gateway or TWS # ib = IB() # ib.connect('127.0.0.1', 7497, clientId=1) # Example Contract creations contract_conid = Contract(conId=270639) stock_amd = Stock('AMD', 'SMART', 'USD') stock_intc = Stock('INTC', 'SMART', 'USD', primaryExchange='NASDAQ') forex_eurusd = Forex('EURUSD') cfd_ibus30 = CFD('IBUS30') future_es = Future('ES', '20180921', 'GLOBEX') option_spy = Option('SPY', '20170721', 240, 'C', 'SMART') bond_isin = Bond(secIdType='ISIN', secId='US03076KAA60') crypto_btc = Crypto('BTC', 'PAXOS', 'USD') # You can then use these contracts with IB API functions # For example, to get market data: # bars = ib.reqHistoricalData( # stock_amd, # endDateTime='', # durationStr='1 Y', # barSizeSetting='1 day', # whatToShow='TRADES', # useRTH=True) # print(bars) ``` -------------------------------- ### Python: Handle Open Orders Source: https://github.com/erdewit/ib_insync/blob/master/docs/html/_modules/ib_insync/wrapper.html A wrapper for handling open orders, including initial order loading, updates from other clients or TWS, and manual orders. It distinguishes between regular orders and 'whatIf' order responses. ```python def openOrder( self, orderId: int, contract: Contract, order: Order, orderState: OrderState): """ This wrapper is called to: * feed in open orders at startup; * feed in open orders or order updates from other clients and TWS if clientId=master id; * feed in manual orders and order updates from TWS if clientId=0; * handle openOrders and allOpenOrders responses. """ if order.whatIf: # response to whatIfOrder if orderState.initMarginChange != str(UNSET_DOUBLE): self._endReq(order.orderId, orderState) else: key = self.orderKey(order.clientId, order.orderId, order.permId) trade = self.trades.get(key) ```