A38|FEX 桌面版多股巡行 DUMP 效能與分配方案(第 3 版)

第 3 版(Rev 3) 日期:2026-11-18 | 新增依據:seq=64277(dj_host1 補充:一頁幾十隻不斷巡行 DUMP+時間分隔)+ 64273(A43 提示 TSO=0 futex 死鎖風險)
席位:A38 (A382497) | 修正紀錄:第 2 次修正(回應 64277 巡行規模問題;Rev 2 與 Rev 1 完整原文保留於下方)

本次修正重點(Rev 2 → Rev 3)

⑤ 巡行 DUMP 效能策略(桌面版 vs Android 模擬器)

要點實作做法避免踩坑(防卡死原因)
1. 單主圖/少格聯動切股(忌多圖並開) 只留 1 個主圖(或最多 2×2 聯動格),透過自選股清單快鍵/事件逐隻切換標的,在同一個已暖機的圖表實例內換股。 Android 一頁幾十隻靠單欄文字或輕量 List;桌面版若同時開幾十個 live 小圖表,CEF/Qt 重繪與 FEX 轉譯稅會呈倍數暴衝導致開市卡死。
2. 狀態刷新即讀(取代死等 sleep) 切股後輪詢檢查左上角「標的代碼+時間戳」變動且指標非空(一般 150–400 ms)即刻抽取,毋須每隻固定 sleep(2s)。 大幅縮短單頁巡行時間,同時避免切得太快讀到上一隻股票的殘影資料。
3. 零視覺抽取 + 安全 FEX 參數 讀取優先用 AT-SPI2 或 Guest LD_PRELOAD(drawText/SSL_read);退回 ROI OCR 時只抓左上角小框並關掉動畫/新聞/掛盤側欄。FEX 啟用 Code Cache+HalfBarrierTSOEnabled=1(保留 TSO 防 futex 死鎖)。 把多餘繪圖從 FEX 轉譯管線拿走,保留 CPU 給行情解碼與指標計算。

⑥ 巡行分配與排程設計(分層、休市閘、分片)

分層/機制分配規則配合 N 支指標嘅效果
Tier 1(重點長駐/主標的) 如納指期貨主圖或高分異動股:獨立 1 個固定小窗長駐唔切換,或每 15–30 秒優先插隊掃描。 主標的零切換延遲,唔會被幾十隻冷門股拖慢。
Tier 2(活躍池批掃) 每批一頁/一組(例 20–40 隻),週期 60–180 秒;每批之間保留 300–800 ms 冷卻與隨機抖動(jitter)。 維持現有「時間分隔」節奏,防 CEF/X11 佇列積壓及伺服器頻控。
Tier 3(冷門低頻補洞) 3–5 分鐘掃一次或盤後補掃;利用自訂指標一次輸出對上 N=5..10 支 K 線的特性,靠 (symbol, bar_ts) 冪等去重寫入。 指標輸出 N 支=天然容錯緩衝:就算巡行間隔拉長到幾分鐘都唔會漏棒!
休市閘 + 市場分片(Sharding) 非交易時段市場直接踢出巡行隊列;如多實例擴容只按市場(港股 vs 美期)分片並 taskset 鎖大核(4C 最多 1–2 實例)。 唔燒無謂 FEX 轉譯算力於靜止K線,並防止多實例搶核互卡。
總結:桌面版唔好「同時畫幾十個圖」,而係「1 個圖高速切股 + N=10 棒指標作緩衝 + Tier 1/2/3 分頻巡行」。
一旦後續打通 Guest SSL_read / CDP WS 直取,巡行只需切換訂閱即可收流,徹底免除 UI 重繪瓶頸。

Rev 3 補充紀錄摘要(Markdown)

# Turn Log 64277 — Multi-Symbol Patrol DUMP Scale: FEX Performance & Scheduling Allocation (A38)
- Target Seq: `64277` (`sender=dj_host1`, `sha12=173a9a1f56ec`)
- Question:
  - Previous Android emulator crawler displayed tens of symbols per page, reading the custom K-line indicator across page 1 -> page 2 -> ... continuously with inter-batch delays.
  - How should Desktop (FEX + Futu) adapt this patrol DUMP with respect to ① Performance and ② Allocation / Scheduling?

## ① Performance Optimization for Patrol DUMP under FEX
1. **Never Keep Tens of Live Chart Panes Redrawing Simultaneously**:
   - In CEF/Qt under FEX, every visible live chart pane incurs x86->ARM64 translation tax on timer ticks and software/GL rasterization. Opening 20–40 chart widgets at once will saturate CPU during market open.
   - **Optimal Pattern**: Keep **1 primary chart (or a 2×2 linked grid max)** and cycle symbols via watchlist keyboard/arrow selection (`XTest`/Qt event) within the same warm chart instance—reusing FEX's warmed JIT code cache and memory arena without spawning new renderers.
2. **Event-Driven Settle Instead of Fixed Long Sleeps**:
   - After switching symbol, wait only until the top-left timestamp/symbol header updates and indicator text is non-empty (~150–400 ms typical), then dump immediately.
3. **Zero-Render / Low-Render Text Extraction + Safe FEX Flags**:
   - Prefer `AT-SPI2` or guest `LD_PRELOAD` (`QPainter::drawText` / `SSL_read`); if falling back to ROI OCR, capture only the tiny top-left indicator box via X11 SHM and disable chart animations/news/orderbook sidebars.
   - Enable FEX Code Caching (`ENABLECODECACHINGWIP` / warmed `~/.fex` cache) + `HalfBarrierTSOEnabled=1`. **Caveat (aligning with A43 64273)**: do not blindly force global `TSOEnabled=0` without stress testing, as full TSO disabling can cause futex deadlocks in multi-threaded GUI runtimes.

## ② Scheduling & Allocation Strategy (Replacing Uniform Slow Patrol)
1. **3-Tier Priority Buckets (Dynamic Cadence Instead of Flat Round-Robin)**:
   - **Tier 1 (Pinned / High-Priority, e.g., NASDAQ Futures + Active Leaders)**: Keep pinned in its own dedicated non-switching pane (near real-time, zero symbol-switch churn) or poll every 15–30 s.
   - **Tier 2 (Active Watchlist, tens per page)**: Batch-scan every 60–180 s with deliberate inter-batch pacing (e.g., 300–800 ms cool-down per batch) to prevent X11/CEF frame-queue buildup and server rate limits.
   - **Tier 3 (Cold / Secondary Symbols)**: Poll every 3–5 min (or post-close backfill). Because the custom indicator outputs `N=5..10` recent bars at once, infrequent passes still recover every bar without gaps when deduplicated idempotently by `(symbol, bar_ts)` on `srv.js`.
2. **Market-Session Gating & Sharding**:
   - Exclude closed markets from the active patrol ring so FEX CPU is never burned polling static candles.
   - Only scale horizontally by market shard (e.g., HK shard vs US Futures shard) with strict CPU core pinning (`taskset`) and per-instance limits matching physical big cores (e.g., max 1–2 instances on 4C).
3. **End-State Upgrade**:
   - Once guest `SSL_read` + Protobuf K-line push decoding or CEF CDP WS interception is verified, patrol DUMP collapses from "wait for UI redraw per symbol" to lightweight subscription cycling / pure memory stream ingestion.

以下為 第 2 版(Rev 2,seq=64272)及第 1 版(Rev 1,seq=64269)完整原文,依修正保留規範完整留存:

A38|FEX 優化與 K 線指標/Data Feed DUMP 技術方案(第 2 版)

第 2 版(Rev 2) 日期:2026-11-18 | 新增依據:seq=64272(dj_host1 補充:Android 自訂指標顯示對上 N 支 K 線+OHLCV+成交額)
席位:A38 (A382497) | 修正紀錄:第 1 次修正(回應 64272 補充;第 1 版完整原文保留於頁面下方)

本次修正重點(Rev 1 → Rev 2)

③ 桌面版配合「自訂指標輸出對上 N 支 K 線」舊做法(回應 seq 64272)

環節做法與注意事項相比 Android 爬蟲的優勢
1. 沿用自訂技術指標 原有富途自訂指標公式(輸出對上 5 / 10 支 K 棒之 時間, O, H, L, C, Vol, 成交額)可直接於桌面版圖表套用。桌面版左上角指標文字欄有單行截斷上限,建議改用精簡格式(例 B0:T,O,H,L,C,V,A)或拆成 2–3 條輸出變數,避免第 5–10 支被 ... 截走。 無須重寫指標選棒與時間對齊邏輯,舊爬蟲解析器幾乎可直接沿用。
2. 文字讀取層(三級由優到簡) ① AT-SPI2 無障礙樹:開 QT_ACCESSIBILITY=1(Qt5)或 --force-renderer-accessibility(CEF),以 pyatspi 直接讀文字節點。
② Guest LD_PRELOAD 攔繪字(最精準):寫輕量 x86_64 .so hook QPainter::drawText/FreeType/XDrawString,依前綴濾出指標文字直寫 /dev/shm JSONL。
③ 固定小框 ROI OCR(保底):只截左上角指標矩形(XGetImage 進 /dev/shm)+ 2–3× 放大二值化 + tesseract 數字白名單。
①② 完全免 OCR 誤判(零 8/B、小數點錯位)且不搶佔 FEX CPU;③ 亦只掃極小區域(<15 ms),遠快於全螢幕抓圖。

④ 更好、直接攞到 K 線 Raw Data(免指標字數截斷、免 OpenD)

優先序直接 Data Feed 路徑適用架構(承 A25 63935)優點與實作要點
A(最推薦) Guest LD_PRELOAD 攔 SSL_read+Protobuf 解 K 線 Push libMainApp.so(原生 Qt5 行情連線) 富途桌面版行情走加密 TCP/Protobuf Push。喺 FEX guest 層 hook OpenSSL/BoringSSL SSL_read 取得明文封包,解出 K 線 Cmd 即可直接吐出任意 N 支完整 ts, O, H, L, C, V, Turnover——完全不受視窗遮擋、指標截斷或只拿 5–10 支的限制。
B(若屬網頁圖表) CEF 本機 CDP 攔截 WebSocket/Chart Store FTWebRender(libcef.so) 啟動加 --remote-debugging-port=9222 --remote-debugging-address=127.0.0.1,監聽 Network.webSocketFrameReceived 或直接讀前端 K 線 Array,一次取全量歷史與實時增量。
C(零注入旁路) 本機磁碟快取/SQLite 讀取 ~/.futu 用戶資料目錄 檢查本地已落盤之歷史 K 線檔(先確認最新未收盤 bar 是否僅存記憶體未即時 flush)。

建議雙軌落地次序(今日即可切換)

1. 短期保底(當日上線):保留自訂指標輸出對上 5–10 支(注意精簡欄位免截斷),先查 AT-SPI2 / QPainter::drawText LD_PRELOAD(或固定左上角小框 ROI OCR)直接接回現有爬蟲格式。
2. 並行升級(徹底脫離 UI):花 5 分鐘分別探測 FTWebRender CDP 與 Guest SSL_read 明文結構;一旦解出 K 線 Protobuf/WS 欄位,即切換為純 Data Feed 直吐,一次拿對上 50–200 支且零 UI 渲染負載。

Rev 2 補充紀錄摘要(Markdown)

# Turn Log 64272 — Desktop Compatibility for Custom-Indicator N-Bar DUMP & Direct Data Feed Routes (A38)
- Target Seq: `64272` (`sender=dj_host1`, `sha12=497fde0c42f7`)
- Context:
  - Prior Android crawler read a custom technical indicator on the K-line chart displaying the past N bars (e.g., 5 or 10 bars: timestamp, Open, High, Low, Close, Volume, Turnover).
  - Desktop architecture (`A25` `seq=63935`): `FTNN` launcher -> `libMainApp.so` (Qt5) + `FTWebRender` (`libcef.so` + `libX11` + `libQt5Core`).
  - `seq=64265`: OpenD rejected (zero-cost desktop route only). `seq=64269`: FEX confirmed working for main UI + live stream.

## Q1: Adapting the Android Custom-Indicator N-Bar DUMP Workflow to Desktop (FEX + Linux X11)
1. **Reuse the Exact Same Futu Custom Indicator Script**:
   - The Futu custom indicator formula outputting the last `N` bars (`T,O,H,L,C,V,Amt`) carries over directly to the desktop chart.
   - Because desktop chart top-left overlay lines have character truncation limits, format compactly (e.g., `B0:T,O,H,L,C,V,A;B1:...`) or split across 2–3 indicator output variables so 5–10 bars do not get ellipsized (`...`).
2. **Replace Mobile Screenshot/Accessibility Scraping with Cleaner Desktop Extraction**:
   - **Check 1 (Qt Accessibility / AT-SPI2)**: Test `QT_ACCESSIBILITY=1` + `pyatspi` (or `--force-renderer-accessibility` for CEF). If the top-left indicator label exposes an accessible node, read text directly with zero OCR and negligible FEX overhead.
   - **Check 2 (Guest `LD_PRELOAD` Text-Draw Interception — Best Exact Drop-in)**: Load a tiny x86_64 `.so` via `LD_PRELOAD` inside the FEX guest to hook `QPainter::drawText` (Qt5 `libMainApp.so`) or FreeType/HarfBuzz/XDrawString, filter by indicator prefix/coordinates, and stream structured JSON lines to `/dev/shm/futu_ind.jsonl` or a local FIFO. Zero OCR errors, immune to overlap/DPI scaling.
   - **Check 3 (Targeted Top-Left ROI OCR Fallback)**: Only grab the small top-left rectangle (`XGetImage` / MIT-SHM into `/dev/shm`), upscale 2–3x + binarize, and run `tesseract` with digit/delimiter whitelist (`< 15 ms` per poll, minimal impact on FEX).

## Q2: Better / Direct Data-Feed Methods (Zero-Cost, No OpenD, No Indicator String Truncation)
Ranked by intrusiveness & reliability:
1. **Local Cache / Memory-Mapped Files Inspection (Lowest Overhead)**:
   - Inspect FTNN's user data directory (`~/.futu` / local SQLite / binary cache files) for persisted K-line chunks; note live forming bars may remain in RAM until bar close/flush.
2. **CEF Remote Debugging / WebSocket Frame Interception (If Chart/Quotes Use `FTWebRender`)**:
   - Launch with `--remote-debugging-port=9222 --remote-debugging-address=127.0.0.1` and subscribe to `Network.webSocketFrameReceived` or query the chart JS store via CDP. Directly receives full bar arrays (`N` bars at once, full precision) without UI layout limits.
3. **Guest `LD_PRELOAD` TLS Plaintext (`SSL_read` / `QSslSocket`) + Protobuf Decode (Most Complete Direct Feed)**:
   - Futu desktop receives encrypted TCP/Protobuf market pushes. Hooking OpenSSL/BoringSSL `SSL_read` (or `SSL_write` for requests) inside the guest yields raw unencrypted Futu protocol frames on `/dev/shm` or a local socket; decoding the K-line push `Cmd` gives full history/live bars directly—independent of chart zoom, indicator truncation, or UI rendering stalls.

## Recommended Rollout Order
- **Immediate (Day-1 parity)**: Keep the custom N-bar indicator -> probe AT-SPI2 -> fall back to `QPainter::drawText` `LD_PRELOAD` (or small top-left ROI OCR) so the existing crawler pipeline switches over immediately.
- **Parallel Upgrade**: Run a 5-minute probe on `FTWebRender` CDP and `SSL_read` plaintext dumps; once the K-line Protobuf/WS payload is verified, switch the crawler to direct feed consumption and eliminate UI scraping completely.

以下為 第 1 版(Rev 1,seq=64269)完整原文,依修正保留規範完整留存供對照:

A38|FEX 效能優化與納指期貨圖表指標 DUMP 技術方案

第 1 版(初稿) 日期:2026-11-18 | 來源 Sequence:64269(dj_host1)+ 64265(OpenD 棄用定案)+ 63935(A25 架構核實)
席位:A38 (A382497) | 修正紀錄:第 0 次修正(初版建立,無舊版)

① 現階段 FEX 效能優化方案(針對 ARM64 跑 FTNN/FTWebRender)

優先序優化層面具體做法預期作用與驗證重點
1 TSO 記憶體屏障減稅(最大槓桿) 於 FEXConfig / 環境變數啟用 FEX_HalfBarrierTSOEnabled=1、FEX_VectorTSOEnabled=0、FEX_MemcpySetTSOEnabled=0;視穩定度再實測 FEX_TSOEnabled=0(先以只讀圖表實測無崩潰/無數據錯位)。 ARM64 無硬體 x86 TSO,CEF/Qt 多線程大量屏障係主要轉譯稅;放寬 TSO 通常可降顯著 CPU 開銷。
2 FEX Thunking 直通原生庫 開啟 Host/Guest Thunking(libX11、libxcb、libGL/libEGL、libasound),將 X11/繪圖調用轉交原生 aarch64 庫執行。 免去圖形與 X11 協議封裝的 x86 指令轉譯(與 64264 方向一致,屬可實測項)。
3 大核綁定 + JIT 快取 + UI 減繪 以 taskset 綁定 ARM64 大核;確保 /dev/shm 容量充足免 Qt/CEF 退回磁碟 IPC;只保留目標期貨圖表分頁、隱藏其他報價板與關掉無謂動畫;使用輕量 X11/Xvfb 免去合成器(compositor)。 減少跨核遷移與重繪像素面積,避免開市幀率搶佔數據處理。

② 納指期貨圖表左上角技術指標 DUMP 方案(由準確到最簡)

方案適用前提(先花 1 分鐘探測)實作路徑優缺點
A. CEF CDP 遠端除錯(最乾淨、零 OCR 誤差) 指標區或圖表由 FTWebRender(CEF)渲染(A25 63935 已核實有 libcef.so)。 啟動加 --remote-debugging-port=9222 --remote-debugging-address=127.0.0.1(只限本機),連 WebSocket CDP 讀 DOM/JS 變數或攔截 Network.webSocketFrameReceived。 直接拿到精準浮點數與 raw data feed;若指標畫在 <canvas> 上但有內部 JS 狀態亦可直接讀取。
B. Guest LD_PRELOAD 文字繪製攔截(無誤差通殺) 圖表屬原生 Qt5(libMainApp.so)直接繪製,或 CEF Canvas 不露 DOM。 寫輕量 x86 .so(於 FEX guest 內 LD_PRELOAD),攔截 QPainter::drawText/XDrawString/FreeType・HarfBuzz glyph 呼叫,按左上角座標濾出指標字串。 100% 精準原文與數值,唔使逆向 Futu 加密 TCP 協議,亦無 OCR 誤讀(如 8/B、小數點)。
C. AT-SPI2 讀節點 → 定點 ROI OCR(最易落地兜底) 唔想改啟動參數或注入 LD_PRELOAD。 ① 先試 QT_ACCESSIBILITY=1+pyatspi 讀介面文字;② 若屬 Canvas/點陣自繪,僅對 X11 視窗左上角固定小框(例 400×80 px)用 XGetImage/mss 抓入 /dev/shm,放大 2–3× 二值化後跑 tesseract --psm 6(限定數字+符號白名單)。 全圖截圖慢,但僅截左上角 400×80 px 喺 ARM64 單次 OCR < 15 ms,可立即像 Android 爬蟲般讀出數值。

誠實邊界與建議驗證次序(1 分鐘判別)

1. 檢查圖表視窗係 FTWebRender (CEF) 定 libMainApp.so (Qt Widget):xwininfo -tree / ps aux | grep FT
2. 若見 FTWebRender:先試 --remote-debugging-port=9222(本機回環)睇有冇 WS/DOM 數據流(拿正 data feed)。
3. 若屬原生自繪:優先對左上角固定框做 ROI 截圖 OCR 立即先跑通 DUMP,再按需要補 guest LD_PRELOAD drawText 消除 OCR 誤差。

原始紀錄摘要(Markdown Turn Log)

# Turn Log 64269 — FEX Performance Optimization & NASDAQ Futures Chart Indicator DUMP (A38)
- Target Seq: 64269 (sender=dj_host1, sha12=831015175a7b)
- Context verified from inbox:
  - seq=64265 (dj_host1): OpenD rejected (cost/limits); zero-cost data route only.
  - seq=64269 (dj_host1): Box64 dropped (crashes at main UI); FEX succeeds (main UI + live data stream).
  - seq=63935 (A25): FTNN launcher uses libc/libstdc++; libMainApp.so (Qt5) + FTWebRender (CEF/libcef.so + Qt5Core + libX11).

## Q1: FEX Performance Optimization on ARM64 (Beyond dropping Box64)
1. **TSO Barrier Reduction (Largest FEX multi-thread lever)**:
   - ARM64 lacks native x86 TSO; FEX inserts DMB barriers around memory accesses. For CEF/Qt heavy multi-threading, test `FEX_HalfBarrierTSOEnabled=1` (safer first step) and `FEX_VectorTSOEnabled=0` / `FEX_MemcpySetTSOEnabled=0`, or per-app testing with `FEX_TSOEnabled=0` (fastest, ~15-30%+ uplift in memory-heavy threads, must verify no crash/corruption in Futu).
2. **FEX Library Thunking (Native ARM64 graphics/X11)**:
   - Enable FEX host thunking for `libX11`, `libxcb`, `libGL`/`libEGL`, `libasound` (`FEXConfig` / `ThunkHostLibs` + `ThunkGuestLibs`) so X11/OpenGL/compositing execute as native aarch64 rather than emulated x86.
3. **Code Cache + Core Pinning + Lightweight Display**:
   - Enable FEX JIT/AOT object-code cache if available in the installed FEX build; pin `FTNN`/`FTWebRender` to big/performance Cortex cores (`taskset`) and keep `/dev/shm` adequately sized for CEF/Qt IPC.
   - Minimize UI redraw scope: keep only the target NASDAQ Futures chart window/tab visible, hide unused market tickers/news panels, run bare Xvfb/lightweight WM without compositor.

## Q2: DUMPing Top-Left Chart Technical Indicator Values (or Data Feed)
Ranked from quickest probe to cleanest exact extraction (all zero-cost, local):
1. **Probe 1 — CEF Remote Debugging / CDP (Exact Data Feed / DOM if chart is in FTWebRender)**:
   - If the chart panel is rendered by `FTWebRender` (CEF), launch with `--remote-debugging-port=9222 --remote-debugging-address=127.0.0.1`. Query `http://127.0.0.1:9222/json` and attach via WebSocket CDP (`Runtime.evaluate` or `Network.webSocketFrameReceived`) to extract exact indicator values or raw chart feed JSON/WS frames with zero OCR error.
2. **Probe 2 — Guest `LD_PRELOAD` Text-Draw Hook (Exact String Capture if native Qt/Canvas)**:
   - If the chart is native Qt5 (`libMainApp.so`) or CEF `<canvas>` without DOM nodes, an x86 `LD_PRELOAD` `.so` inside the FEX guest hooking `QPainter::drawText` (or `HarfBuzz`/`FreeType`/`XDrawString`/`pango`) intercepts the exact rendered indicator strings and `(x, y)` coordinates before rasterization—100% exact digits, no OCR, no Futu protocol decryption needed.
3. **Probe 3 — Accessibility Tree (`AT-SPI2`) vs Targeted ROI OCR (Simplest Non-Invasive Fallback)**:
   - First check `QT_ACCESSIBILITY=1` + `pyatspi`/`accerciser` (or `--force-renderer-accessibility` for CEF); if exposed as accessible text nodes, read directly.
   - If painted directly onto bitmap/canvas (invisible to AT-SPI2), crop ONLY the fixed top-left indicator ROI (e.g., ~400x80 px) from X11 (`XGetImage` / `mss` / `ffmpeg x11grab` into `/dev/shm` tmpfs), upscale 2-3x + grayscale threshold, and run `tesseract` (`--psm 6/7`) or `PaddleOCR` on that tiny ROI (<15 ms/frame on ARM64).
   - Note: Direct Futu TCP/TLS feed reverse-engineering is higher-effort due to Futu's proprietary binary/encrypted framing compared to CDP or `drawText` hooking.