Broker API HubMenu

Interactive Brokers API in Python: paper to first call

Connect to an IBKR paper account with ib_async or the Client Portal Web API: ports, API settings, account summary and free delayed data. Every step sourced.

Independent and unofficialChecked Code not yet run on a demo account

Risk warning: CFDs and spread bets are complex instruments and come with a high risk of losing money rapidly due to leverage. You can lose money on these products, and each provider publishes its own loss figure under FCA rules. You should consider whether you understand how they work and whether you can afford to take the high risk of losing your money. Automated and API trading can amplify losses through bugs, connectivity failures and runaway orders.

Demo accounts only. Credentials are read from environment variables on your own machine. No field on this site asks for a key, a username or a password.

Steps

  1. Log in to paper, not live

    Start TWS or IB Gateway and log in with your paper trading username. It is separate from your live one and sits in Client Portal settings. IBKR's older setup guide gives the default TWS socket ports as 7497 for a paper session and 7496 for a live one, and says they can be changed. This site also holds 4002 paper and 4001 live for IB Gateway: those two were not found on the IBKR pages read on 12 October 2026, so check the socket port shown in your own API settings. Get the port wrong and you are either not connected or connected to real money.

    interactivebrokers.github.iochecked

  2. Switch the API on

    In TWS open Global Configuration, then API, then Settings. Tick Enable ActiveX and Socket Clients and check the socket port. Read-Only API hides order information from the API. Leave it on for this quickstart and connect with readonly=True; IBKR's guide says to disable it for API use, so untick it when you are ready to send orders.

    interactivebrokers.comchecked

  3. Install ib_async

    ib_async is the community successor to ib_insync and needs Python 3.10 or later. IBKR's own ibapi client needs 3.11. For the JavaScript and curl tabs, run the Java based Client Portal Gateway instead and log in at https://localhost:5000.

    Python
    # Python 3.10 or later
    pip install ib_async
    
    JavaScript
    // Nothing to install: Node 18 or later has fetch built in.
    // Start the Client Portal Gateway (needs a Java runtime), then log in at https://localhost:5000
    //   macOS or Linux: bin/run.sh root/conf.yaml
    //   Windows:        bin\run.bat root\conf.yaml
    
    curl
    # Client Portal Gateway (needs a Java runtime), from its folder:
    bin/run.sh root/conf.yaml
    # Windows: bin\run.bat root\conf.yaml
    # Then open https://localhost:5000 in a browser and log in with your paper username.
    

    pypi.orgchecked

  4. Connect and check the clock

    Connect to 127.0.0.1 on the paper port with a clientId unique to this script. reqCurrentTime proves the socket works. On the Web API, POST /iserver/auth/status should come back with authenticated true. It is a POST, not a GET.

    Python
    from ib_async import IB
    
    ib = IB()
    # TWS paper 7497, IB Gateway paper 4002
    ib.connect('127.0.0.1', 7497, clientId=1, readonly=True)
    print("Server time:", ib.reqCurrentTime())
    print("Accounts:", ib.managedAccounts())
    ib.disconnect()
    
    JavaScript
    // This tab uses the Client Portal Web API with fetch, not the TWS socket API.
    // The gateway runs on your own machine with a self-signed certificate.
    // For localhost only, run with: NODE_TLS_REJECT_UNAUTHORIZED=0 node step.mjs
    const BASE_URL = "https://localhost:5000/v1/api";
    
    const res = await fetch(`${BASE_URL}/iserver/auth/status`, { method: "POST" });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const status = await res.json();
    console.log("authenticated:", status.authenticated, "connected:", status.connected);
    
    curl
    # -k accepts the gateway's self-signed certificate. Use it against localhost only.
    curl -k -s -X POST "https://localhost:5000/v1/api/iserver/auth/status"
    

    ibkrcampus.comchecked

  5. First real call: your account

    accountSummary returns balances as AccountValue rows. If you see NetLiquidation, you are in. On the Web API, call GET /portfolio/accounts first: IBKR requires it before any other /portfolio endpoint.

    Python
    from ib_async import IB
    
    ib = IB()
    ib.connect('127.0.0.1', 7497, clientId=1, readonly=True)
    for v in ib.accountSummary():
        if v.tag in ('NetLiquidation', 'AvailableFunds'):
            print(v.account, v.tag, v.value, v.currency)
    ib.disconnect()
    
    JavaScript
    // This tab uses the Client Portal Web API with fetch, not the TWS socket API.
    // The gateway runs on your own machine with a self-signed certificate.
    // For localhost only, run with: NODE_TLS_REJECT_UNAUTHORIZED=0 node step.mjs
    const BASE_URL = "https://localhost:5000/v1/api";
    
    const res = await fetch(`${BASE_URL}/portfolio/accounts`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const accounts = await res.json();
    console.log(accounts.map(a => a.id));
    
    curl
    # Set IBKR_ACCOUNT_ID as an environment variable first (an id from the call above).
    # Must be called before other /portfolio endpoints
    curl -k -s "https://localhost:5000/v1/api/portfolio/accounts"
    
    # Then, for example:
    curl -k -s "https://localhost:5000/v1/api/portfolio/$IBKR_ACCOUNT_ID/summary"
    

    interactivebrokers.comchecked

  6. Prices without paying for data

    Call reqMarketDataType(3) to accept delayed data when you have no live subscription. Forex needs no extra market data subscription, so EURUSD midpoint bars are the safest first request. Live data needs 500 USD in the account, the subscription cost on top and the Market Data API Acknowledgement.

    Python
    from ib_async import IB, Forex
    
    ib = IB()
    ib.connect('127.0.0.1', 7497, clientId=1, readonly=True)
    ib.reqMarketDataType(3)  # 1 live, 2 frozen, 3 delayed, 4 delayed frozen
    
    contract = Forex('EURUSD')
    ib.qualifyContracts(contract)  # fills in conId and exchange; skip it and the request can come back empty
    
    bars = ib.reqHistoricalData(
        contract,
        endDateTime='',
        durationStr='1 D',
        barSizeSetting='1 hour',
        whatToShow='MIDPOINT',
        useRTH=False,  # forex has no regular trading hours, so useRTH=True often returns an empty list
    )
    if not bars:
        raise SystemExit('No bars returned. Check the symbol, the duration and that the gateway is connected.')
    for b in bars[-3:]:
        print(b.date, b.open, b.high, b.low, b.close)
    ib.disconnect()
    
    JavaScript
    // This tab uses the Client Portal Web API with fetch, not the TWS socket API.
    // The gateway runs on your own machine with a self-signed certificate.
    // For localhost only, run with: NODE_TLS_REJECT_UNAUTHORIZED=0 node step.mjs
    // Snapshot pre-flight and field 31 are not confirmed on a page we opened.
    // The first call starts the stream; repeat it to get values.
    const BASE_URL = "https://localhost:5000/v1/api";
    const CONID = process.env.IBKR_CONID; // the contract id, set as an environment variable
    const url = `${BASE_URL}/iserver/marketdata/snapshot?conids=${CONID}&fields=31`;
    
    await fetch(url); // pre-flight
    await new Promise(r => setTimeout(r, 1000));
    const res = await fetch(url);
    console.log(await res.json());
    
    curl
    # Snapshot pre-flight and field 31 (last price) are not confirmed on a page we opened.
    # Set IBKR_CONID (the contract id) as an environment variable, call once, wait, call again.
    curl -k -s "https://localhost:5000/v1/api/iserver/marketdata/snapshot?conids=$IBKR_CONID&fields=31"
    sleep 1
    curl -k -s "https://localhost:5000/v1/api/iserver/marketdata/snapshot?conids=$IBKR_CONID&fields=31"
    

    interactivebrokers.comchecked

Interactive Brokers limits to pace against

LimitValueScopeSource
Global requests a second (Web API)10Per authenticated username, that is per Web API sessionibkrcampus.comchecked corroborated by interactivebrokers.com/docs/web-api/trading/usage-and-availability/pacing-limitations
Historical market data requestsEither 10 req/s or 50 req/minute, as the page words itGET /iserver/marketdata/history onlyinteractivebrokers.comchecked corroborated by ibkrcampus.com/campus/ibkr-api-page/webapi-doc/
Market data snapshot requests a second10GET /iserver/marketdata/snapshot onlyinteractivebrokers.comchecked corroborated by ibkrcampus.com/campus/ibkr-api-page/webapi-doc/
Order and trade list requests1 req/5 sGET /iserver/orders and GET /iserver/trades, each counted on its owninteractivebrokers.comchecked corroborated by ibkrcampus.com/campus/ibkr-api-page/webapi-doc/
Session validation requests a minute1GET /sso/validate onlyinteractivebrokers.comchecked corroborated by ibkrcampus.com/campus/ibkr-api-page/webapi-doc/
Session keep alive requests a second1GET /tickle onlyinteractivebrokers.comchecked corroborated by ibkrcampus.com/campus/ibkr-api-page/webapi-doc/

Sources

Sections