Metadata-Version: 2.4
Name: py-ib-controller
Version: 0.2.0
Summary: Login/launch controller for TWS and IBKR Gateway, via an in-process Java agent
Author-email: gnzsnz <8376642+gnzsnz@users.noreply.github.com>
License-Expression: Apache-2.0
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Development Status :: 3 - Alpha
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: aeventkit
Requires-Dist: attrs
Requires-Dist: cattrs
Requires-Dist: python-dotenv>=1.2.3
Requires-Dist: platformdirs>=4.11.7
Requires-Dist: typer>=0.15.1
Requires-Dist: typed-settings
Requires-Dist: anyio>=4.15.1
Dynamic: license-file

# ibcontroller

An ibgateway/TWS automation tool.

Heavily inspired by [IBC](https://github.com/IbcAlpha/IBC) project, now archived.

## What it does?

- Finds ibgateway/TWS installation, JRE and launch it.
- Automates user/password entry, waits for MFA.
- Automates ibgateway/TWS settings.
- Manages pop-ups and automatically accept.
- Manages ibgateway/TWS restarts.

It provides a "**declarative**" engine, so settings and pop-ups can be "declared" by configuration entries.

**v0.2.0 is a breaking change**; see [docs/Upgrading.md](./docs/Upgrading.md).

## How to use it

To use `ibcontroller` the recommended way is to install with uv/pipx or pip:

```bash
# install with uv/pipx
uv tool install py-ib-controller

# with pip
uv pip install py-ib-controller
```

Give it a spin, `ib-controller run --dotenv=.env-paper --trading-mode=paper --program=gateway --tws-channel latest`

https://github.com/user-attachments/assets/b97f7180-29d9-4e09-b32f-8be838dff0e2

You can check the full list of [cli parameters](#cli-parameters) or [config keys](#configuration).

To it build from source:

```bash
# 0. Fetch the code
git clone https://github.com/gnzsnz/ibcontroller.git
cd ibcontroller
# 1. Build the Java agent jar and install the package (editable, for a source checkout)
make dist
uv sync

# 2. Scaffold a starter config directory (platformdirs default, or $IBC_APP_DIR)
uv run ibcontroller init

# 3. Export IBC_USERID / IBC_PASSWORD or create an .env file (see Credentials below).
# 4. Run it -- Ctrl-C for a graceful shutdown
uv run ibcontroller run
```

For a detailed build guide please check the [development guide](./docs/development.md).

`ibcontroller run` scaffolds the config directory automatically the first time
`ibcontroller.toml` is missing (same effect as running `init` first), so it can also be
run directly on a fresh install. It will still fail with a clear error naming whichever
setting is actually missing (in practice, just the two credential env vars).

### CLI parameters

You can use the following cli parameters:

```text
 Usage: ibcontroller [OPTIONS] COMMAND [ARGS]...

 Login/launch controller for TWS and IBKR Gateway.

╭─ Options ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --install-completion          Install completion for the current shell.                                                                 │
│ --show-completion             Show completion for the current shell, to copy it or customize the installation.                          │
│ --help                        Show this message and exit.                                                                               │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Commands ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ init     Scaffold the config directory with starter ibcontroller.toml/                                                                  │
│          labels.json.example files. Never overwrites a file                                                  │
│          that already exists unless --force is given.                                                                                   │
│ run      Run one ibcontroller instance until it stops (Ctrl-C for a graceful shutdown,                                                  │
│          or Gateway/TWS exiting or restarting on its own). Scaffolds the config directory                                               │
│          first if it's missing, same as `ibcontroller init`.                                                                            │
│ version  Print the installed ibcontroller version.                                                                                      │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
```

And the `ibcontroller run` parameters:

```text
 Usage: ibcontroller run [OPTIONS]

 Run one ibcontroller instance until it stops (Ctrl-C for a graceful shutdown, or Gateway/TWS exiting or restarting on its own). Scaffolds the config directory first if it's
 missing, same as `ibcontroller init`.

 `--trading-mode`/`--tws-path`/`--tws-channel`/`--program`/`--tws-settings-path`/
 `--instance` let one invocation pick these `Config` fields directly, overriding
 TOML/env for this run only -- e.g. `ibcontroller run --trading-mode=live
 --dotenv=.env-live` and `ibcontroller run --trading-mode=paper
 --dotenv=.env-paper` run side by side from one shared config.

╭─ Options ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --dotenv                   <path>        Optional .env file to load into the environment before reading config (only fills variables not already set).                          │
│ --app-dir                  <path>        Override IBC_APP_DIR for this invocation -- config/log/run all move under {app_dir}/{config,log,run} instead of the platform           │
│                                          default.                                                                                                                               │
│ --trading-mode             <live|paper>  Override Config.trading_mode ('live'/'paper') for this invocation.                                                                     │
│ --tws-path                 <path>        Override Config.tws_path (the TWS/Gateway install-path inference) for this invocation.                                                 │
│ --tws-channel              <str>         Override Config.tws_channel ('stable'/'latest', filters install auto-detection) for this invocation.                                   │
│ --program                  <gateway|tws> Override Config.program ('gateway'/'tws') for this invocation.                                                                         │
│ --tws-settings-path        <path>        Override Config.tws_settings_path (where TWS/Gateway stores its own settings) for this invocation.                                     │
│ --instance                 <str>         Override Config.instance (per-instance log/trace/socket names) for this invocation. Defaults to '{program}-{trading_mode}', so         │
│                                          --trading-mode alone is usually enough to keep paper/live instances apart.                                                             │
│ --help                                   Show this message and exit.                                                                                                            │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
```

### Running paper and live in parallel

To run parallel instances in `live`and `paper`trading mode, we need to pass credentials and trading mode:

```bash
# terminal 1
ibcontroller run --trading-mode=live --dotenv=.env-live
# terminal 2
ibcontroller run --trading-mode=paper --dotenv=.env-paper
```

`--app-dir` (also accepted by `init`) overrides `IBC_APP_DIR` for one
invocation, for pointing each instance's config/log/run dirs somewhere different too.

## Configuration

`ibcontroller` is configured through a TOML file (its own settings under an
`[ibcontroller]` table) and/or environment variables, with precedence `defaults < TOML file < .env < environment`. Environment
can be loaded from a `.env` file. Credentials are environment-variable-only and must
never appear in the config file.

A sample file with all environment settings is provided as an [example](./ibcontroller.env).
In the same way a sample `.toml` file with all config is
[available](./ibcontroller/data/ibcontroller.toml.example).

`ibcontroller init` (or the first `ibcontroller run`) copies starter templates into the
config directory: `ibcontroller.toml` (every key commented out -- safe to run as-is,
since it changes nothing versus the defaults below) and `labels.json.example` (an
optional, sparse override for window/button labels, applied once renamed to
`labels.json` -- see `labels.py`'s own docstring for the merge mechanism).
`labels.json.example` is deliberately left inert (kept under its `.example` name)
until renamed -- it does not apply just by existing. The templates themselves are
bundled inside the installed package (`ibcontroller/data/`), not kept in this
repository.

### Credentials (env only, never in the configuration file)

A single pair is used regardless of `trading_mode`.

| Env var | Description |
| --- | --- |
| `IBC_USERID` | Account user id |
| `IBC_PASSWORD` | Account password |

Each also accepts a `_FILE`-suffixed variant (`IBC_USERID_FILE`,
`IBC_PASSWORD_FILE`) that reads the value from a file instead —
Docker/Compose secrets, so a value never has to sit in the process environment.

The startup `IBC_*` environment dump masks any variable whose name contains
`PASSWORD`, `USERID`, `SECRET`, `TOKEN`, `TOTP` or `KEY` (e.g.
`IBC_PASSWORD_PAPER`, set by other tooling), except `_FILE` variants, which
only hold a path.

### File location

When environment variable `IBC_APP_DIR` is not set, then
`ibcontroller` will use the standard platform directories.

| Location | Directory | Platform |
| --- | --- | --- |
| `config_dir` | `~/.config/ibcontroller` | Linux |
| `config_dir` | `~/Library/Application Support/ibcontroller` | macOS |
| `log_dir` | `~/.local/state/ibcontroller/log` | Linux |
| `log_dir` | `~/Library/Logs/ibcontroller` | macOS |
| `socket_dir` | `/run/user/<uid>/ibcontroller` | Linux |
| `socket_dir` | `~/Library/Caches/TemporaryItems/ibcontroller` | macOS |

When `IBC_APP_DIR` is set then:

- `config_dir`-> `IBC_APP_DIR/config`
- `log_dir`-> `IBC_APP_DIR/log`
- `socket_dir` -> `IBC_APP_DIR/run`

Socket paths (`socket_dir/ibcontroller-agent-<instance>-events.sock`) must fit
the Unix socket limit: 102 bytes on macOS, 106 on Linux. On macOS the default
`socket_dir` leaves room for an instance name of about 15 characters with a
5-letter user name (each extra user-name character costs one). Over the limit,
`ibcontroller run` stops with an error naming the path; use a shorter instance
name or set `IBC_APP_DIR` to a shorter directory.

### Settings

`ibcontroller`ships with sensible defaults.  **Only the two credential env vars below are actually mandatory**
 everything else here has a safe default or is auto-detected.

`None` on a `TWS/Gateway setting` row is a deliberate third state, not just
"unset" yes/no/unset convention: set it explicitly to apply value, or leave
it `None` to leave TWS/Gateway's existing setting alone. This is the actual
enable/disable mechanism for these fields, not a side effect of the type
allowing `None`. `Config`'s schema is closed — an unknown key in
`ibcontroller.toml` fails at startup with a clean error (`ConfigError`).

| TOML key | Env var or CLI flag | Description | Default |
| --- | --- | --- | --- |
| `instance` | `IBC_INSTANCE`, `--instance` | Instance name; separate log/trace files per instance | `"{program}-{trading_mode}"` (e.g. `"gateway-paper"`) |
| `program` | `IBC_PROGRAM`, `--program` | `"gateway"` or `"tws"` (any letter case); anything else is a config error | `"gateway"` |
| `tws_version` | `IBC_TWS_VERSION` | Installed TWS/Gateway version, e.g. `"10.50"` | `None` — auto-detected (see below) |
| `tws_channel` | `IBC_TWS_CHANNEL`, `--tws-channel` | `"stable"`/`"latest"`; narrows auto-detection to one update channel | `"stable"` |
| `tws_path` | `IBC_TWS_PATH`, `--tws-path` | Override TWS/gateway install-path inference | `None` |
| `tws_settings_path` | `IBC_TWS_SETTINGS_PATH`, `--tws-settings-path` | TWS/Gateway settings dir (per instance) | `None` |
| `trace_enabled` | `IBC_TRACE_ENABLED` | Enable verbose raw wire trace (`cmd-{instance}.jsonl`/`events-{instance}.jsonl`) | `false` |
| `log_dir` | `IBC_LOG_DIR` | Where ibcontroller's own log file lives; always resolved at startup | platform default |
| `log_level` | `IBC_LOG_LEVEL` | `debug`/`info`/`warning`/`error` | `info` |
| `log_sink` | `IBC_LOG_SINK` | `"std"` (console only) or `"file"` (only, under `log_dir`) — exclusive, not both. Covers `ibcontroller-{instance}.log` and `gateway-{instance}.log` only; the Java agent log and the wire trace are always file, unaffected — see "Logging" below | `"std"` |
| `log_max_bytes` | `IBC_LOG_MAX_BYTES` | Rotate log/trace files at this size in bytes; `0` disables rotation. Only respected when `log_sink="file"` | `10485760` (10 MiB) |
| `log_backup_count` | `IBC_LOG_BACKUP_COUNT` | Number of rotated backups to keep. Only respected when `log_sink="file"` | `5` |
| `diagnostic_scope` | `IBC_DIAGNOSTIC_SCOPE` | `"known"`/`"unknown"`/`"all"` — which windows get a structure dump logged (see `docs/Configuration.md`'s "Diagnostics") | `"known"` |
| `diagnostic_when` | `IBC_DIAGNOSTIC_WHEN` | `"open"`/`"openclose"`/`"never"` — when to log a structure dump | `"never"` |
| `diagnostic_settings_sweep` | `IBC_DIAGNOSTIC_SETTINGS_SWEEP` | Log a dump of each Global Configuration tree node in `labels.settings.sweep_paths` (see `docs/Configuration.md`'s "Diagnostics") | `false` |
| (env only) | `IBC_APP_DIR`, `--app-dir` | Override file locations (config/log/run) for container mode; `--app-dir`/`init`/`run` set the env var for the invocation, same effect |

TWS/ibgateway settings

| TOML key | Env var or CLI flag | Description | Default |
| --- | --- | --- | --- |
| `trading_mode` | `IBC_TRADING_MODE`, `--trading-mode` | `"live"` or `"paper"`; which account to authenticate as | `"paper"` |
| `read_only_login` | `IBC_READ_ONLY_LOGIN` | TWS-only (Gateway warns and logs in normally); clicks "Enter Read Only" on the 2FA frame instead of waiting for the push, no effect without 2FA (paper) | `false` |
| `existing_session_action` | `IBC_EXISTING_SESSION_ACTION` | `manual`/`primary`/`primaryoverride`/`secondary` | `"manual"` |
| `login_dialog_display_timeout` | `IBC_LOGIN_DIALOG_DISPLAY_TIMEOUT` | Seconds to wait for the login dialog | `60.0` |
| `mfa_timeout` | `IBC_MFA_TIMEOUT` | IB's 2FA limit in seconds; a dialog closing at or after it counts as timed out | `180.0` |
| `relogin_after_mfa_timeout` | `IBC_RELOGIN_AFTER_MFA_TIMEOUT` | Log in again after a timed-out push, and enforce `mfa_exit_interval` after an approved one | `false` |
| `mfa_exit_interval` | `IBC_MFA_EXIT_INTERVAL` | Post-approval wait for login to complete when relogin is on | `60.0` |
| `mfa_timeout_action` | `IBC_MFA_TIMEOUT_ACTION` | `exit` (exit 75, see "Exit codes" above) or `restart` (relaunch with a fresh login) when `mfa_exit_interval` expires after an approved push | `"exit"` |
| `restart_cap` | `IBC_RESTART_CAP` | Max consecutive relaunches that never reach READY (login frame timeout, transient login failure, logout, crash during login); then exit 70 | `3` |
| `time_zone` | `IBC_TIME_ZONE` | IANA zone name, e.g. `"Europe/Zurich"`, written to `jts.ini`'s `TimeZone`. Auto-detected from `TZ`, then `/etc/localtime` -- no setup needed in the common case; never overwrites an existing `TimeZone` line | auto-detected |
| `cold_restart_time` | `IBC_COLD_RESTART_TIME` | TWS and Gateway. `"HH:MM"` 24-hour local time; every Sunday, ibcontroller closes the instance tidily and relaunches with a full fresh login, forcing IBKR's weekly Sunday 01:00 US/Eastern token-invalidation reauth -- not a GUI setting, see "Scheduled shutdown" below | `None` |
| `closedown_at` | `IBC_CLOSEDOWN_AT` | TWS and Gateway. `"HH:MM"` (daily) or `"<Weekday> HH:MM"` (weekly); closes the instance tidily at that time, no relaunch -- not a GUI setting, see "Scheduled shutdown" below | `None` |

#### `tws_version` auto-detection

When `tws_version` is unset, `launcher._detect_tws_version` scans `tws_path` for every
installed version (a directory with its own `jars/` subfolder) and picks the greatest
one — optionally narrowed to one update channel first, if `tws_channel` is set. A real
install can carry more than one version side by side, each on its own channel: e.g.
`IB Gateway 10.45` (channel `stable`) and `IB Gateway 10.50` (channel `latest`) installed
at once — `tws_channel = "stable"` picks `10.45`; leaving it unset picks `10.50`, the
greatest overall. The channel itself is read per-install from its own
`.install4j/i4jparams.conf`, not guessed from the version number.

TWS requests fall back to Gateway installs when `program = "tws"` and no TWS install matches — no
`Trader Workstation *` directory at all, or none on the requested `tws_channel` — the
Gateway installs (`IB Gateway *`) are used instead, launching the TWS front end
(`jclient.LoginFrame`) from the Gateway jars. `tws_channel` still applies to the
fallback pool strictly: a Gateway install on the *wrong* channel never satisfies a TWS
request (that raises a clear error instead, naming `tws_channel`). The reverse
(Gateway falling back to TWS installs) is deliberately not supported. Applies to a
pinned `tws_version` too — a pinned version absent from TWS installs resolves against
Gateway installs of the same version.

#### Scheduled shutdown: `cold_restart_time` / `closedown_at`

Unlike the `[ibkr]` settings (real Global Configuration GUI settings), these two aren't written to TWS/Gateway at all -- ibcontroller schedules
the action itself, ported from IBC's own `IbcTws.java` (the shared base class both
programs use, so both apply here too). If both are set, whichever occurs first wins; a
malformed value is logged and skipped rather than aborting the other one.

- `cold_restart_time` -- `"HH:MM"`, 24-hour, local time. Every **Sunday** at this time,
  ibcontroller closes the instance tidily and relaunches with a full fresh login forcing the weekly
 re-auth IBKR requires around Sunday 01:00 US/Eastern token invalidation.
- `closedown_at` -- `"HH:MM"` (every day) or `"<Weekday> HH:MM"` (one day a week,
  `Weekday` a full English name, `Monday`..`Sunday`). Closes the instance tidily at that
  time, with no relaunch -- you're responsible for restarting it yourself.

Both use the local system clock, not
converted to US/Eastern, so pick a local time that lands after the Sunday 01:00
US/Eastern invalidation window if that's the intent.

## Declarative configuration

Inside `ibcontroller.toml`, the `[ibkr]` table gives values to IBKR's own settings and
pop-ups, by name, and the environment can do the same as `IBKR_<NAME>` (it wins over the
file). The `IBKR_` prefix is reserved for ibcontroller: a variable that names no setting or
dialog is logged as a warning and ignored. Two table kinds describe entries the bundled catalog lacks: `[[setting]]` and
`[[dialog]]`. The catalog is `ibcontroller/data/catalog.toml`. Beyond that, **`labels.json`**
(window/button text) lets you shape ibcontroller without writing any Python. Each is covered
below; the full reference is in [docs/Configuration.md](./docs/Configuration.md).

### `labels.json` — window/button text

`{config_dir}/labels.json` (rename `labels.json.example` to activate) overrides one or
more fields of the bundled default, field by field — you only need to include what
you're changing, not the whole file. Use it when a TWS/Gateway release renames a button
or dialog title ibcontroller matches against.

A malformed file is rejected at startup (exit code 78) with a message naming the file and
the field: a string where a list is expected, an empty list of titles or buttons, or
invalid JSON. A misspelled key is
logged as a warning and ignored, so check the log if an override seems to have no effect.

`generic.dismiss_buttons` lists the buttons tried, in order, to close a pop-up no specific
handler recognises (default `OK`, `Close`, `Dismiss`).

Pop-ups that are always handled the same simple way (match a window, click a button) are
not in `labels.json`: they are entries of the bundled dialog catalog (`data/catalog.toml`).
Today those are the non-brokerage-account warning and the auto-restart confirmation, both
handled automatically; the password-expiry notice, blind-trading confirmation and the TWS
socket-port confirmation ship switched off; incoming connections and crypto order confirmation
default to `manual`, which leaves the dialog to you. Matching: windows by substring, controls by
whole label, case never matters; see [Matching](./docs/Configuration.md#matching). Switch an entry
with its name in `[ibkr]` and add your own with `[[dialog]]` in `ibcontroller.toml`. Some entries
have not been checked against a live window; the list is in
[docs/Upgrading.md](./docs/Upgrading.md#not-verified-live).

Login-outcome dialogs ("Login failed", "Unrecognized Username or Password", the connection
and too-many-attempts warnings) and the "Shutdown progress" / "Restart in progress" windows
are always handled first, before catalog entries, so a credential rejection still exits with
code 77 and a restart is still recognised as one.

### Global Configuration settings

Global Configuration settings (the "Configure" / "Settings" dialog inside Gateway/TWS) are
applied once, right after login. Each is an entry of the catalog with a name; a value in
`[ibkr]` (or `IBKR_<NAME>`) makes it apply, and a setting with no value is left as it is.
The value is checked at startup, a wrong one stops the run with an error naming the setting.

| Name | Value | Notes |
| --- | --- | --- |
| `auto_logoff_time` | `"hh:mm AM/PM"`, e.g. `"08:00 AM"` | Daily logoff time. |
| `auto_restart_time` | `"hh:mm AM/PM"`, e.g. `"08:00 AM"` | Daily restart time. Shares the "Lock and Exit" radio pair with `auto_logoff_time`: if you set both, `auto_restart_time` wins, as in IBC. |
| `read_only_api` | `true`/`false` | API/Settings "Read-Only API". |
| `socket_port` | number or text | API/Settings "Socket port". IBKR defaults: 7496 TWS live, 7497 TWS paper, 4001 Gateway live, 4002 Gateway paper. On TWS, changing it opens a confirmation dialog after OK, see `socket_port_confirmation`. |
| `master_api_client_id` | number or text | API/Settings "Master API client ID". |
| `send_market_data_in_lots_us_stocks` | `true`/`false` | API/Settings, lots for US stocks. Do not set `true` yet: it opens a confirmation window that is not handled and blocks the settings step. |
| `api_precautions_bypass_order_precautions` | `true`/`false` | API/Precautions: bypass the order precautions for API orders. |
| `api_precautions_bypass_bond_warning` | `true`/`false` | API/Precautions: bypass the bond warning for API orders. |
| `api_precautions_bypass_negative_yield_to_worst` | `true`/`false` | API/Precautions: bypass the negative yield to worst confirmation for API orders. |
| `api_precautions_bypass_called_bond_warning` | `true`/`false` | API/Precautions: bypass the called bond warning for API orders. |
| `api_precautions_bypass_same_action_pair_trade` | `true`/`false` | API/Precautions: bypass the "same action pair trade" warning for API orders. |
| `api_precautions_bypass_price_based_volatility` | `true`/`false` | API/Precautions: bypass the price-based volatility risk warning for API orders. |
| `api_precautions_bypass_redirect_order_warning` | `true`/`false` | API/Precautions: bypass the redirect order warning (stock orders) for API orders. |
| `api_precautions_bypass_no_overfill_protection` | `true`/`false` | API/Precautions: bypass the no overfill protection precaution for API orders. |
| `api_precautions_bypass_route_marketable_to_bbo` | `true`/`false` | API/Precautions: bypass the route marketable to BBO warning for API orders. Do not set `true` yet: it opens a confirmation window that is not handled and blocks the settings step. |

```toml
[ibkr]
read_only_api = false
auto_restart_time = "04:00 AM"
```

When no setting has a value (the default), the dialog is not opened. Only the TWS Mosaic
layout is supported: on TWS Classic no setting is applied and the attempt waits for
`mfa_timeout` (default 180s) before failing. Gateway is not affected. A setting that fails
(control not found) is logged and the next one still runs.

For a setting the catalog lacks, add a `[[setting]]` entry; it carries no value, give it one
in `[ibkr]` under its name:

```toml
[ibkr]
my_checkbox_setting = true

[[setting]]
name = "my_checkbox_setting"
tree_path = "API/Settings"                # Global Configuration's own tree, section by section
action = "toggle"                         # "toggle" | "type_text" | "type_text_near_label"
label = "Label of the checkbox"  # a literal label...
# label_ref = "my_label"                 # ...or a name from labels.json's settings.controls map
field_index = 0                           # only type_text_near_label: 0-based field below the label
```

A custom name must not be the name of a catalog entry or of a dialog.

Settings that moved or were removed since v0.1.x: see [docs/Upgrading.md](./docs/Upgrading.md).

## Logging

ibcontroller writes all of its log/trace files into one shared log directory
(resolved by `app_dirs.py`, or overridden with `IBC_APP_DIR` for
container mode). Every file is named with the `{instance}` name, so two instances
(e.g. `paper` and `live`) can run in parallel in the same directory without ever
interleaving — matched by `tail -f` on the right filename, no subdirectory per
instance.

**`IBC_LOG_SINK`** (`"std"`/`"file"`, default `"std"`) controls where
ibcontroller's own log and TWS/Gateway's own stdout/stderr go — console
(`"std"`) or file (`"file"`), exclusive, not both. This is the setting that
matters for Docker: with the default `"std"`, both streams show up in
`docker logs` and no file is written inside the container. It does **not**
cover the Java agent log or the wire trace below — those two are always file,
regardless of `log_sink`, the same way `trace_enabled`'s files are always
file when it's on: the Java agent log is JVM-side diagnostic detail (not
something you'd want interleaved into `docker logs` at `debug`), and the wire
trace is deliberately verbose NDJSON meant to be tailed, not read as console
scrollback.

| File | Layer | Enabled by | Level |
| --- | --- | --- | --- |
| `ibcontroller-{instance}.log` | ibcontroller app control flow | `log_sink=file` (else console) | `log_level` (default `info`) |
| `gateway-{instance}.log` | TWS/Gateway own stdout/stderr | `log_sink=file` (else console) | TWS/Gateway's own |
| `ibcontroller-java-agent-{instance}.log` (see rotation note below) | Java agent (in-process JUL) | always file, not affected by `log_sink` | `log_level` (see mapping below) |
| `cmd-{instance}.jsonl` | raw wire: commands sent + results, NDJSON | `trace_enabled`; always file, not affected by `log_sink` | always (DEBUG emit, gated separately) |
| `events-{instance}.jsonl` | raw wire: every event message received, NDJSON | `trace_enabled`; always file, not affected by `log_sink` | always (DEBUG emit, gated separately) |

**Rotation** (`IBC_LOG_MAX_BYTES`/`IBC_LOG_BACKUP_COUNT`, default 10 MiB x 5
backups, **on by default**) applies to every file above in file mode. Set
`IBC_LOG_MAX_BYTES=0` to disable it (unbounded files). Python's files keep
their usual name active, with `.1`/`.2`/... as old backups. The Java agent log
is the opposite: once rotation is on, the active file is
`ibcontroller-java-agent-{instance}.log.0`, not the unsuffixed name.

### Log levels

`IBC_LOG_LEVEL` (`debug`/`info`/`warning`/`error`, default `info`) controls
both the Python app log and (via `-Dibcontroller.log.level`) the Java agent log:

| `IBC_LOG_LEVEL` | Python `logging` | Java JUL |
| --- | --- | --- |
| `debug` | `DEBUG` | `FINE` |
| `info` | `INFO` | `INFO` |
| `warning` | `WARNING` | `WARNING` |
| `error` | `ERROR` | `SEVERE` |

The default `info` is quiet — it records the *actions* taken and problems found,
not the raw event stream. `debug` additionally logs every event message that
arrives on the Python side (below).

`trace_enabled` is a separate, independent toggle: it turns on the structured
raw-wire files and is not coupled to `log_level` — you can trace at `info`, or
read the human-readable arrival lines at `debug` without writing the NDJSON files,
or both.

### What gets logged, per stream

- **`ibcontroller-{instance}.log`** — only written when `log_sink=file`; with
  the default `log_sink=std` this same content goes to the console instead, no
  file is created. The app's own control flow: launching an
  instance, each login state transition (credentials submitted, 2FA in progress, login
  completed/skipped on restart), declarative settings applied (and which entries were
  skipped), and every recogniser action (e.g. `dismissed non-brokerage account
  warning`). Credential *values* are never logged: `Config.userid`/`password` are
  `typed_settings.types.Secret`-wrapped, and a `Secret`'s `__str__`/`__repr__` both
  mask the real value (`*******`), so even a careless `logger.info("login as %s",
  password)` stays safe. At `debug` this same file gets one line per arriving
  event message (IBC's always-on
  `logWindow` posture, mapped to our DEBUG level here) — e.g. `event: window_opened
  class=ibgateway.ax title='IBKR Gateway' seq=1`. Event content is window metadata
  only, never field values.
- **`gateway-{instance}.log`** — same `log_sink=file`/`std` split as above; a plain
  drain of TWS/Gateway's own stdout/stderr, captured for the process's whole life
  either way. Used to diagnose issues *inside* Gateway itself (JWPRINT prints, JVM
  warnings, the occasional `InaccessibleObjectException` and similar). Level/content
  are entirely TWS/Gateway's own; ibcontroller only pipes it to a file or the console.
- **`ibcontroller-java-agent-{instance}.log`** — **always a file, regardless of
  `log_sink`** — the Java agent's `java.util.logging` output, from the JVM that
  actually hosts TWS/Gateway, never routed to the console. At `debug` this is the
  noisiest stream by far (every processed command, logged from inside the JVM
  itself); console output at that level would drown out ibcontroller's own log
  lines, so it stays file-only the same way the wire trace does. It logs connection
  accepts/disconnects, each processed command's name + target/label/path/window_id
  (**never a value** — `set_text`/`set_checkbox` values and therefore credentials can
  never land here, mirroring Python's `Secret` redaction), window register/unregister,
  and an event-queue overflow warning. Its level follows `log_level` via the table
  above — note `debug` maps to JUL `FINE`.
- **`cmd-{instance}.jsonl` / `events-{instance}.jsonl`** — the raw wire protocol,
  one JSON object per line, no formatter prefix (pure NDJSON), primarily for
  debugging what was actually sent and received at the socket boundary.
  `cmd-{instance}.jsonl` records each command as sent, then its result or error,
  correlated by a `seq`. `events-{instance}.jsonl` mirrors **every** event message the
  agent pushes, in order. Files are truncated at startup (per-session only) and are
  deliberately a separate, opt-in stream — they are verbose by design and not meant
  for steady-state operation.

### Ordering / correctness notes

- File writes happen on dedicated listener threads (Python side) and a background
  writer thread (Java side); a slow log volume never blocks the control loop or the
  AWT event dispatch.
- All five files carry the instance name and share one flat directory, so two
  instances (e.g. `paper` and `live`) can run in parallel and each tail its own files
  without interleaving, even if copied or globbed out of their directory.

## Finding the TWS / Gateway installation

ibcontroller does not install anything: it launches the TWS or Gateway you already
installed with IBKR's own installer, using that install's jars and bundled JRE. It
resolves the installation in three steps.

1. **Install root** (`tws_path`). Unless set, it defaults to:

   | OS | Default root |
   | --- | --- |
   | macOS | `~/Applications` |
   | Linux | `~/Jts` |

2. **Version** (`tws_version`). A pinned `tws_version` is used as-is. Otherwise
   ibcontroller scans the root, picks the greatest installed version and logs the
   choice; `tws_channel` narrows the scan first. See "`tws_version` auto-detection"
   above.

3. **Install directory.** Version and `program` select the directory below the root:

   | OS | Gateway | TWS |
   | --- | --- | --- |
   | macOS | `IB Gateway <version>/` | `Trader Workstation <version>/` |
   | Linux | `ibgateway/<version>/` | `<version>/` |

   A directory counts as an installation only if it has a `jars/` subfolder. The
   classpath is built from those jars plus the install's `.install4j/i4jruntime.jar`,
   and the JVM options come from its `ibgateway.vmoptions` / `tws.vmoptions`.

If nothing matches, ibcontroller exits with an error naming `tws_path` and
`tws_channel`. A `program = "tws"` request with no TWS install falls back to a
Gateway install; the reverse does not (details above).

Settings (`tws_settings_path`) are separate from the install root: each instance
defaults to its own `~/Jts/<instance>`, so `paper` and `live` do not share state.

## Exit codes

`ibcontroller run` exits with a [BSD sysexits](https://man.freebsd.org/cgi/man.cgi?query=sysexits)
code, grouped by what a supervisor (a container's `restart:` policy, systemd's
`Restart=`) should do about it. The specific cause is always in the logs and in the
`stopped: <CAUSE>` line.

| Code | Meaning | Supervisor action |
| --- | --- | --- |
| `0` | Intentional stop (Ctrl-C, `closedown_at`, Gateway/TWS closed normally, e.g. File>Close, or this session yielded to another via `existing_session_action`: `stopped: SESSION_CEDED`) | Do not restart |
| `1` | Unhandled exception (a bug) | Restart, report |
| `2` | CLI usage error | Fix the command |
| `78` (`EX_CONFIG`) | Deployment error (bad config, install not found) | Do not retry |
| `77` (`EX_NOPERM`) | Credentials rejected | Do not retry (lockout risk) |
| `76` (`EX_PROTOCOL`) | A dialog `existing_session_action` rules out (Trading Login Handoff with `secondary`/`primaryoverride`) | Do not retry |
| `75` (`EX_TEMPFAIL`) | Login did not complete after 2FA, `mfa_timeout_action=exit` | Retry per policy |
| `70` (`EX_SOFTWARE`) | `restart_cap` consecutive relaunches never reached READY | Do not retry |
| `69` (`EX_UNAVAILABLE`) | Transient runtime failure (process crashed or killed, connection lost, JVM exited before becoming ready) | Retry |

`70`/`76`/`77`/`78` work with systemd's `RestartPreventExitStatus=`.

Some login-blocking dialogs IB reports as a server-side condition -- not a credential
rejection -- never reach this table at all: a "Login failed"/"Login Error"/"not currently available" dialog, or a
Gateway "Connection to server failed" reason other than a known credential/account one
(e.g. a stale restart token), make ibcontroller relaunch in-process with a full fresh
login, the same way a scheduled `cold_restart_time` does -- the container
itself does not exit for these, until `restart_cap` consecutive relaunches never reach READY
(exit 70).

## Stopping under Docker

On SIGTERM (`docker stop`, Ctrl-C) a logged-in instance closes through File > Exit/Close so
TWS/Gateway can save its session and upload settings. Measured over 88 shutdowns: mean 1.3 s,
p99 4.3 s, max 4.9 s. A slow path (a dialog open, a stuck menu) can take longer: the menu retry
waits up to 5 s, the exit up to 8 s, then SIGTERM gets 5 s. Docker sends SIGKILL after 10 s by
default, which loses the graceful close. Set `stop_grace_period: 30s` (Compose) or
`docker stop -t 30` to keep it.

## License

```text

   Copyright 2023 gnzsnz

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
```
