GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - medovarszki/ibkrfacade: Interactive Brokers API wrapper and trading toolbox

BranchesTags
Open more actions menu

Latest commit

 

History

56 Commits
56 Commits

Folders and files

NameName
Last commit message
Last commit date
docs
docs
 
 
lib
lib
 
 
scripts
scripts
 
 
src
src
 
 
.dockerignore
.dockerignore
 
 
.env.example
.env.example
 
 
.gitignore
.gitignore
 
 
Dockerfile
Dockerfile
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
docker-compose.expose.yml
docker-compose.expose.yml
 
 
docker-compose.host-tws.yml
docker-compose.host-tws.yml
 
 
docker-compose.yml
docker-compose.yml
 
 
pom.xml
pom.xml
 
 

Repository files navigation

IBKR Facade

Interactive Brokers API wrapper and trading toolbox

This project is built around the Interactive Brokers TWS API for Java. With a running TWS or IB Gateway it works as a REST gateway to the market, a market data source for time series analysis (Redis TimeSeries) or a trading bot framework. It's based on Spring Boot 4 and Java 21+.

It is designed to be the broker layer of an agent based system: an internal service, reachable only on a private Docker network, in front of a containerized IB Gateway (paper account by default).

In this project you'll find:

  • The TWS API exposed to a REST API (OpenAPI spec, Swagger UI at /ibkr/swagger-ui/index.html)
    • instrument search, contract details, option chain
    • options of a VIX future with conids, live quotes and the IBKR model greeks
    • market data subscription and latest prices (with sizes, volume, open interest, previous close), historical OHLCV bars
    • futures chain, calendar spread quotes (from the legs and from the exchange listed spread)
    • account summary (NAV, cash, buying power, margin), positions with market value and P&L
    • idempotent order placement, order status with fills and commissions, cancellation
    • news providers, headlines and articles (if the account has news subscriptions)
  • Safety by default: no order on a live account unless explicitly allowed, no order without a recent market price, optional read / write API tokens, sample strategies disabled
  • Market data streamed into Redis TimeSeries
  • Docker image and a Docker Compose stack with IB Gateway (paper, automatic login and daily restart by IBC) and Redis 8
  • Structured JSON logs with trace id propagation, health endpoint with the TWS connection state

Quick start with Docker Compose (paper account)

Prerequisites: Docker with Compose v2, an IBKR account with a paper trading user.

cp .env.example .env
# edit .env: TWS_USERID / TWS_PASSWORD of the paper user, REDIS_PASSWORD,
# IBKR_SECURITY_READ_TOKEN / IBKR_SECURITY_WRITE_TOKEN (eg. openssl rand -hex 32)
docker compose up -d --build
docker compose logs -f ibkrfacade

The stack:

Service Image Notes
ib-gateway ghcr.io/gnzsnz/ib-gateway:10.50.1f IB Gateway + IBC, TRADING_MODE=paper, daily restart (AUTO_RESTART_TIME), API on ib-gateway:4004 (paper)
redis redis:8.8.3 Redis 8 has RedisTimeSeries built in, password protected, persistent volume
ibkrfacade built from Dockerfile REST API on ibkrfacade:8082/ibkr, non-root, health check

Nothing is published to the host: the services share the internal ibkr-backend network (no internet access), only the gateway has an extra network to reach the IB servers. Other containers (eg. an MCP server) join the ibkr-backend network and call http://ibkrfacade:8082/ibkr.

To call the API from the host during development, publish the REST port on 127.0.0.1:

docker compose -f docker-compose.yml -f docker-compose.expose.yml up -d
curl -H "Authorization: Bearer $IBKR_SECURITY_READ_TOKEN" http://localhost:8082/ibkr/account/summary
curl http://localhost:8082/ibkr/actuator/health

Using a TWS / IB Gateway running on the host

Instead of the ib-gateway container the facade can connect to a TWS (or IB Gateway) running on the docker host, eg. the desktop TWS during development. The docker-compose.host-tws.yml override doesn't start ib-gateway and points the facade to host.docker.internal:7497 (paper TWS; live: 7496, IB Gateway: 4002 / 4001, set HOST_TWS_PORT). The internal network can't reach the host, so the facade joins an extra network with a fixed address (HOST_TWS_CLIENT_IP, default 172.31.250.10).

The facade reaches the host through the gateway of this network (host.docker.internal = 172.31.250.1, see HOST_TWS_GATEWAY), so the connection always comes from 172.31.250.10. That is the address TWS and the firewall see, not the docker host address (172.17.0.1).

Setup on the host:

  1. TWS: File > Global Configuration > API > Settings
    • check Enable ActiveX and Socket Clients, Socket port 7497 (paper)
    • uncheck Allow connections from localhost only
    • add 172.31.250.10 to the Trusted IPs (otherwise TWS asks to accept every connection)
  2. Firewall: if the host drops incoming traffic (eg. ufw with the default deny policy, the connection times out and [UFW BLOCK] ... DPT=7497 shows up in journalctl -k), allow only the facade to reach the API port:
    sudo ufw allow from 172.31.250.10 to any port 7497 proto tcp comment 'ibkrfacade -> TWS'

Troubleshooting (the tws component of /actuator/health stays DOWN):

  • Test the TCP connection from the container: docker exec ibkrfacade-ibkrfacade-1 bash -c '</dev/tcp/host.docker.internal/7497' && echo OK. A timeout means the packets don't get through. If the TCP connection works but the API doesn't, check the TWS settings above.
  • Firewall: journalctl -k | grep 'DPT=7497' shows the blocked packets with their real source address.
  • Duplicate subnet: if Docker stops while the stack is starting, a bridge can be left behind with the same subnet. The host then sends the TWS replies to that dead bridge: TWS accepts the packets, but the container gets a timeout. ip -4 route | grep 172.31.250 must list exactly one route. Delete the extra bridge, which isn't listed in docker network ls and is usually linkdown: sudo ip link delete br-<id>.
docker compose -f docker-compose.yml -f docker-compose.host-tws.yml -f docker-compose.expose.yml up -d --build

To make it the default, set COMPOSE_FILE in .env (see .env.example), then a plain docker compose up -d is enough. TWS_USERID / TWS_PASSWORD are still required by the base file, but unused in this mode: any placeholder will do.

The facade connects automatically when the gateway is ready, and reconnects after the daily restart. Secrets are only read from the environment (.env is git-ignored), nothing is stored in the image. For the gateway password you can also use Docker secrets (TWS_PASSWORD_FILE), see the ib-gateway image docs.

Paper accounts often have no live market data. Share the subscriptions of the live account with the paper account (how to), or set IBKR_MARKET_DATA_TYPE=3 for delayed data.

Configuration

Every property can be set through environment variables (Spring relaxed binding). The most important ones:

Environment variable Default Description
IBKR_TWS_HOST / IBKR_TWS_PORT localhost / 4002 TWS / IB Gateway API endpoint (compose: ib-gateway / 4004)
IBKR_TWS_CLIENT_ID 1 API client id, unique per gateway
IBKR_ALLOW_LIVE false Orders are rejected (403 LIVE_TRADING_DISABLED) on a live account unless true
IBKR_STRATEGIES_ENABLED false Loads the sample strategies (SampleSaver, TrendTradingStrategy)
IBKR_MARKET_DATA_TYPE 1 1 live, 2 frozen, 3 delayed, 4 delayed frozen
IBKR_PRICE_STALE_AFTER IBKR_ORDER_MAX_QUOTE_AGE GET /price reports stale: true if the latest bid/ask is older than this
IBKR_PRICE_QUOTE_WAIT 3s How long GET /price waits for the first quote of a not yet subscribed instrument
IBKR_SPREAD_MAX_SUBSCRIPTIONS 10 Market data subscriptions kept for exchange listed spreads (GET /spread)
IBKR_OPTION_MAX_SUBSCRIPTIONS 60 Option market data subscriptions kept by GET /options/chain, the least recently requested chain is cancelled first
IBKR_OPTION_CHAIN_CACHE_TTL 12h How long the option contracts of an expiration are cached by GET /options/chain
IBKR_ORDER_MAX_QUOTE_AGE 15m An order needs a bid/ask not older than this (0 disables the age check)
IBKR_ORDER_QUOTE_WAIT 3s How long to wait for the first quote of a not yet subscribed instrument
IBKR_ORDER_IDEMPOTENCY_TTL 30d How long a client_order_id is kept in Redis
IBKR_SECURITY_ENABLED false (compose: true) Bearer token authentication
IBKR_SECURITY_READ_TOKEN / IBKR_SECURITY_WRITE_TOKEN Read-only and read-write tokens (min. 16 characters)
REDIS_HOST / REDIS_PORT / REDIS_PASSWORD localhost / 6379 / Redis connection
REDIS_DEFAULT_RETENTION 3600000 Retention of the price time series (ms)
SERVER_PORT 8082 REST port (context path /ibkr)
LOGGING_STRUCTURED_FORMAT_CONSOLE (image: ecs) JSON logs: ecs, logstash or gelf

See application.properties for the full list.

REST API

All paths are relative to /ibkr. Errors are RFC 9457 problem details with a machine readable code:

{"status": 422, "title": "Unprocessable Content", "code": "MARKET_DATA_UNAVAILABLE", "detail": "No market price (bid/ask) for conid 265598, no order is placed"}
Method Path Description
GET /search?query= Instrument search
GET /contract/{conid} Contract details (unknown conids are resolved through TWS, 404 if there's no such contract)
GET /contract/{conid}/session?hours=liquid Market open / next_open / next_close, see Trading session
GET /subscribe/{conid} Market data subscription (stream into Redis)
GET /price/{conid}?max_age= Latest bid / ask / last with timestamps and freshness, see Prices
GET /prices?conids=1,2,3 Latest prices of several instruments (at most 100) in one request
GET /futures/chain?symbol=VIX&exchange=CFE&trading_class=VX&include_expired=false Futures of an underlying ordered by expiration, see Futures
GET /spread?near={conid}&far={conid} Calendar spread of two futures, see Futures
GET /history/{conid}?duration=1 M&barSize=1 day&whatToShow=TRADES&useRth=true OHLCV bars, times in the exchange time zone
GET /options/chain?future_conid=&product=VIX&strike_range=0.25&max_strikes=15&rights=C,P Options expiring with a VIX future, with conids, quotes and model greeks, see Options
GET /optionChain/{conid} Expirations and strikes of the options of an underlying (no conids, no prices)
GET /account/summary?account= NAV, cash, available funds, buying power, margin requirements, currency, timestamp (query), updated_at (last update from TWS)
GET /positions Positions with average cost, market price, market value, unrealized / realized P&L
POST /order Place an order (write token)
GET /orders, /orders?client_order_id=, /orders/active, /orders/{orderId} Order status, filled quantity, average fill price, commission, executions
DELETE /orders/{orderId} Cancel an order (write token)
GET /news/providers, /news/{conid}, /news/article/{provider}/{articleId} News
GET /actuator/health Health including the TWS connection (tws) and Redis, always public

Prices

{"conid": 265598, "bid": 345.0, "ask": 345.01, "last": 345.0016, "quote_time": "2026-10-15T15:22:17Z",
 "quote_age_seconds": 4, "stale": false, "market_data_type": "LIVE", "subscribed": true, "stream_error": null, ...}
  • The prices come from the Redis time series, they may be old (eg. from before a restart of the facade, or outside of the trading hours). Check stale: it's true if there is no bid/ask, or the latest one is older than IBKR_PRICE_STALE_AFTER (default: IBKR_ORDER_MAX_QUOTE_AGE, 15m). quote_age_seconds is the age of quote_time.
  • Without a market data subscription the instrument is subscribed automatically, and the request waits at most IBKR_PRICE_QUOTE_WAIT (3s) for the first quote. Without a TWS connection the cached price is returned.
  • max_age (seconds): an older price (or no price) is rejected with 422 STALE_MARKET_DATA.
  • market_data_type: LIVE, FROZEN, DELAYED or DELAYED_FROZEN, as reported by TWS for the subscription. A paper account without shared live market data gets DELAYED data.
  • An unknown conid is 404 CONTRACT_NOT_FOUND.
  • bid_size, ask_size, last_size, volume, open_interest, close (previous close, for futures the previous settlement price), open, high, low are the latest values sent by TWS. They are kept in memory only: null after a restart of the facade until TWS sends them again. mid and spread (ask - bid) are computed.
  • Indices have no bid/ask: their quote_basis is LAST, so quote_time, quote_age_seconds and stale are based on the latest value of the index (last).
  • GET /prices?conids= returns the same for several instruments in the order of the conids. The ones without subscription are subscribed, the request waits at most IBKR_PRICE_QUOTE_WAIT altogether for their first quotes. Every subscription uses a market data line of the account (100 by default).

Futures and calendar spreads

GET /futures/chain?symbol=VIX&exchange=CFE&trading_class=VX lists the futures of an underlying ordered by expiration (last_trade_date, contract_month, real_expiration_date, local_symbol, multiplier, min_tick), underlying_conid is the conid of the underlying index. Without trading_class every future of the symbol is returned: for VIX VX is the monthly contract, VX01..VX53 are the weekly ones. With include_expired=true the expired contracts are listed too (TWS knows the ones expired in the last two years); GET /history/{conid} works for them, pass an endDateTime not later than the expiration.

GET /spread?near={conid}&far={conid} is the calendar spread of two futures of the same underlying, quoted as far minus near (buying the spread = buying the far, selling the near leg):

{"near_conid": 1001, "far_conid": 1002, "near": {"bid": 17.05, "ask": 17.1, "...": "..."}, "far": {"bid": 18.35, "ask": 18.4, "...": "..."},
 "synthetic": {"bid": 1.25, "ask": 1.35, "mid": 1.3, "last": 1.25, "close": 1.2, "stale": false},
 "native": {"bid": 1.29, "ask": 1.31, "mid": 1.3, "bid_size": 85, "ask_size": 60, "stale": false, "subscribed": true, "stream_error": null, "...": "..."}}
  • synthetic is computed from the legs: ask = far ask - near bid (the price the spread can be bought at with two orders), bid = far bid - near ask, close = the spread of the previous settlement prices.
  • native is the quote of the exchange listed spread (a TWS combo: BUY 1 far, SELL 1 near), usually tighter than the synthetic one. Its prices may be zero or negative. The quote is kept in memory only, and only the IBKR_SPREAD_MAX_SUBSCRIPTIONS (10) most recently requested spreads stay subscribed. The first request of a spread waits at most IBKR_PRICE_QUOTE_WAIT for its first quote.
  • 400 INVALID_SPREAD if the legs are not two different futures of the same underlying and exchange.

Options of a VIX future

GET /options/chain?future_conid={conid} returns the options expiring together with a VX future, with their conids, live quotes and the values of the IBKR option model:

{"future_conid": 866999753, "expiration": "20261215", "multiplier": 100, "trading_class": "VIX", "underlying_price": 22.3,
 "options": [{"conid": 868724165, "strike": 22.0, "right": "C", "bid": 2.95, "ask": 3.05, "bid_size": 120, "ask_size": 80,
              "last": 2.99, "quote_age_seconds": 1, "stale": false, "model_iv": 1.16, "model_delta": 0.514,
              "model_gamma": 0.058, "model_vega": 0.024, "model_theta": -0.046, "stream_error": null}, "..."]}
  • product=VIX (default): the monthly VIX index options (OPT, trading class VIX, the weeklies VIXW are excluded). They settle to the same SOQ as the future, but IBKR reports the day before the expiration of the future as their last trading day: expiration is 20261215 for VXZ6 (20261216). product=VX_FOP: options on the VX future itself (FOP on CFE); IBKR has no such contracts at the moment, so this is 404 FOP_NOT_AVAILABLE.
  • Strikes: the max_strikes (15) strikes closest to the price of the future (underlying_price: mid, or last, or previous close) between F * (1 - strike_range) and F * (1 + strike_range) (0.25), each with the requested rights (C,P). The options are ordered by strike, the call first.
  • The contracts are resolved through TWS (reqContractDetails) and cached by expiration for IBKR_OPTION_CHAIN_CACHE_TTL (12h).
  • Market data: every option is subscribed, the request waits at most IBKR_PRICE_QUOTE_WAIT (3s) altogether for the first quotes. Every option uses a market data line of the account (100 by default, shared with the futures and everything else): this endpoint keeps at most IBKR_OPTION_MAX_SUBSCRIPTIONS (60) options subscribed, e.g. two expirations with 15 strikes, calls and puts. When a chain needs more lines, the option subscriptions of the least recently requested chain are cancelled first, and the strikes which drop out of a chain are cancelled at once. Options which were already subscribed by GET /subscribe or GET /prices are never cancelled here. A single request needing more lines than the limit is 400 OPTION_SUBSCRIPTION_LIMIT.
  • model_iv, model_delta, model_gamma, model_vega, model_theta come from the IBKR option model (tickOptionComputation). TWS sends them asynchronously: they can be null in the first response of a new subscription, and outside of the trading hours they may take longer.
  • A missing market data permission doesn't fail the request: the option has stream_error (eg. 354: Requested market data is not subscribed) and stale: true. stale and quote_age_seconds work like in Prices.
  • Errors: 404 CONTRACT_NOT_FOUND (unknown conid), 400 INVALID_FUTURE (not a VIX future), 404 OPTIONS_NOT_FOUND (no options for the expiration), 422 UNDERLYING_PRICE_UNAVAILABLE (no price of the future at all).

GET /optionChain/{conid} (reqSecDefOptParams) only lists the expirations and strikes of an underlying, without conids and prices.

Trading session

{"conid": 265598, "hours": "liquid", "time_zone": "US/Eastern", "open": true,
 "next_open": "2026-10-16T13:30:00Z", "next_close": "2026-10-15T20:00:00Z", "as_of": "2026-10-15T15:49:00Z"}

Computed from the liquid_hours (regular trading hours, default) or the trading_hours (hours=trading, with the extended hours) and the time_zone of the contract details, so the clients don't have to parse the TWS format. Times are UTC. next_close is the end of the current session if open, otherwise of the next one; next_open is the start of the next session (after the current one, if open). TWS sends the hours about one week ahead: the cached contract details are requested again when they run out (without TWS connection the cached ones are used, and next_open / next_close may be null). An unusable time zone is 502 TRADING_HOURS_UNAVAILABLE.

Account summary

The facade keeps a single account summary subscription (reqAccountSummary) open per TWS connection, and the endpoint returns the latest values; TWS sends the changes every 3 minutes (updated_at). The subscription is never cancelled: IB Gateway 10.50 ignores the protobuf encoded cancelAccountSummary, and TWS allows only two active account summary subscriptions (error 322).

Orders

curl -X POST http://localhost:8082/ibkr/order \
  -H "Authorization: Bearer $IBKR_SECURITY_WRITE_TOKEN" -H "Content-Type: application/json" \
  -d '{"client_order_id": "auxin-20261014-0001", "conid": 265598, "action": "BUY", "quantity": 10,
       "order_type": "LMT", "limit_price": 150.25, "tif": "DAY"}'

The response contains the IBKR order_id, the status and the fill information. Order types: MKT, LMT (limit_price), STP (stop_price), STP_LMT (both). Time in force: DAY (default), GTC, IOC, FOK, OPG.

Safety rules of POST /order:

  • Idempotency. client_order_id is mandatory and is stored in the IBKR orderRef field. It is reserved in Redis (SET NX) before the order is sent, so an order can't go out twice, even with concurrent requests or after a restart. A repeated request returns the existing order with HTTP 200 and "duplicate": true. The same id with different parameters is rejected with 409 CLIENT_ORDER_ID_REUSED. If the id is reserved but TWS doesn't know the order (eg. the facade crashed while sending it), the status is Unknown and the order is never re-sent: use a new client_order_id. A request rejected by a safety check (4xx/503) does not reserve the id.
  • Paper / live. The account type is logged at connection (DU... accounts are paper). Orders on a live account are rejected unless IBKR_ALLOW_LIVE=true; while the account type is unknown, orders are rejected with 503.
  • Market price. Without a bid or ask not older than IBKR_ORDER_MAX_QUOTE_AGE the order is rejected with 422 MARKET_DATA_UNAVAILABLE (the instrument is subscribed automatically).
  • Unknown contract. 404 CONTRACT_NOT_FOUND.
  • No connection / Redis down. 503 TWS_NOT_CONNECTED / IDEMPOTENCY_STORE_UNAVAILABLE, nothing is sent.

Order statuses are the IBKR ones (PendingSubmit, PreSubmitted, Submitted, Filled, Cancelled, Inactive, ...) plus Rejected (TWS rejected the order, see error_code / error_message) and Unknown.

Authentication

With IBKR_SECURITY_ENABLED=true every request needs Authorization: Bearer <token>:

  • read token: GET endpoints and POST /price
  • write token: everything, including POST /order and DELETE /orders/{orderId}

/actuator/health and the API docs (unless IBKR_SECURITY_PUBLIC_DOCS=false) are public.

Observability

  • JSON logs (LOGGING_STRUCTURED_FORMAT_CONSOLE=ecs, default in the image).
  • The trace id of the caller is taken from the W3C traceparent header, or X-Trace-Id, or generated; it is in every log line of the request (trace_id) and returned in the X-Trace-Id response header.
  • /actuator/health is DOWN while the TWS connection is not ready or Redis is not reachable; the tws component shows the connection details and the account type. /actuator/health/liveness and /readiness are available too.
  • Optional OpenTelemetry: mount the OpenTelemetry Java agent and set JAVA_TOOL_OPTIONS=-javaagent:... (see the comments in docker-compose.yml).

Market data in Redis

Subscribed instruments are streamed into Redis TimeSeries under stream:[conid]:[BID|ASK|LAST], labeled with the conid and the symbol. Contracts are cached as contract:[conid] hashes. You can use the full power of Redis on this data (compaction rules for OHLC, pub/sub, etc.), see TimeSeriesHandler.

Building and running without Docker

Requirements: JDK 21+ and Maven. The TWS API jar is vendored in lib, no manual step needed.

mvn package                      # build and unit tests
REDIS_IT=true REDIS_PORT=6379 mvn test -Dtest=ContractRepositoryRedisIT   # optional, needs a running Redis
java -jar target/ibkrfacade-1.0-SNAPSHOT.jar --ibkr.tws.port=4002 --spring.data.redis.host=localhost

You need a running TWS or IB Gateway with the API enabled (initial setup) and a Redis with RedisTimeSeries.

Trading strategy automation

The strategy package contains a sample: it watches the price of Apple in Redis looking for a signal and places orders through the same safety checks as the REST API. The samples are not loaded unless IBKR_STRATEGIES_ENABLED=true, and even then the trading methods are not scheduled.

Important: This is not a real strategy. Don't even think about using it in real conditions!

License

Copyright (C) 2022-2026 Mihaly Medovarszki

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. See LICENSE.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. This also applies to trading: use it at your own risk, any order it places is your responsibility.

The bundled TWS API is released by Interactive Brokers under the GNU GPL v3 from version 10.49 (see lib/README.md). Distributing the application (eg. the Docker image or the packaged jar) means distributing a combined work under the GPL v3, together with its complete corresponding source code.

About

Interactive Brokers API wrapper and trading toolbox

Topics

financefinancial-datafinancial-data-readerfinancial-marketsibkribkr-apiinteractive-brokersmarket-datastock-analysisstock-datastock-marketstock-pricesstock-tradingtrading-bottrading-platformtrading-strategiestrading-tooltwstws-api

Resources

Readme
GPL-3.0 license
Activity

Stars

49 stars

Watchers

5 watching

Forks

15 forks
Report repository

Used by

Contributors

Languages

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.