IBKR Paper vs Live Trading: Separating a Bot Before Go-Live

To move an Interactive Brokers bot from paper to live trading without mixing the two, treat them as two deployments rather than one switch: separate configuration files, IBKR users, ports, client IDs and state directories; a check of the accounts IBKR reports on every connect; Read-Only API for the first data tests in the live session; and a written release procedure for the first live order. IBKR documents default socket ports of 7497 for paper and 7496 for live TWS sessions, and 4002 and 4001 for IB Gateway. Ports can be changed, so a port alone proves nothing about the account behind it. This article walks through each layer with a tested Python check and a release checklist, as of November 2026.

Why paper and live trading need more than one switch

Many bots start with one configuration and a flag such as LIVE = False. Later the flag changes the port, the account, the limits and the log file at once. That is convenient and fragile: one copied file, one wrong environment variable or one TWS session logged in to the wrong user is enough to run paper logic on a live account, or to test a quick fix in live trading by accident.

IBKR’s own documentation points to the weak spots. Its older, now deprecated API guide warns that when paper and live TWS run on the same computer, you have to make sure the client application connects to the right one. Its paper trading guide says the paper interface clearly indicates a simulated account; if it does not, you are in a production account and liable for every trade that fills. And paper is not a scaled copy of live: trading permissions and market data subscriptions match the regular account, but every paper account starts with USD 1,000,000 of paper equity and can be reset to up to five times the production account’s value. A sizer based on a percentage of equity therefore trades very different quantities in paper.

The goal is a setup in which a mix-up fails loudly before the first request, not after the first fill.

Separate configurations, not a flag

Paper and live become two deployments of the same code. Everything that identifies a deployment is set per environment and checked for overlap. The file names are examples; the port defaults come from IBKR and can be changed in TWS or IB Gateway.

ItemPaperLive
Configuration filepaper.tomllive.toml
IBKR user and sessionPaper userLive user, ideally a dedicated username for the bot
Account whitelistPaper account IDLive account ID
Socket port (IBKR default)7497 TWS, 4002 IB Gateway7496 TWS, 4001 IB Gateway
Client IDOwn rangeOwn range
State directoryKill switch, order map and logs for paperThe same for live, never shared
Read-only flag in the botAs neededOn until the release
Risk limitsAs in live, so they get testedReduced at first
Alerts and log linesMarked PAPERMarked LIVE

The bot takes exactly one configuration path at startup and has no default that points to live. Credentials stay out of both files and out of the repository. Separate operating system users or containers for paper and live keep log files and state from mixing, even when both run on the same machine.

Check the account on every connect

The port tells you where the bot connected, not which account sits behind it. The account list does: according to IBKR, TWS automatically sends the list of managed accounts once the connection is established, as a comma-separated string in the managedAccounts callback. In ib_async, ib.managedAccounts() returns the same list. The bot compares it with the whitelist in its configuration and stops on any surprise before it requests market data or sends an order, and again after every reconnect.

Two functions cover most mix-ups. check_pair runs on both configuration files before anything starts and fails if paper and live share a port, a client ID, a state directory or an account, or if a port is IBKR’s default for the other mode. check_session runs right after connecting. The code uses only the standard library, connects to nothing and passed its tests with Python 3.9 and 3.12; account IDs and paths are placeholders.

"""Paper/live separation checks. Python 3 standard library only.
check_pair runs on the two config files before anything starts; check_session runs
right after connecting. Neither function connects anywhere or sends orders."""
import unittest
from dataclasses import dataclass

DEFAULT_PAPER_PORTS = {7497, 4002}   # IBKR defaults: TWS paper, IB Gateway paper
DEFAULT_LIVE_PORTS = {7496, 4001}    # IBKR defaults: TWS live, IB Gateway live


@dataclass(frozen=True)
class Env:
    name: str              # "paper" or "live"
    accounts: frozenset    # the only account IDs this config may see
    port: int
    client_id: int
    state_dir: str         # kill switch, order map and logs live here
    read_only: bool        # True for first data tests: the adapter refuses all orders


def check_pair(paper, live):
    problems = []
    if (paper.name, live.name) != ("paper", "live"):
        problems.append("configs must be named 'paper' and 'live'")
    for field in ("port", "client_id", "state_dir"):
        if getattr(paper, field) == getattr(live, field):
            problems.append(f"paper and live share {field}")
    if paper.accounts & live.accounts:
        problems.append("paper and live share an account ID")
    if paper.port in DEFAULT_LIVE_PORTS or live.port in DEFAULT_PAPER_PORTS:
        problems.append("a port is the IBKR default of the other mode")
    return problems


def check_session(env, reported):
    """reported: account IDs from managedAccounts (split the TWS API string at commas)."""
    seen = {a.strip() for a in reported if a.strip()}
    if not seen:
        return ["no account reported"]
    if not seen <= env.accounts:
        return [f"{env.name} config, unexpected account(s): {sorted(seen - env.accounts)}"]
    return []


class SeparationTest(unittest.TestCase):
    PAPER = Env("paper", frozenset({"PAPER_ID"}), 4002, 11, "/srv/bot/paper", True)
    LIVE = Env("live", frozenset({"LIVE_ID"}), 4001, 21, "/srv/bot/live", True)

    def test_clean_pair(self):
        self.assertEqual(check_pair(self.PAPER, self.LIVE), [])

    def test_copied_file_is_caught(self):
        copy = Env("live", self.PAPER.accounts, 4002, 11, "/srv/bot/paper", False)
        problems = check_pair(self.PAPER, copy)
        self.assertEqual(len(problems), 5)

    def test_live_account_behind_paper_config(self):
        self.assertEqual(check_session(self.PAPER, "PAPER_ID".split(",")), [])
        self.assertEqual(check_session(self.PAPER, "LIVE_ID".split(",")),
                         ["paper config, unexpected account(s): ['LIVE_ID']"])
        self.assertEqual(check_session(self.LIVE, ["", " "]), ["no account reported"])


if __name__ == "__main__":
    unittest.main()

Wired into ib_async, the session check sits directly after connect(). The parameters follow the ib_async 2.1.0 documentation, which says to set readonly to True when the API is in read-only mode. This fragment was checked for syntax only, not run against TWS or IB Gateway:

from ib_async import IB


def connect_checked(env):
    ib = IB()
    ib.connect("127.0.0.1", env.port, clientId=env.client_id, readonly=env.read_only)
    problems = check_session(env, ib.managedAccounts())
    if problems:
        ib.disconnect()
        raise SystemExit("; ".join(problems))
    return ib

connect() returns only after its startup sync, which already reads positions and account values; the check then runs before the first order or market data request. Take the account IDs for the whitelists from the first read-only connection of each user, and keep them in the configuration, not in the code.

Read-Only API for the first data tests

Read-Only API is a setting in TWS and IB Gateway. IBKR’s older, now deprecated API documentation describes it as a way to configure TWS not to accept API orders, enabled by default as an additional precautionary measure, and notes that information about orders is not available to the API in read-only mode. IBKR’s current setup instructions for API connections say to uncheck it, which a bot that places orders needs: in TWS under Global Configuration, API, Settings; in IB Gateway under Configure, Settings, API, Settings. The current setup pages do not state a default, so do not rely on one. Because IBKR saves TWS settings separately for live and paper users, the setting can be on in one and off in the other, so check both.

That makes Read-Only the right mode for the first live connection. With it on, the bot can show that the account check passes, contracts resolve, market data arrives and positions match what Client Portal shows, while TWS or IB Gateway refuses orders on its own. Set the bot’s own read-only flag as well, so that its adapter refuses orders before they reach TWS; a forgotten setting then does not leave a single layer of protection. Only when these tests pass is Read-Only unchecked for the live user, by hand, as one step of the release.

A read-only session in the live account is a good moment to test everything except the orders themselves:

  • the account check passes, and fails on purpose with a wrong whitelist;
  • contracts resolve and market data arrives for every instrument in the configuration;
  • positions and account values in the bot match Client Portal;
  • the bot’s own read-only flag refuses an order attempt before anything reaches TWS, and the refusal shows up in the log and the alerts; do not probe the TWS setting with a real order in the live account;
  • a deliberate network interruption raises an alert and a clean reconnect, followed by a new account check.

A release procedure for the first live order

Going live is a release, not a toggle. Write the steps down once and follow them every time, including for later updates:

  1. Freeze: tag the version and record the commit, the Python and library versions and the TWS or IB Gateway build.
  2. Exit criteria: the paper phase met the criteria agreed in advance, such as provoked disconnects, one kill-switch test and zero unexplained position differences.
  3. Configuration diff: a second person, or you on the next day, compares paper.toml and live.toml. Only the fields in the table above may differ, and check_pair passes.
  4. Read-only connection: start live with Read-Only on and confirm account, data and positions.
  5. Arm: uncheck Read-Only for the live user, set the bot’s read-only flag to false and start with reduced limits, for example one instrument and the smallest size.
  6. Observe: watch the first orders, fills and the reconciliation, and trigger the kill switch once on purpose.
  7. Record: who released which version when, and who approved it.
  8. Rollback: know in advance how to stop the bot, cancel its orders, close positions if needed and return to the previous version.

The steps look bureaucratic until something goes wrong: at Knight Capital in 2012, a deployment that no second person checked left old code on one of eight servers, a failure the SEC’s order traces in detail and the trading system audit guide summarizes.

Limits and risks of paper/live separation

  • Separation prevents mix-ups, not losses. A correctly separated bot can still trade a strategy that loses money; with leveraged products, losses can exceed the capital deployed.
  • Paper fills are simulated. Slippage and partial fills will look different live; the pre-live checklist linked in the next section lists the differences IBKR documents.
  • Checks are only as good as the configuration. A wrong account ID in the whitelist passes the check. That is why the configuration diff needs a second pair of eyes.
  • Settings live per user and installation. After a reinstall, a new machine or a new username, check Read-Only, ports and the other API settings again.
  • Two sessions on one machine need two ports. IBKR’s older API guide notes that only one application can listen on a port at a time, so parallel paper and live sessions need different ports.
  • People remain the weak point. A procedure helps only if it is followed when the release is urgent, too.

Paper/live separation checklist before go-live

  • Two configuration files, one path at startup, no default that points to live.
  • check_pair passes: no shared port, client ID, state directory or account.
  • Account whitelists filled from the first read-only connection of each user.
  • check_session runs on every connect and reconnect and stops the bot on a mismatch.
  • Read-Only API checked in the settings of both users; the bot’s own read-only flag on until the release.
  • Alerts and log lines carry PAPER or LIVE.
  • Release steps written down, including the rollback, and the first live session at reduced size.
  • The rollback practiced once in the paper account: stop, cancel, close, return to the previous version.
  • After every reinstall, new machine or new username: Read-Only, ports and API settings checked again.

Exit criteria for the paper phase itself, and the differences between paper and live fills that IBKR documents, are covered in the pre-live checklist for AI-built trading bots; for running IB Gateway without a desktop session, see IB Gateway in Docker after IBC.

Frequently asked questions

What are the default IBKR API ports for paper and live trading?

According to IBKR, TWS uses port 7496 for live and 7497 for paper sessions by default, and IB Gateway uses 4001 for live and 4002 for paper. These are defaults, not rules: the port can be changed in the API settings, and the port in your application has to match the one set in TWS or IB Gateway. Because ports can be changed, a bot should also check which account it is connected to.

How do I switch an IBKR trading bot from paper to live?

Do not flip a flag. Prepare a separate live configuration with its own port, client ID, state directory and account whitelist, and compare it with the paper file. Connect to the live user with Read-Only API on and confirm account, data and positions. Then uncheck Read-Only, start with reduced size and watch the first orders, with a rollback plan ready.

What does Read-Only API do in TWS and IB Gateway?

With Read-Only API enabled, TWS does not accept orders from API applications. IBKR’s older, now deprecated API documentation describes it as enabled by default; the current setup instructions only say to uncheck it to place orders, in TWS and in IB Gateway. TWS settings are saved separately for paper and live users, so check the setting in each. For the first data tests in a live session, leaving it on is a sensible extra layer.

How can a bot tell whether it is connected to a paper or a live account?

Compare account IDs, not ports. When the connection is established, TWS sends the list of accounts the logged-in user can access through the managedAccounts callback; ib_async returns it from managedAccounts(). Keep the paper and live account IDs in separate configuration files and stop the bot before its first order or market data request if the reported list contains anything that is not on the whitelist.

Why does my bot connect to the IBKR paper account but not to the live one?

Usually because of the settings. IBKR saves TWS settings separately for live and paper users, so enabling socket clients, unchecking Read-Only API or changing the port in the paper session changes nothing for the live user. The live user also listens on port 7496 by default instead of 7497, and the port in the bot has to match. Configure each user separately, then let the bot verify the account IDs it reports.

Sources and status

As of November 2026. Third-party rules, prices and APIs may have changed since; the providers' current documentation and the official texts are authoritative.

This article is also available in German: Paper und Live sauber trennen: so schützt sich ein Trading-Bot.

Want the paper/live setup and release steps of your bot reviewed before go-live? Get in touch — a free intro call clarifies your setup and what the review should cover. More: Trading system code review and audit.