Metadata-Version: 2.5
Name: ibkr-flex-accounting
Version: 0.1.0
Summary: Strict, resumable Interactive Brokers Flex Web Service v3 accounting, reconciliation, and market-projection engine
Project-URL: Homepage, https://github.com/benjamin-di/ibkr-flex-accounting
Project-URL: Issues, https://github.com/benjamin-di/ibkr-flex-accounting/issues
Author: benjamin-di
License-Expression: MIT
License-File: LICENSE
Keywords: accounting,finance,flex,ibkr,interactive-brokers,portfolio,reconciliation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Accounting
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Python: >=3.11
Requires-Dist: pyyaml<7,>=6
Description-Content-Type: text/markdown

# ibkr-flex-accounting

Strict, resumable Interactive Brokers Flex Web Service v3 accounting, reconciliation, and market-projection engine for Python.

## Why this library exists

Thin XML parsers turn Flex statements into objects, but real portfolio accounting hits harder problems:

- **Strict arithmetic reconciliation**: Every accepted snapshot must reconcile native cash (`CashReport`), positions (`OpenPositions`), accruals (`InterestAccruals`, `OpenDividendAccruals`), closing FX (`ConversionRates`), Statement of Funds running balances (`StmtFunds`), Forex balances (`FxPositions`), `ChangeInNAV`, and `MTMPerformanceSummaryInBase` / `FIFOPerformanceSummaryInBase` using `Decimal` arithmetic.
- **Resumable multi-lane acquisition**: Independent `daily`, `period` (YTD/MTD), `performance_history`, and `history` lanes persist durable JSON journals so a slow backfill never blocks the daily close, references survive restarts, and tokens are never logged or redirected off `*.interactivebrokers.com`.
- **Immutable archives + safe compaction**: Raw XML files are stored content-addressed (`YYYY-MM-DD-ibkr-flex-<sha16>.xml`), superseded period windows can be compacted in memory and safely pruned on disk while preserving every daily original.
- **Any base currency**: Base currency (`USD`, `EUR`, `GBP`, `CHF`, etc.) is inferred from `EquitySummaryInBase` or enforced explicitly via `base_currency=...`.
- **Pure market projection**: `value(report, when, quote=..., fx=...)` projects confirmed broker quantities onto external closing prices/FX without mutating accounting facts, separating quote-source basis differences from market movement.

## Installation

```bash
pip install ibkr-flex-accounting
```

Or with `uv`:

```bash
uv add ibkr-flex-accounting
```

## Quick start

### Python API

```python
from pathlib import Path
from ibkr_flex_accounting import account, store

cfg = {
    "account": "U1234567",
    "query_id": "123456",
    "query_name": "Portfolio Accounting",
    "anchor": "2025-12-31",
}

# Bootstrap a normalized store from an archive of Flex XML files
acct_store, rejected = store.bootstrap(Path("./archive"), cfg)
store.compact(acct_store)

latest = account.latest(acct_store, "2026-09-08")
print(latest["base_currency"], latest["nav"]["total"])
```

### Multi-lane collection (resumable)

```python
import os
from pathlib import Path
from ibkr_flex_accounting import account, reporting, store

acct_store = account.load("store.json")
acct_store, acks, findings = store.collect(
    acct_store,
    cfg,
    state_dir=Path("./state"),
    archive=Path("./archive"),
    when="2026-09-08",
    token=os.environ["IBKR_FLEX_TOKEN"],
)
store.compact(acct_store)
store.save("store.json", acct_store)
for state_path, state, _ in acks:
    reporting.acknowledge(state_path, state)
```

### CLI

```bash
# Build a store from archived XMLs
ibkr-flex bootstrap --archive ./archive --config ibkr-flex.yaml --output store.json --compact

# Run one resumable collection cycle (reads IBKR_FLEX_TOKEN from env)
ibkr-flex collect --archive ./archive --config ibkr-flex.yaml --state-dir ./state --store store.json

# Inspect latest NAV, controls, and issues
ibkr-flex inspect --store store.json

# Safely prune superseded period XMLs (all daily originals are preserved)
ibkr-flex prune --archive ./archive --store store.json
```

See [docs/flex-query-setup.md](docs/flex-query-setup.md) for the required IBKR Activity Flex Query sections and configuration fields.

## Security & safety invariants

- **XXE-safe**: Rejects XML payloads containing `<!DOCTYPE` or `<!ENTITY`.
- **No token leakage**: `GetStatement` only follows `https://*.interactivebrokers.com/.../GetStatement` URLs, disables HTTP redirects (`NoRedirect`), redacts tokens and URLs from error messages, and caps responses at 32 MiB.
- **Rate-limit friendly**: Enforces a 1.1s cooldown after every Flex Web Service call (including failures).
- **Atomic writes**: Journals, archives, and JSON stores use same-directory temp file + `fsync` + `os.replace`.

## License

MIT — see [LICENSE](LICENSE).
