Skip to main content

One Paper Gateway, Two Traders

Infrastructure
Deploying a paper-trading app to four home-lab containers with Pulumi and Ansible. The hard constraint was one broker session per login, so the Gateway got a machine of its own, both traders reach it through an SSH tunnel that can do exactly one thing, and each trader learned to ignore the other’s orders.
Author

Benedict Thekkel

Published

November 8, 2026

The app is a Django REST + React + Celery dashboard with a separate trader process that talks to Interactive Brokers (IBKR) through IB Gateway, the headless version of their trading terminal. It trades a paper account only. Every check below was run against paper, on a home lab, with no real money anywhere near it.

Until this week the whole thing ran on my dev machine. The goal was a deployed stack that runs all the time, so the stored stock data builds up, while dev keeps trading on the same paper account. One rule from IBKR shaped every decision after it: one session per username.


The constraint: one login, one session

IBKR allows one logged-in session per username. The Gateway container is set to EXISTING_SESSION_DETECTED_ACTION=primary, which logs off any other session. So if dev and the deployed stack each ran a Gateway, starting dev would silently log the deployed one off.

The way out is that one Gateway accepts up to 32 API clients, each with its own client ID. So there is one Gateway, and two traders connect to it as clients:

Deployed trader Dev trader
Client ID 1 2
Peer client IDs (ignored) 2 1
Market data lines 60 30
Database and Redis its own its own
Background stock loading on off

The dev side also sets IB_GATEWAY_SHARED=true, and with that set just gateway-up refuses to start a local Gateway. The mistake that would log the shared session off now needs someone to edit a file first.


Four machines from Pulumi, configured by Ansible

The Gateway got its own machine, so there are four LXC containers on one Proxmox node:

Machine Cores RAM Disk Runs
ibkr-obs 2 4 GB 100 GB Grafana, Prometheus, Loki
ibkr-db 2 2 GB 60 GB Postgres 16
ibkr-gateway 2 2 GB 16 GB IB Gateway, and nothing else
ibkr-app 2 4 GB 40 GB the Compose stack: nginx, gunicorn, Celery, trader, Redis, tunnel

Pulumi (Python, pulumi_proxmoxve) creates them, copying the container pattern from another project of mine. A few rules carried over because they had already saved me once:

  • A local file:// state backend, set per command through PULUMI_BACKEND_URL. Never pulumi login: it is global, and the other project’s recipes depend on it.
  • protect=True and retain_on_delete=True on every container, and no destroy recipe.
  • No addresses in tracked files. The stack config with the IPs is git-ignored, with a tracked .example next to it.

The first preview said + 5 to create (the stack and four containers). pulumi up created them in 17 s. The second preview said 5 unchanged, and so did the other project’s stack. That second preview is the real test.

Ansible then configures each machine: Postgres with a pg_hba that admits only the app host, Docker and the Compose plugin, the Gateway machine’s SSH rules and firewall, and Alloy on all four for metrics and logs. Secrets come from an Ansible Vault. The IBKR login sits in a second Vault file that is git-ignored, because the repo rule is that broker credentials are never committed, not even encrypted.


Why the Gateway gets a machine of its own

The deployed and dev traders reach one paper Gateway through restricted SSH tunnels

Three reasons, in order of how much they mattered:

  1. Deploying or rebooting ibkr-app no longer drops dev’s connection. If the Gateway lived on the app host, every deploy would take dev down too.
  2. A Gateway problem cannot take memory from the app. The Gateway is a Java process, and its 2 GB is a starting guess to check in Grafana after a week.
  3. The machine that holds the broker login runs nothing else. That makes “who can reach the API port” a short question to answer.

The TWS API has no login, so the network is the authentication

The Gateway’s API (the TWS API) has no authentication and no encryption. Anything that can open a TCP connection to it can place orders. So the whole security design is about who can reach that port.

On ibkr-gateway the API is published on 127.0.0.1:4002 only. It is never on the LAN. From the dev machine, nc -z to port 4002 on both ibkr-gateway and ibkr-app fails.

On ibkr-app the problem is the other containers. In the old dev Compose file every container could reach the Gateway, including the Celery workers that download data from outside. A compromised worker could have traded. The prod file has a Docker network called gateway with internal: true and exactly two members, the trader and the tunnel. Everything else reaches IBKR only by sending a command to the trader through Redis.

That was checked from inside the running containers, not just in the YAML. From web, celery_worker and nginx, the name gateway-tunnel does not resolve. From web and celery_stocks, a connection to the tunnel’s IP on 4002 times out. From trader, the name resolves. A test (test_only_the_trader_reaches_the_tunnel) pins the network membership so a later edit cannot quietly widen it.

Two smaller rules in the same file: no env_file (every service lists its variables, so a local run cannot pull the dev .env into prod containers), and ${VAR:?} on SECRET_KEY, ALLOWED_HOSTS and DATABASE_URL, so docker compose config fails without them.


An SSH key that can open one port and nothing else

Both traders reach the Gateway the same way: an SSH local forward as a user called gateway-tunnel. On the deployed side it is an autossh container. On dev it is a just gateway-tunnel recipe. Each side has its own key, so either can be revoked alone.

Each line in that user’s authorized_keys starts like this:

restrict,port-forwarding,permitopen="127.0.0.1:4002" ssh-ed25519 AAAA... deploy

And sshd_config repeats the limits for the user, so a wrong key line cannot loosen them:

Match User gateway-tunnel
    AllowTcpForwarding local
    PermitOpen 127.0.0.1:4002
    PermitTTY no
    X11Forwarding no
    ForceCommand /usr/sbin/nologin

restrict turns off everything (PTY, agent forwarding, X11, user rc files), and port-forwarding turns back on the one thing needed. permitopen limits that to a single destination. Password login is off for every user on the machine.

The checks, run with each real key:

  • ssh gateway-tunnel@ibkr-gateway id returns “This account is currently not available”. No shell.
  • -L ...:127.0.0.1:22 is refused by the server: “administratively prohibited”.
  • -L ...:127.0.0.1:4002 is accepted.
  • sshd -T for the user shows allowtcpforwarding local, permitopen 127.0.0.1:4002, permittty no and forcecommand /usr/sbin/nologin.
  • From ibkr-db, TCP to port 22 on ibkr-gateway times out, because nftables lets SSH in from the two trader hosts only.

One nftables detail worth knowing: the role replaces only its own table. It never runs flush ruleset, which would also delete the tables Docker writes for its own networking.


Teaching each trader to ignore the other

The trader was written on the assumption that it was the only client on the account. Reconciliation compares IBKR’s open orders with its own database, and any order it does not know becomes an unknown_broker_order event, which sends an alert email. With a peer on the same account, every dev order would page the deployed stack, and the other way round.

The fix is a list of peer client IDs. Reconciliation drops orders by order.clientId and fills by execution.clientId before matching, with one debug line per pass. The order event stream skips a peer’s status, execution and commission events the same way. Orders from any other client still get reported: client 0 (an order placed in the desktop terminal) and client 98 (scripts).

Market data needed a budget. Each trader had a hard cap of 90 lines out of IBKR’s 100 per user, so two of them could ask for 180. The cap is now a setting, split 60 for deploy and 30 for dev.

Some things are shared on purpose, because the account is for testing, and they are written down rather than fixed:

  • cancel_all uses IBKR’s global cancel, which cancels the peer’s orders too.
  • The daily loss limit reads the whole account’s P&L, so a dev loss can halt deploy.
  • READ_ONLY_API is per Gateway, so dev cannot be read-only while deploy trades.

The live check, with both traders connected at the same time: a buy of 1 share of F at $0.50 from dev, far from the market, submitted and then cancelled. On deploy, that produced 0 unknown_broker_order events and 0 alert emails. (The first attempt, 1 share of AAPL at $1, never reached IBKR: the trader’s own risk check rejected it for going over the maximum position. That is the risk check working.)


Idempotence was most of the work

The measurable goal was that a second pulumi preview and a second just deploy both report no changes. Getting Ansible there took more fixes than the deploy itself, and each one was a small lie about state:

Symptom Cause Fix
A setlocale warning on every remote command, and synchronize reporting a change every run My workstation forwards LC_ALL over SSH, and the containers lacked that locale The docker role generates the locale
docker compose pull reported a change every run It prints “Pulled” even when nothing changed Compare the image ID before and after
The observability stack restarted every run Git checkout rewrites modification times, and rsync compared those rsync compares checksums
The app was unpacked and rebuilt every run No record of what was deployed A DEPLOYED file with the commit; same commit skips the build
A change reported after every reboot Proxmox rewrites /etc/resolv.conf at boot Stop managing that file; Pulumi sets DNS

After those, the second just deploy gives changed=0 on all four machines. A full deploy of a new commit took 3 min 7 s.


The cutover, and what it found

The cutover was a written list: halt trading on dev, cancel open orders, turn off strategies, stop the dev trader and its Gateway, dump the dev database, restore it on ibkr-db, run migrations, confirm deploy reads halted, then start the Gateway on its own machine and watch reconciliation.

The dump was 3 MB. After the restore the counts matched dev exactly: 53 orders, 6 fills, 195 audit events and 11,767 stocks, still halted. The deployed trader connected through the tunnel in about 45 s.

Then four things went wrong, which is why the cutover was done halted:

  • Reconciliation never finished. With the Gateway in read-only API mode, IBKR refuses the open-orders request (error 321), so every pass timed out and the trader sat in “Reconciling”. Read-only had to be turned off, as it already was on dev.
  • The Gateway first started with an empty login. The dev .env held IBKR_USERNAME=${PAPER_LOGIN}, and the script that copied it into the Vault did not expand the variable. The Vault held the literal text.
  • Every web restart gave 502s until nginx restarted. nginx resolves a proxy_pass hostname once at startup and keeps the old container IP. Using Docker’s resolver with a variable in proxy_pass makes it look up web on each request; after web moved IP, nginx followed within 1 s.
  • The trader logged the full paper account number. ib_async logs portfolio items and orders at INFO, and those lines now went to Loki. A log filter now masks account IDs on every handler.

The last one is the kind of thing a deployment surfaces that dev never does: the logs existed before, but nobody was shipping them anywhere.


Failure drills

Each drill was run on the deployed stack, and the trader container was never restarted by any of them:

Drill Result
Restart the Gateway container “reconnecting”, then “connected” in about 16 s
Restart the tunnel container disconnected at 15:35:42, connected and reconciled at 15:35:44
Restart sshd on the Gateway host and kill the tunnel session autossh reconnected in about 3 s, 0 container restarts
Restart Postgres one burst of pool warnings, then writes resumed
Reboot all four machines all back within about 20 s; halt switch and risk limits intact
Stop the trader for over 60 s “Trader is down”, then “Trader is back” alerts sent
just deploy of a new commit deployed trader restarts and reconciles; dev stays connected

The Gateway also restarts itself every night. Both traders disconnect at 23:45 UTC, reconnect by 00:04, and reconcile with 0 corrections.

Backups are a nightly pg_dump from a systemd timer, kept 14 days. A dump restored into a scratch database gave the same 53 order rows as live. A backup you have not restored is a hope, not a backup.


What this is not

Paper only, by design. Before any live account, each side needs its own Gateway and its own login, because READ_ONLY_API, global cancel and the daily loss limit are all shared today. The dashboard runs on plain HTTP on the LAN, has no roles (any login can trade paper), and sign-up is off. Prometheus and Loki answer on the LAN without auth.

Outbound traffic from the Gateway machine is not pinned. Inbound is locked down, but IBKR’s servers are not a stable list of addresses, and apt and image pulls need HTTPS out.

Two checks are weaker than they look. An order from a third client (a script on client 98) never reached the broker, because IBKR held it with warning 2139, so the “other clients are still reported” rule is proven by simulated tests only. And the dev tunnel dropping and reopening was checked with a fake ssh, not a live drop. It all runs on one Proxmox node.


Takeaway

Decision Why Evidence
One Gateway on its own machine One session per login; deploys must not drop dev Both traders connected at once; dev stayed up through a deploy
An internal Docker network with two members The TWS API has no auth Other containers cannot resolve or reach the tunnel
A tunnel user limited to one forward Revocable per key, no shell “not available” for a shell, “administratively prohibited” for port 22
Peer client IDs and a line budget Two traders on one account 0 events and 0 emails from a dev order on deploy
Halted cutover with a written list Four surprises, none of them could trade Counts matched; reconciled with 0 corrections
Second run must change nothing Drift you cannot see is drift you cannot trust changed=0 on all four; 5 unchanged in Pulumi

The pattern I would reuse anywhere: when a service has no authentication of its own, do not bolt one on. Make the network and the SSH layer the authentication, then test each refusal from the machine that should be refused.


Back to top