IBKR · Research Data Plane · August 2026

IBKR August Improvement & Development Handover

Interactive development handover for extending the existing ib_async integration across the daemon, CLI, nightly report, weekly report, and AI advisor.

Document IBKR_Aug_Improvement.md · Date: 2026-08-16 · Status: Development-team handover proposalLibrary ib_async(現有整合,非 migrate)· Companion: Futu OpenD read-onlyGit branch futu-speed-p0 · rollback tag pre-futu-speed-2026-08-16 · 391 unit tests passing
32Development plan work packages
P0 → P2Prioritized rollout sequence
Read-onlyNo order behavior changes
No matching sections. Try a different search term.

1. Executive decision

將現有 CLI + reports 變成 single, source-aware research data service:

CLI / nightly / weekly → daemon queue → one IBKR connection + _ib_lock
                        ↘ Futu OpenD (independent read-only plane)

四個 decision:

  1. Daemon-only IBKR access. Report 唔再開 direct client 87/88。
  2. Source-aware rich contract. source / timestamp / age / market_data_type / availability 每個 field 都要有。
  3. Research baseline. Rich quote + held-option liquidity + cached daily history。
  4. One-call agent bundle. Hermes 由 3–4 calls / 2–3 分鐘 → 1 call,budget warm ≤3s / cold ≤10s / worst 60s。Futu 係 universe market data 嘅速度答案;IBKR 保持 account/execution authority。

2. Non-negotiable rules

  1. IBKR first — gateway 健康就用 IBKR 做 current price / range / fundamentals / history / options / portfolio。
  2. One daemon connection — research call 全部經 daemon queue + _ib_lock
  3. Read-only scope — 唔加 auto order / roll / rebalance。
  4. Backward compatibility — 舊 quote keys(price/close/bid/ask)保留,rich fields additive。
  5. No silent fallback — missing field = null + availability state;external fallback 要 source/timestamp/reason。
  6. No disguised delaymarketDataType live/frozen/delayed/delayed-frozen 要 expose。
  7. No fabricated values — missing/not_entitled/timeout ≠ zero ≠ 成功。
  8. Preserve raw data — raw ratios / XML / WSH JSON / headline IDs 保留。
  9. Bound every request — outer deadline + try/finally cleanup。
  10. Trading math stays in core/ — PMCC/vertical/max-loss math 唔入 Futu 或 report。
  11. Account truth = IBKR/Flex only — Futu 永遠唔係 positions/cash/fills/orders/P&L/BAG 權威。
  12. Indicators ≠ predictions — derived metrics 係 advisor context。

Source arbitration:

DomainAuthorityFutu role
Account/cash/margin/positions/fills/orders/BAGIBKR/FlexNone — never
Current executable quoteIBKR when healthycross-check + display fallback
Historical daily barsIBKR by defaultcached supplement / explicit fallback
Valuation / financials / analyst consensusfirst-class Futu research
Capital flow / short interest / ownershipfirst-class Futu research
Earnings/economic/FedFutu(WSH optional)first-class Futu macro
News / sentimentsource=futu_content
Strategy analyticscore combo mathFutu informational cross-check

3. Implementation status(2026-08-16,已 ship)

CapabilityCommandMeasured
Batched universe quotes ≤400 codes,bad code 隔離ibkr futu quote SYM... / futu universe118 codes = 242ms cold / 108ms warm
Cross-process 60s disk cacheautomaticrepeat ≈ 1ms
Full-row normalization60+ fields/row(was 7)
One-call research bundleibkr bundle [--with-history] [--with-research]1.65s(was worst 72 calls / 390s)
Fast portfolio(skip Greek enrichment)ibkr portfolio --fast~1.7s,combos 一致
History cache + quota guardibkr futu history SYM --interval 1d --count N / futu quotalatest-N bars,6h cache
Research shortcutsfutu short / flow / fedwatch / earningslive-verified
Symmetric speed log~/.kit-ibkr/logs/speed.logIBKR + Futu JSON lines
CN code mapping fixedto_futu_codeSH./SZ./SG./MY./JP./CC./EC. pass-through
Economic calendar paginationeconomic_calendar()≤20 pages
Pure JSON stdoutFutu SDK console silencedagent-parseable

Bundle resilience contract(normative):

  1. Bundle 永遠唔 raise provider error — 全部變 warnings[] + partial sections。
  2. account/portfolio/quotes/events always run;optional sections symbol-bounded、per-symbol error。
  3. 60s wall budget:optional section skip + skipped: bundle wall budget exhausted
  4. Portfolio 3 層 fallback:raw+local combos(fast)→ enriched daemon(slow)→ direct client;每次 fallback 寫 warning。
  5. warnings[] 非空 = 該 section 不可信 → Hermes fallback 個別 command,唔可以當成功。

Monday comparison:

grep '"command": "futu' ~/.kit-ibkr/logs/speed.log | tail -50
grep -E 'cmd=(quote|batch quote|portfolio)' ~/.kit-ibkr/logs/audit.log | tail -50

快/同等 + data 更豐富 → merge futu-speed-p0main。慢 → git checkout pre-futu-speed-2026-08-16(即時回舊)。


4. Hermes bundle contract

ibkr bundle                          # account+portfolio+universe+events 一個 call
ibkr bundle --with-history           # 每 holding 最新 250 daily bars
ibkr bundle --with-research          # short interest + capital flow
StateBudget
Warm(cache fresh)≤3s(實測 1.65s closed)
Cold≤10s typical
--fresh≤60s hard bound
Futu downIBKR-only degraded + FUTU_UNAVAILABLE warning
IBKR downexplicit error,no silent fallback

機制:CLI 同時打 IBKR daemon + Futu OpenD(獨立 planes),wall ≈ max(t_ibkr, t_futu)


5. ib_async API assessment(精簡)

5.1 Contract identity / metadata

APIUsePriority
qualifyContractsAsync身份權威,research 前必行P0
reqContractDetailsAsyncdetails;industry/tz/hours/market rulesP1
reqHistoricalScheduleAsyncUS/HK session-aware 窗口,取代 hardcode NYSE calendarP1
reqHeadTimeStampAsync / reqMarketRuleAsync / reqMatchingSymbolsAsync診斷 / 價格規則 / symbol searchP2

5.2 Rich market data(reqMktData generic ticks)

TicksFieldsUse
16513/26/52 週 range + avVolumerange position、volume context
221 233 236mark / RT volume+VWAP / shortablemark、intraday、liquidity
258 456fundamentalRatios / Dividendsvaluation、股息
293–295 411tradeCount/Rate/VolumeRate + RT hist volactivity、volatility
Option 100/101/104/105/106volume / OI / HV / avg vol / IVheld-leg liquidity

Collector:qualify → reqMktData → bounded wait → copy → finally cancelMktDatareqTickersAsync 唔支援 generic ticks。

5.3 Options / Greeks

Ticker.bidGreeks/askGreeks/lastGreeks/modelGreeksOptionComputation{impliedVol,delta,optPrice,pvDividend,gamma,vega,theta,undPrice}。保留 side-specific provenance;唔好再 modelGreeks or bidGreeks or askGreeksreqSecDefOptParamsAsync 只返 chain metadata(strike/expiry 可能有 invalid combo,要 qualify selected legs)。Option volume/OI 可以計 put/call ratio,但唔可以宣稱 dealer flow(冇 aggressor side / open-close 分類)。

5.4 Historical(reqHistoricalDataAsync

BarDataList → BarData{date,open,high,low,close,volume,average,barCount}whatToShow 包括 TRADES / ADJUSTED_LAST / HISTORICAL_VOLATILITY / OPTION_IMPLIED_VOLATILITY。官方限制:50 concurrent、identical ≤15s 禁止、同 contract 6/2s、60/10min、BID_ASK 計兩次、few-thousand bars、≤30s bars 6 個月外不可用、expired options EOD 不可用。scheduled jobs 用 cached daily bars + exact-request cache。

5.5 Fundamentals / WSH / News

  • reqFundamentalDataAsync → XML:ReportsFinSummary / ReportsOwnership / ReportSnapshot / ReportsFinStatements / RESC / CalendarReport。保留 raw XML + LATESTADATE;normalize 只用實測 aliases。
  • WSH:getWshMetaDataAsyncgetWshEventDataAsync。要 Wall Street Horizon subscription;metadata 先行、一次一個 request(duplicate 會被拒)。Optional,NOT_ENTITLED 唔當 failure。
  • News:reqNewsProvidersAsync / reqHistoricalNewsAsync(≤300)/ reqNewsArticleAsync。API-specific subscriptions。Weekly/on-demand only。
  • 注意:ib_async 冇 macro calendar API — economic calendar/Fed 用 Futu。

5.6 Account / Executions / PnL

  • reqExecutionsAsync + Fill/CommissionReport → 佣金、realized P&L、exchange — weekly attribution;Flex 仍然係歷史 authority。
  • reqPnL / reqPnLSingle 係 sync subscription-start(實測 2.1.0 冇 Async variants),要 cancel lifecycle;intraday only,歷史 attribution 要 persisted snapshots + Flex reconcile。
  • accountSummaryAsync / portfolio() 保持 source-of-truth。

5.7 Scanner / Deferred

reqScannerDataAsync on-demand only(50 rows / 10 active scans,結果只係 contracts 要 follow-up quote)。Deferred:reqMktDepth / reqTickByTickData / reqRealTimeBars / reqHistoricalTicks / calculateImpliedVolatilityAsync / calculateOptionPriceAsync — 全部 explicit research tool,唔入 nightly baseline。


6. Futu companion plan(精簡)

6.1 Position

First-class read-only companion plane,經 OpenD 127.0.0.1:11111,唔經 IBKR socket / _ib_lock。現時權限:US LV3、US Options LV1/OPRA、HK。

6.2 Capability matrix

Futu APIStateUseCadence
get_market_snapshot(≤400/call,60/30s)universe quotesnightly / on-demand
request_history_kline(≤1000/page,60/30s)history cacheweekly / on-demand
get_history_kl_quotaquota guardbefore batches
get_option_strategy_analysis(30/30s,免 subscription quota)combo bid/ask + probability cross-checkon-demand
get_option_chain / get_option_quote✅ / inventorycontract discovery、multi-leg quoteon-demand
get_earnings_calendar(7-day window)earningsweekly
get_economic_calendar✅ paginatedmacroweekly
get_fed_watch_target_rateLEAPS rate sensitivityweekly
get_short_interest / get_capital_flownightly flownightly
Financials / valuation / analyst / corporate actions / ownershipinventoryresearch enrichmentweekly / on-demand
Rankings / screeners / platesinventorycandidate discoveryon-demand
Content skills(news/research/sentiment)public HTTPsource=futu_content digeston-demand

6.3 Quota / lifecycle rules

  • Snapshot 1 call ≤400 codes;unknown/delisted code 會令成 batch fail → recursive bisect 隔離(已實作)。
  • Subscription = lease:每個 code×type 食 1 quota,≥1 分鐘先可 unsubscribe;nightly 唔好用 subscription 代替 snapshot。
  • History quota 7 日 dedup(官方 authority page)vs Agent Hub 寫 30 日 — 以 runtime get_history_kl_quota(get_detail=True) 為準,唔 hardcode。
  • 一個 scoped context per report run;close 喺 finally;OpenD down = FUTU_UNAVAILABLE,唔 auto-restart。
  • futu_api/OpenD 版本要 pin + record(FP-00)。

6.4 Provenance envelope

{
  "source": "futu",
  "endpoint": "get_market_snapshot",
  "requested_at": "...", "received_at": "...", "as_of": "...", "age_ms": 340,
  "delayed_or_realtime": "realtime",
  "availability": "available",
  "quota": {"checked": true, "remaining": null},
  "errors": [],
  "data": []
}

Content skills 用 source=futu_contentfutu_enrich.py 唔可以丟 envelope。


7. Data contracts(精簡)

Provenance(所有 result 必有): source / source_detail / requested_at / received_at / as_of / age_ms / market_data_type / availability / errors / request

Availability vocabulary: available / missing / not_entitled / unsupported / timeout / error / stale

Market snapshot(stock,Futu 已實作 60+ fields): identity(conid/sec_type/exchange/currency)· market(bid/ask/last/mark/close/open/high/low/volume/vwap/sizes)· range(13/26/52w + position%)· quality(spread、volume ratio、trade rates)· fundamentals(raw + normalized + report_date)· dividends(past/next/date/amount)· sessions(pre/after/overnight)· provenance。

Option snapshot(additive): bid/ask/mid/spread$/%、IV/HV、side-specific/model Greeks、volume/OI/avg option volume、underlying price、DTE/BE distance、risk flags(OPTION_BID_ASK_MISSING / WIDE_SPREAD / DELAYED_DATA / NOT_ENTITLED)。

Historical(derived 要標 formula): returns、realized vol、ATR、SMA20/50/200、max drawdown、benchmark-relative;insufficient history = null + missing,唔 fabricated。


8. CLI surface

ibkr quote / batch quote        additive rich fields(P0 collectors)
ibkr snapshot SYM [--history 1y] [--fundamentals] [--events] [--options --expiry]
ibkr portfolio [--raw] [--fast]  --fast = no Greek enrichment ~1.7s(已實作)
ibkr bundle [--with-history] [--with-research]   ← Hermes preferred(已實作)
ibkr futu universe / quote / history / quota / short / flow / fedwatch / earnings(已實作)
ibkr futu health / chain / option / bars / strategy(原有)
ibkr screen / news / events     P1/P2 on-demand

規則:Futu commands 永遠唔經 IBKR daemon;成功/error 都標 source=futu;所有 speed 相關 call 寫 speed.log


9. Development plan(32 work packages,精簡 table)

9.1 IBKR DP-*

IDPriorityDepsEffortScopeKey files
DP-00P0Spin/test ib_async,source hierarchypyproject, AGENTS
DP-01P0DP-00Mreport IBKR work 收歸 daemon(拆 client 87/88)daemon, data, weekly
DP-02P0DP-00S/Mprovenance/availability schemamodels/market_data
DP-03P0DP-01,02MIBClient research wrapperscore/connection
DP-04P0DP-02,03Mgeneric-tick collector + rich quotedaemon, cli
DP-05P0DP-04M/Hheld-option liquidity + risk flagsdaemon, portfolio, analysis
DP-06P0DP-01,03MIBKR history cache + derived metricsmarket_data, weekly
DP-07P0DP-02,04–06Mprovenance 入 nightly/weekly/AI/HTMLreport/*
DP-08P1DP-03,04M/Hfundamentals XML + RESCcore, daemon
DP-09P1DP-03,07M/HWSH events(optional entitlement)upcoming, weekly
DP-10P1DP-01,07S/Mexecutions commission attributiondaemon, weekly
DP-11P1DP-03,04Mon-demand scanner + bounded top-Ndaemon, cli
DP-12P2DP-03,07Mnews digestdaemon, weekly
DP-13P2DP-05,07M/HPnLSingle snapshots + reconciledaemon, weekly
DP-14P2DP-04,05S/Mcalculate* scenario toolsdaemon, cli
DP-15P0+DP-01..Mrollout + smoke + runbook

9.2 Futu FP-*

IDPriorityDepsEffortScopeKey files
FP-00P0Spin futu-api/OpenD + quota window 實測pyproject, config
FP-01P0FP-00S/Mprovenance envelope 全 section(✅部分已做)futu/models
FP-02P0FP-01Mscoped context + batch snapshot + cache(✅已做)futu/client, service
FP-03P0FP-00,02Mhistory cache + quota guard(✅已做)futu/service
FP-04P0FP-02,03S/Mspeed/freshness diagnostics(✅speed.log 已做)futu, cli
FP-05P1FP-01,02Moption/strategy research adaptersfutu/service
FP-06P1FP-01,02M/Hfundamentals + corporate actionsfutu/service
FP-07P1FP-01,02,04Mflow/calendar hardening(✅pagination 已做)futu, reports
FP-08P1FP-01..07M完整 Futu CLI(✅core commands 已做)cli
FP-09P2FP-01,04Mcontent skills digestfutu/content
FP-10P0+FP-02–04Mcross-provider benchmark gate(星期一)

9.3 Bundle DB-*

IDPriorityDepsEffortScope
DB-00P0DP-00,02,FP-00,01S/Mibkr bundle contract + dispatcher(✅已做:1.65s + resilience)
DB-01P0FP-01,02MFutu batch universe quotes + 60s cache(✅已做)
DB-02P0DP-06,FP-03Mhistory precompute(nightly/weekly 餵 cache)— 剩低
DB-03P0FP-01,02,04,07Mresearch/event precompute — 剩低
DB-04P0DB-00..03S/Mlatency benchmark + regression gate — 星期一執行

10. Pacing / lifecycle / error policy

  • Async 規則: *Async methods + outer asyncio.wait_for;唔 time.sleep;唔喺 event handler 內發新 request。
  • Cleanup: 所有 subscription finally cancel(mktData / historical / depth / tickByTick / realtimeBars / scanner / WSH / PnL)。
  • Error 分類: CONTRACT_NOT_FOUND / AMBIGUOUS / NOT_ENTITLED / UNSUPPORTED / TIMEOUT / PACING / DISCONNECTED / PARSE_ERROR / STALE / UNKNOWN。empty result ≠ 成功(ib_async RaiseRequestErrors=False 陷阱)。
  • IBKR pacing: 50 concurrent max、identical 15s、6/2s 同 contract、60/10min、BID_ASK×2;exact-request cache + serial queue。
  • Futu pacing: snapshot 60/30s、history 60/30s first page、search 10/30s、strategy 30/30s;subscription ≥1min lease。
  • Timezone: formatDate=2(UTC)、RTH explicit、contract session data 取代 hardcode NYSE;holiday/early-close ≠ missing。

11. Rejected / deferred

  1. ib_async macro calendar — 唔存在,用 Futu。
  2. Duplicate Futu capabilities 過 IBKR — 除非 data quality 原因。
  3. Full-universe nightly scanner / full-chain nightly — bounded only。
  4. Silent Yahoo primary/fallback — 如保留要 source+reason。
  5. Depth/tick-by-tick 做 report baseline — execution research only。
  6. Persistent streaming by default — snapshot 評估計比較安全。
  7. 由 current PnL 重建歷史 attribution — persisted snapshots 先啱。
  8. Option volume = dealer flow — 冇 aggressor/open-close 分類,唔可以咁講。
  9. Trading/order enhancements — 唔屬於本 plan。
  10. Cosmetic HTML/3D 先過 data quality — defer。

12. Tests & verification

Unit(391 passing baseline): test_market_data(schema/availability/delayed mapping)· test_historical_market_data(bars/cache/metrics)· test_bundle(combo detection/budget/fallback)· test_futu(27:allowlist/batch/cache/error isolation/source)· test_futu_report · test_fundamentals · test_wsh_events · test_news · test_scanner · test_pnl_snapshots + 現有 suites(batch_quote/connection/portfolio_raw/analysis/weekly/fallback/upcoming/advisor/html_v3)。

Paper smoke(read-only):

.venv/bin/ibkr health && .venv/bin/ibkr portfolio --fast
.venv/bin/ibkr bundle && .venv/bin/ibkr futu universe
.venv/bin/python scripts/nightly_report.py --no-ai --no-discord --no-pagedrop
.venv/bin/python scripts/weekly_report.py --no-ai --no-discord

Failure matrix: daemon down / gateway reconnecting / invalid + ambiguous contract / no live subscription / delayed only / generic tick not entitled / WSH not entitled / news provider absent / history timeout / stale cache / OpenD down / Flex 1019 / mixed per-symbol fallback / cancelled request + follow-up quote。


13. Rollout + rollback

Stages: schema-only → paper rich quote → paper nightly → paper weekly → optional entitlements(逐個開)→ live read-only → docs。

Rollback(即時):

git checkout pre-futu-speed-2026-08-16     # 完整 rollback point(tag)
# 繼續修:
git checkout futu-speed-p0

Rollback 邊界: 只有 Futu quote path + bundle 改咗;IBKR portfolio/orders/BAG/P&L 未動;disk cache passive(刪 ~/.kit-ibkr/cache/futu/ 即 disable);speed.log append-only。

Handover checklist(short):

  • 所有 IBKR request 經 daemon;無 direct client 87/88
  • Rich fields 帶 source/as-of/age/market-data type/availability
  • Missing ≠ zero;delayed ≠ live;per-symbol mixed sources 可見
  • Bundle warm ≤3s 實測;warnings[] 非空時 Hermes 識 fallback
  • Historical pacing + exact-request cache + subscriptions cancel
  • Futu quota 先 check;WSH serialized;futu-api pin
  • Paper + live read-only smoke pass
  • 無 order 行為、無 Futu account authority、無 silent Yahoo、無 dealer-flow claims

14. Schedule & backlog

已 ship(2026-08-16): speed milestone 完成 — bundle 1.65s、Futu batch 242ms/118 codes、60s cache、history cache、symmetric speed.log、CN fix、economic pagination。

剩低(順序):

#TaskEst
1DB-04 星期一 open-market 實測 + baseline gate → merge 決定1d
2DB-02 nightly/weekly precompute history cache3d
3DB-03 research/event precompute3d
4DP-01 report IBKR work 收歸 daemon3d
5DP-04/05 daemon 14s Greek enrichment 拆解 + rich quote5.5d
6DP-08 fundamentals / DP-09 WSH probes5.5d each
7FP-05/06 Futu option + research adapters3–5.5d
8P2:news / PnL snapshots / scenario tools3–5.5d each

Estimate: P0 剩低 ≈ 6–8 週;全部連 P1/P2 ≈ 10–12 週(一人)。