{"id":48826021,"url":"https://github.com/trippwill/gbkr","last_synced_at":"2026-04-14T18:01:22.863Z","repository":{"id":339880295,"uuid":"1162369570","full_name":"trippwill/gbkr","owner":"trippwill","description":"Go client for the IBKR REST API","archived":false,"fork":false,"pushed_at":"2026-03-21T22:21:27.000Z","size":338,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-03-22T10:56:39.842Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/trippwill.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2026-02-20T07:11:14.000Z","updated_at":"2026-03-21T22:21:29.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/trippwill/gbkr","commit_stats":null,"previous_names":["trippwill/gbkr"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/trippwill/gbkr","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trippwill%2Fgbkr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trippwill%2Fgbkr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trippwill%2Fgbkr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trippwill%2Fgbkr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/trippwill","download_url":"https://codeload.github.com/trippwill/gbkr/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trippwill%2Fgbkr/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31808518,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-14T11:13:53.975Z","status":"ssl_error","status_checked_at":"2026-04-14T11:13:53.299Z","response_time":153,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-04-14T18:01:22.005Z","updated_at":"2026-04-14T18:01:22.839Z","avatar_url":"https://github.com/trippwill.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# gbkr\n\nA Go client library for the [Interactive Brokers](https://www.interactivebrokers.com/) Client Portal Gateway REST API.\n\n## Features\n\n- **Two-tier session model** — `gbkr.Client` for gateway access, `brokerage.NewSession` for brokerage session capabilities\n- **Handle-based API** — capabilities accessed via purpose-built handle types (`Portfolio`, `Analysis`, `Accounts`, `MarketData`, `Contracts`, `Trades`)\n- **Automatic API pacing** — built-in rate limiting and concurrency control matching IBKR's documented limits\n- **Strongly-typed domain aliases** — `AccountID`, `ConID`, `Currency`, `BarSize`, `TimePeriod` prevent parameter confusion\n- **Structured error model** — const sentinel errors with `errors.Is`/`errors.As` support\n\n## Install\n\n```bash\ngo get github.com/trippwill/gbkr\n```\n\n## Quick Start\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n\n    \"github.com/trippwill/gbkr\"\n    \"github.com/trippwill/gbkr/brokerage\"\n)\n\nfunc main() {\n    client, err := gbkr.NewClient(\n        gbkr.WithBaseURL(\"https://localhost:5000/v1/api\"),\n        gbkr.WithInsecureTLS(),\n    )\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    // Elevate to a brokerage session (SSO/DH handshake).\n    bc, err := brokerage.NewSession(context.Background(), client, \u0026brokerage.SSOInitRequest{})\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    // Use handle-based API.\n    accounts, err := bc.Accounts().List(context.Background())\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(accounts)\n}\n```\n\n## Session Model\n\ngbkr mirrors the IBKR gateway's two-phase session lifecycle:\n\n| Tier | Type | How to get | Capabilities |\n|------|------|------------|--------------|\n| Gateway | `*gbkr.Client` | `gbkr.NewClient(opts...)` | `SessionStatus`, `Portfolio`, `Analysis` |\n| Brokerage | `*brokerage.Client` | `brokerage.NewSession(ctx, client, req)` | `Accounts`, `MarketData`, `Contracts`, `SecurityDefinitions`, `Trades` |\n\n### Capability-to-Path Mapping\n\n| Capability | Access Point | IBKR Path Prefix |\n|------------|-------------|-----------------|\n| Portfolio | `Client.Portfolio()` | `/portfolio/{accountId}/*` |\n| Analysis | `Client.Analysis()` | `/pa/*` |\n| Accounts | `brokerage.Client.Accounts()` | `/iserver/accounts` |\n| MarketData | `brokerage.Client.MarketData()` | `/iserver/marketdata/*` |\n| Contracts | `brokerage.Client.Contracts()` | `/iserver/contract/{conid}/*` |\n| SecurityDefinitions | `brokerage.Client.SecurityDefinitions()` | `/iserver/secdef/*` |\n| Trades | `brokerage.Client.Trades()` | `/iserver/account/trades` |\n\n## Capability Separation (ADR-008)\n\nTypes are co-located with their capabilities — no separate `models` package. Shared\nprimitives (`AccountID`, `ConID`, `Currency`, etc.) live in `types.go` in the root package;\nbrokerage-specific types (`BarSize`, `SnapshotField`, etc.) live in `brokerage/types.go`.\n\nDangerous capabilities (trading, banking) will live in **separate Go modules**\n(`gbkr/trading`, `gbkr/banking`) so that consuming applications must explicitly import\nthem — making the dependency visible in `go.mod`. See [ADR-006](https://github.com/trippwill/midwatch.work/blob/main/docs/decisions/006-structural-capability-separation.md) for rationale.\n\n## API Pacing\n\nThe client automatically enforces IBKR's pacing limits:\n\n- Global ceiling of 10 requests/second\n- Per-endpoint rate limits for sensitive paths\n- Concurrency semaphores where documented\n\nPacing can be disabled for testing with `WithRateLimit(nil)` or observed via `WithPacingObserver`.\n\n## Error Handling\n\nAll domain errors are inspectable via standard Go error patterns:\n\n```go\nimport \"errors\"\n\n// Check sentinel errors\nif errors.Is(err, gbkr.ErrAPIRequest) {\n    // non-2xx API response\n}\n\n// Extract structured context\nvar apiErr *gbkr.APIError\nif errors.As(err, \u0026apiErr) {\n    fmt.Println(apiErr.StatusCode, apiErr.Status)\n}\n```\n\n## CLI\n\nA test CLI is included for exercising the library:\n\n```bash\ngo run ./cmd/gbkr --insecure\n```\n\n## Field Name Mapping\n\nModel structs use friendly Go names where the IBKR API uses abbreviations or\ninconsistent casing. The table below lists every rename; JSON serialization\nuses the original API keys so wire compatibility is preserved.\n\n### PnLEntry (`GET /iserver/account/pnl/partitioned`)\n\n| Go Field | API Key | Description |\n|----------|---------|-------------|\n| `DailyPnL` | `dpl` | Daily profit/loss |\n| `NetLiquidation` | `nl` | Net liquidity |\n| `UnrealizedPnL` | `upl` | Unrealized profit/loss |\n| `RealizedPnL` | `rpl` | Realized profit/loss |\n| `ExcessLiquidity` | `el` | Excess liquidity |\n| `MarginValue` | `mv` | Margin value |\n\n### AccountList (`GET /iserver/accounts`)\n\n| Go Field | API Key | Description |\n|----------|---------|-------------|\n| `SelectedAcct` | `selectedAccount` | Currently selected account |\n\n### Position (`GET /portfolio/{accountId}/positions/{pageId}`)\n\n| Go Field | API Key | Description |\n|----------|---------|-------------|\n| `Qty` | `position` | Total position size |\n\n### LedgerEntry (`GET /portfolio/{accountId}/ledger`)\n\n| Go Field | API Key | Description |\n|----------|---------|-------------|\n| `FuturesPnL` | `futuresonlypnl` | Futures position PnL |\n| `FutureOptionValue` | `futureoptionmarketvalue` | Futures options market value |\n| `NetLiquidation` | `netliquidationvalue` | Net liquidation value |\n\n### HistoryResponse / HistoryBar (`GET /iserver/marketdata/history`)\n\n| Go Field | API Key | Description |\n|----------|---------|-------------|\n| `Bars` | `data` | Array of OHLCV bars |\n| `Open` | `o` | Bar open price |\n| `High` | `h` | Bar high price |\n| `Low` | `l` | Bar low price |\n| `Close` | `c` | Bar close price |\n| `Volume` | `v` | Bar volume |\n| `Time` | `t` | Epoch timestamp |\n\n### Snapshot (`GET /iserver/marketdata/snapshot`)\n\n| Go Field | API Key | Description |\n|----------|---------|-------------|\n| `ServerID` | `server_id` | Internal server identifier |\n| `UpdateTime` | `_updated` | Last update timestamp |\n\n### SessionStatus (`POST /iserver/auth/ssodh/init`, `POST /iserver/auth/status`)\n\n| Go Field | API Key | Description |\n|----------|---------|-------------|\n| `HardwareInfo` | `hardware_info` | Hardware info string |\n\n## Flex Web Service (`gbkr/flex`)\n\nThe `flex` subpackage is a separate Go module for retrieving IBKR Activity Statement reports\nvia the Flex Web Service — a standalone IBKR API independent of the Client Portal Gateway.\n\n```bash\ngo get github.com/trippwill/gbkr/flex\n```\n\n### What it does\n\n- Fetches Activity Statement XML reports using a long-lived API token and pre-configured query ID\n- Parses Trades, Cash Transactions, Option Events, and Commission Details sections\n- Handles the two-step retrieval protocol (SendRequest → poll GetStatement) with configurable retry/backoff\n- Optionally saves raw response bodies to disk for debugging\n- Detects common misconfigurations (CSV output, expired tokens, query errors)\n\n### Quick Start\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n    \"time\"\n\n    \"github.com/trippwill/gbkr/flex\"\n)\n\nfunc main() {\n    c := flex.NewClient(\n        flex.WithReportDir(\"/tmp/flex-reports\"), // optional: save raw XML/CSV responses\n    )\n\n    resp, err := c.FetchReport(context.Background(), \"YOUR_TOKEN\", \"YOUR_QUERY_ID\",\n        flex.WithMaxRetries(10),\n        flex.WithInitialDelay(5*time.Second),\n    )\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    for _, stmt := range resp.Statements {\n        fmt.Printf(\"Account %s: %d trades\\n\", stmt.AccountID, len(stmt.Trades))\n    }\n}\n```\n\n### Error Types\n\n```go\nimport \"errors\"\n\n// Check for specific conditions\nif errors.Is(err, flex.ErrWrongFormat) {\n    // Query Format is not set to XML in IBKR Flex query template\n}\nif errors.Is(err, flex.ErrTokenExpired) {\n    // API token needs to be renewed in IBKR Client Portal\n}\n```\n\n## Development\n\n```bash\nmise run precommit   # fmt → build → test with race detection\nmise run ci          # full CI pipeline\nmise run vet         # golangci-lint\nmise run flex:precommit  # run the flex module precommit pipeline from repo root\nmise run flex:ci         # run the flex module CI pipeline from repo root\n```\n\nSee [AGENTS.md](AGENTS.md) for full development guidelines.\n\n## License\n\nSee [LICENSE](LICENSE) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrippwill%2Fgbkr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftrippwill%2Fgbkr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrippwill%2Fgbkr/lists"}