### Local Development Setup Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/index.md Steps to clone the repository, install dependencies, and set up for local development. ```bash git clone https://github.com/ib-api-reloaded/ib_async.git cd ib_async poetry install --with=dev,docs ``` -------------------------------- ### Install Everything with Poetry Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Install all dependencies, including those for documentation and development testing. ```bash poetry install --with=docs,dev ``` -------------------------------- ### Install ib_async Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Install the ib_async library using pip. ```bash pip install ib_async ``` -------------------------------- ### IBC Initialization Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/api.md Example of how to initialize and start the IBC controller. ```python ibc = IBC(976, gateway=True, tradingMode='live', userid='edemo', password='demouser') ibc.start() IB.run() ``` -------------------------------- ### Install Library with Poetry Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Install only the library dependencies using poetry. ```bash poetry install ``` -------------------------------- ### Get Account Information Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Retrieves and prints account summary details. ```python from ib_async import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Get account summary account = ib.managedAccounts()[0] summary = ib.accountSummary(account) for item in summary: print(f"{item.tag}: {item.value}") ib.disconnect() ``` -------------------------------- ### Install Poetry Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Install or upgrade poetry, a dependency management tool. ```bash pip install poetry -U ``` -------------------------------- ### Local Development - Install Dependencies Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Command to install all necessary dependencies for local development, including dev and docs. ```bash poetry install --with=dev,docs ``` -------------------------------- ### Take profit Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/readme.md Example of setting up a take profit order. ```python takeProfit = LimitOrder('SELL', 100, 260.00) takeProfit.orderId = ib.client.getReqId() takeProfit.parentId = parent.orderId takeProfit.transmit = True # Place bracket order trades = [] trades.append(ib.placeOrder(contract, parent)) trades.append(ib.placeOrder(contract, stopLoss)) trades.append(ib.placeOrder(contract, takeProfit)) print(f"Bracket order placed: {len(trades)} orders") ib.disconnect() ``` -------------------------------- ### Generate Documentation Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Install documentation dependencies and build the HTML documentation. ```bash poetry install --with=docs poetry run sphinx-build -b html docs html ``` -------------------------------- ### Connect to IB API and start the event loop Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/ordering.ipynb This code snippet shows how to import necessary libraries, start the asyncio event loop, and connect to the IB API using a specified host, port, and client ID. ```python from ib_async import * util.startLoop() ib = IB() ib.connect("127.0.0.1", 7497, clientId=13) ``` -------------------------------- ### Place a Simple Order Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Demonstrates placing a market order and monitoring its status. ```python from ib_async import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Create a contract and order contract = Stock('AAPL', 'SMART', 'USD') order = MarketOrder('BUY', 100) # Place the order trade = ib.placeOrder(contract, order) print(f"Order placed: {trade}") # Monitor order status while not trade.isDone(): ib.sleep(1) print(f"Order status: {trade.orderStatus.status}") ib.disconnect() ``` -------------------------------- ### Upload Package Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Install dependencies, configure PyPI token, and publish the package. ```bash poetry install poetry config pypi-token.pypi your-api-token poetry publish --build ``` -------------------------------- ### Basic Connection Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md A simple example to establish a connection to TWS or IB Gateway and disconnect. ```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() ``` -------------------------------- ### Importing and Starting Event Loop Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/basics.ipynb Imports all necessary components from ib_async and starts the event loop for live updates in notebooks. ```python from ib_async import * util.startLoop() ``` -------------------------------- ### Portfolio Monitoring Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Retrieves and displays current positions and open orders. ```python from ib_async import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Get current positions positions = ib.positions() print("Current Positions:") for pos in positions: print(f"{pos.contract.symbol}: {pos.position} @ {pos.avgCost}") # Get open orders orders = ib.openTrades() print(f"\nOpen Orders: {len(orders)}") for trade in orders: print(f"{trade.contract.symbol}: {trade.order.action} {trade.order.totalQuantity}") ib.disconnect() ``` -------------------------------- ### Example usage Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/api.md Demonstrates how to initialize and use the Watchdog class. ```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() ``` -------------------------------- ### Async Application Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Demonstrates how to use ib_async in an asynchronous Python application. ```python import asyncio from ib_async import * async def main(): ib = IB() await ib.connectAsync('127.0.0.1', 7497, clientId=1) # Your async code here ib.disconnect() asyncio.run(main()) ``` -------------------------------- ### Running Tests Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Command to install development dependencies and run tests using Poetry. ```bash poetry install --with=dev poetry run pytest ``` -------------------------------- ### PyGame Integration Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/recipes.md This example demonstrates how to integrate ib_async with the PyGame event loop by periodically calling `ib.sleep` to keep the API updated. ```python import ib_async as ibi import pygame def onTicker(ticker): screen.fill(bg_color) text = f'bid: {ticker.bid} ask: {ticker.ask}' quote = font.render(text, True, fg_color) screen.blit(quote, (40, 40)) pygame.display.flip() pygame.init() screen = pygame.display.set_mode((800, 600)) font = pygame.font.SysFont('arial', 48) bg_color = (255, 255, 255) fg_color = (0, 0, 0) ib = ibi.IB() ib.connect() contract = ibi.Forex('EURUSD') ticker = ib.reqMktData(contract) ticker.updateEvent += onTicker running = True while running: # This updates IB-insync: ib.sleep(0.03) # This updates PyGame: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() ``` -------------------------------- ### Bracket Order Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/api.md Example of how to submit a bracket order using the bracketOrder method. ```python for o in bracket: ib.placeOrder(contract, o) ``` -------------------------------- ### Real-time P&L Tracking Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Sets up a callback to receive and print real-time P&L updates. ```python from ib_async import * def onPnL(pnl): print(f"P&L Update: Unrealized: ${pnl.unrealizedPnL:.2f}, Realized: ${pnl.realizedPnL:.2f}") ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Subscribe to P&L updates account = ib.managedAccounts()[0] pnl = ib.reqPnL(account) pnl.updateEvent += onPnL # Keep running to receive updates try: ib.run() # Run until interrupted except KeyboardInterrupt: ib.disconnect() ``` -------------------------------- ### Contract Creation Examples Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/api.md Examples of creating various contract types using the Contract class and its specialized constructors. ```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') ``` -------------------------------- ### Place Bracket Order Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Example of placing a bracket order with parent, stop-loss, and take-profit orders. ```python trades = [] trades.append(ib.placeOrder(contract, parent)) trades.append(ib.placeOrder(contract, stopLoss)) trades.append(ib.placeOrder(contract, takeProfit)) print(f"Bracket order placed: {len(trades)} orders") ib.disconnect() ``` -------------------------------- ### Scanner Subscription Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/scanners.ipynb Example of using ScannerSubscription with tag values to find US stocks based on percentage gain, price range, and sorting. ```python sub = ScannerSubscription( instrument="STK", locationCode="STK.US.MAJOR", scanCode="TOP_PERC_GAIN" ) tagValue = [ TagValue("changePercAbove", "20"), TagValue("priceAbove", 5), TagValue("priceBelow", 50), ] ``` -------------------------------- ### Live Market Data Subscription Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Subscribes to live market data for a stock and prints quotes for a duration. ```python from ib_async import * import time ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Subscribe to live market data contract = Stock('AAPL', 'SMART', 'USD') ticker = ib.reqMktData(contract, '', False, False) # Print live quotes for 30 seconds for i in range(30): ib.sleep(1) # Wait 1 second if ticker.last: print(f"AAPL: ${ticker.last} (bid: ${ticker.bid}, ask: ${ticker.ask})") ib.disconnect() ``` -------------------------------- ### Basic Script Usage Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md A fundamental example of connecting, performing actions, and disconnecting in a script. ```python from ib_async import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=1) # Your code here ib.disconnect() ``` -------------------------------- ### Sending a request for contract details Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/basics.ipynb Example of how to send a request for contract details for a specific stock. ```python contract = Stock("TSLA", "SMART", "USD") ib.reqContractDetails(contract) ``` -------------------------------- ### Contract by conId Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/contract_details.ipynb Demonstrates creating a contract using its conId and qualifying it. ```python contract_4391 = Contract(conId=4391) ib.qualifyContracts(contract_4391) assert contract_4391 == amd ``` -------------------------------- ### Contract Examples Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/basics.ipynb Demonstrates various ways to define contracts, including using the ibapi way, keyword arguments, and specialized contract types. ```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"); ``` -------------------------------- ### Event Handling Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Examples of subscribing to order status updates and ticker events, both synchronously and asynchronously. ```python # Subscribe to events def onOrderUpdate(trade): print(f"Order update: {trade.orderStatus.status}") ib.orderStatusEvent += onOrderUpdate # Or with async async def onTicker(ticker): print(f"Price update: {ticker.last}") ticker.updateEvent += onTicker ``` -------------------------------- ### Retrieving positions using a request Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/basics.ipynb Example of retrieving positions using the `reqPositions()` method, demonstrating its slower performance compared to `positions()`. ```python %time l = ib.reqPositions() ``` -------------------------------- ### Stock Contract Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/contract_details.ipynb Demonstrates requesting contract details for a specific stock (AMD) on the SMART exchange in USD. ```python amd = Stock("AMD", "SMART", "USD") assert len(ib.reqContractDetails(amd)) == 1 ``` -------------------------------- ### Retrieving positions using current state Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/basics.ipynb Example of retrieving positions using the `positions()` method, which is preferred over `reqPositions()` for performance. ```python %time l = ib.positions() ``` -------------------------------- ### Non-existent Contract Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/contract_details.ipynb Demonstrates requesting contract details for a non-existent stock (XXX) and asserts that no contract is found. ```python xxx = Stock("XXX", "SMART", "USD") assert len(ib.reqContractDetails(xxx)) == 0 ``` -------------------------------- ### Intel Stock Contract Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/contract_details.ipynb Demonstrates requesting contract details for Intel stock (INTC) on the SMART exchange in USD. ```python intc = Stock("INTC", "SMART", "USD") assert len(ib.reqContractDetails(intc)) == 1 ``` -------------------------------- ### Get WSH metadata Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/api.md Example of how to retrieve Wall Street Horizon metadata, which includes available filters and event types. ```python # Get the list of available filters and event types: meta = ib.getWshMetaData() print(meta) ``` -------------------------------- ### Get WSH event data Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/api.md Example of how to retrieve Wall Street Horizon event data for a specific contract (IBM) and event types (Earnings Dates, Board of Directors meetings). ```python # For IBM (with conId=8314) query the: # - Earnings Dates (wshe_ed) # - Board of Directors meetings (wshe_bod) data = WshEventData( filter = '''{ "country": "All", "watchlist": ["8314"], "limit_region": 10, "limit": 10, "wshe_ed": "true", "wshe_bod": "true" }''') events = ib.getWshEventData(data) print(events) ``` -------------------------------- ### OrderStateNumeric Usage Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/api.md Example of how to use OrderStateNumeric for type checking. ```python state_numeric: OrderStateNumeric = state.numeric(digits=2) ``` -------------------------------- ### Getting Current Positions Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/basics.ipynb Retrieves a list of current positions. ```python ib.positions() ``` -------------------------------- ### Place an order and retrieve the Trade object Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/ordering.ipynb Demonstrates placing an order using `ib.placeOrder()` which returns a `Trade` object immediately. This object is live-updated. ```python trade = ib.placeOrder(contract, order) ``` -------------------------------- ### Get Market Price Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/tick_data.ipynb Retrieves the market price from a ticker object. ```python ticker.marketPrice() ``` -------------------------------- ### Package Contents Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/basics.ipynb Prints all available attributes within the ib_async package. ```python import ib_async print(ib_async.__all__) ``` -------------------------------- ### Historical Data Analysis Source: https://github.com/ib-api-reloaded/ib_async/blob/main/docs/index.md Example of requesting historical data for multiple timeframes for a stock. ```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) ``` -------------------------------- ### Build Package Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Build the distribution package for ib_async. ```bash poetry build ``` -------------------------------- ### Market Data Type Configuration Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Shows how to set market data types for delayed or real-time data. ```python # For free delayed data (no subscription required) ib.reqMarketDataType(3) # Delayed ib.reqMarketDataType(4) # Delayed frozen # For real-time data (requires subscription) ib.reqMarketDataType(1) # Real-time ``` -------------------------------- ### Code Formatting Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Commands to format and lint code using Ruff with Poetry. ```bash poetry run ruff format poetry run ruff check --fix ``` -------------------------------- ### Connection Refused Troubleshooting Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Ensures TWS/Gateway is running, API is enabled, and ports match for connection. ```python # Make sure TWS/Gateway is running and API is enabled # Check that ports match (7497 for TWS, 4001 for Gateway) ib.connect('127.0.0.1', 7497, clientId=1) # TWS ib.connect('127.0.0.1', 4001, clientId=1) # Gateway ``` -------------------------------- ### Qualify Contracts Example Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/contract_details.ipynb Demonstrates qualifying a contract (amd) and comparing it before and after qualification. ```python amd = Stock("AMD", "SMART", "USD") ib.qualifyContracts(amd) amd ``` -------------------------------- ### Local Development - Clone Repository Source: https://github.com/ib-api-reloaded/ib_async/blob/main/README.md Steps to clone the ib_async repository and navigate into the directory. ```bash git clone https://github.com/ib-api-reloaded/ib_async.git cd ib_async ``` -------------------------------- ### Create a contract and a market order Source: https://github.com/ib-api-reloaded/ib_async/blob/main/notebooks/ordering.ipynb This snippet shows how to define a contract (Forex EURUSD) and create a LimitOrder for selling 20000 units at a limit price of 1.11. ```python contract = Forex("EURUSD") ib.qualifyContracts(contract) order = LimitOrder("SELL", 20000, 1.11) ```