Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.
Articles

execute the same trades across multiple Interactive Brokers (IBKR) accounts

execute the same trades across multiple Interactive Brokers (IBKR) accounts

To use this script, you'll need to create a trading_config.json file with your trading parameters:

{
    "host": "127.0.0.1",
    "port": 7497,
    "client_id": 1,
    "symbol": "AAPL",
    "action": "BUY",
    "quantity": 100,
    "order_type": "MKT",
    "sec_type": "STK",
    "exchange": "SMART",
    "currency": "USD"
}

Key features of this script:

  1. Connects to multiple IBKR accounts using the IBKR API
  2. Places identical trades across all managed accounts
  3. Includes error handling and logging
  4. Tracks execution status for each account
  5. Configurable through external JSON file
  6. Supports different order types and instruments

To use this script:

  1. Install the IBKR API:

pip install ibapi

  • Make sure you have TWS (Trader Workstation) or IB Gateway running
  • Enable API connections in TWS/Gateway
  • Configure the port and client ID in TWS/Gateway
  • Update the trading_config.json with your desired trading parameters
  • Run the script

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import Order
import threading
import time
import logging
import json
from typing import List, Dict

class MultiAccountTrader(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.data = []
        self.order_id = 0
        self.active_accounts = []
        self.execution_status = {}
        
        # Setup logging
        logging.basicConfig(
            filename='multi_account_trades.log',
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s'
        )

    def error(self, reqId: int, errorCode: int, errorString: str):
        logging.error(f"Error {errorCode}: {errorString}")

    def nextValidId(self, orderId: int):
        self.order_id = orderId
        self.start_trading()

    def managedAccounts(self, accountsList: str):
        self.active_accounts = accountsList.split(",")
        logging.info(f"Active accounts: {self.active_accounts}")

    def execDetails(self, reqId: int, contract: Contract, execution):
        account = execution.acctNumber
        self.execution_status[account] = {
            'status': 'Executed',
            'shares': execution.shares,
            'price': execution.price,
            'time': execution.time
        }
        logging.info(f"Order executed for account {account}: {self.execution_status[account]}")

    def place_order_all_accounts(self, contract: Contract, order_template: Order):
        """Place the same order across all managed accounts."""
        for account in self.active_accounts:
            try:
                # Create a new order for each account
                order = Order()
                order.__dict__.update(order_template.__dict__)  # Copy all attributes
                order.account = account
                
                self.placeOrder(self.order_id, contract, order)
                logging.info(f"Order placed for account {account}, order ID: {self.order_id}")
                
                self.execution_status[account] = {'status': 'Pending'}
                self.order_id += 1
                time.sleep(0.1)  # Small delay between orders
                
            except Exception as e:
                logging.error(f"Error placing order for account {account}: {str(e)}")

    def create_contract(self, symbol: str, sec_type: str = "STK", 
                       exchange: str = "SMART", currency: str = "USD") -> Contract:
        """Create a contract object."""
        contract = Contract()
        contract.symbol = symbol
        contract.secType = sec_type
        contract.exchange = exchange
        contract.currency = currency
        return contract

    def create_order(self, action: str, quantity: float, 
                    order_type: str = "MKT") -> Order:
        """Create an order object."""
        order = Order()
        order.action = action
        order.totalQuantity = quantity
        order.orderType = order_type
        return order

def main():
    # Load configuration
    try:
        with open('trading_config.json', 'r') as f:
            config = json.load(f)
    except FileNotFoundError:
        logging.error("Configuration file not found")
        return

    # Initialize the trader
    app = MultiAccountTrader()
    
    # Connect to TWS
    app.connect(config.get('host', '127.0.0.1'), 
               config.get('port', 7497), 
               config.get('client_id', 0))

    # Start the client thread
    api_thread = threading.Thread(target=app.run, daemon=True)
    api_thread.start()
    time.sleep(1)  # Give time for connection to establish

    # Example trade setup
    try:
        # Create contract
        contract = app.create_contract(
            symbol=config['symbol'],
            sec_type=config.get('sec_type', 'STK'),
            exchange=config.get('exchange', 'SMART'),
            currency=config.get('currency', 'USD')
        )

        # Create order template
        order = app.create_order(
            action=config['action'],
            quantity=config['quantity'],
            order_type=config.get('order_type', 'MKT')
        )

        # Place orders for all accounts
        app.place_order_all_accounts(contract, order)

        # Wait for executions
        timeout = time.time() + 60  # 60 second timeout
        while time.time() < timeout and any(status.get('status') == 'Pending' 
                                          for status in app.execution_status.values()):
            time.sleep(1)

        # Log final status
        logging.info("Final execution status: " + json.dumps(app.execution_status, indent=2))

    except Exception as e:
        logging.error(f"Error in main trading loop: {str(e)}")
    finally:
        app.disconnect()

if __name__ == "__main__":
    main()

caa January 18 2025 15 reads 0 comments Print

0 comments

Leave a Comment

Please Login to Post a Comment.
  • No Comments have been Posted.

Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 1
Members Online 0

Total Members: 14
Newest Member: Frank_nKansas