v2 原始設計紀錄(turn_log_64272_dump_n_bars.md)
# Turn Log 64272 — Desktop Compatibility with "Last-N-Bars Custom Indicator" DUMP & Direct Data Alternatives (A38)
- Target Seq: `64272` (`sender=dj_host1`, `sha12=497fde0c42f7`)
- Follows: `seq=64269` (`FEX` locked in, `Box64` dropped), `seq=64265` (`OpenD` dropped, zero-cost route only), `seq=63935` (A25 verified `FTNN` launcher + `libMainApp.so` Qt5 + `FTWebRender` CEF).
## 1. Key Shift Revealed by seq=64272
Previously in Android:
- A custom Futu indicator formula prints the **last N bars (e.g., N=5 or N=10)** of `(Time, Open, High, Low, Close, Volume, Turnover)` directly onto the K-line chart indicator area.
- The crawler reads those displayed strings to reconstruct the K-line window (getting N bars per poll automatically fills cross-minute gaps without losing bars).
Why this matters on Desktop (`FTNN` under `FEX` on ARM64):
1. **70+ numbers per frame (10 bars × 7 fields)**: Naive screen OCR on 5-10 lines of dense decimals is fragile (decimal-point / `6` vs `8` errors corrupt bars, line-wrap/truncation in top-left corner, and screenshot+Tesseract burns CPU during market open).
2. **Hidden advantage of the custom indicator**: `FTNN` itself already decrypts Futu's proprietary protocol, aligns contract/exchange timestamps, and computes exact floating-point `O/H/L/C/V/Turnover`. So hooking the *rendered text string* right before rasterization gives **already-decrypted, exact N-bar data without reversing Futu's binary protocol**!
## 2. How to Match This Exact Workflow on Desktop (`FTNN` + `FEX`)
### Route A (Recommended Direct Upgrade to Android Crawler): Guest `LD_PRELOAD` Text Hook → `/dev/shm` → Native ARM64 Python
- Keep your exact Futu custom indicator formula, adding a short magic prefix + compact delimiter (e.g. `DMP|<tf>|t0,o0,h0,l0,c0,v0,a0;t1,...`).
- Check with `QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1` + `pyatspi` first (1-min check; custom-painted charts usually don't expose indicator text to AT-SPI, only toolbar widgets).
- Load a tiny x86_64 `.so` via `LD_PRELOAD` inside the FEX guest hooking `QPainter::drawText` (in `libQt5Gui.so.5`, mangled symbols `_ZN8QPainter8drawTextE...`) and/or `XftDrawStringUtf8` / `SkCanvas::drawSimpleText` (if CEF).
- Whenever the intercepted UTF-8 text starts with `DMP|`, append a JSON/line record into `/dev/shm/ftnn_kline_dump.ndjson` (or Unix domain socket) atomically.
- **Native ARM64 Python** (outside FEX!) tails `/dev/shm/ftnn_kline_dump.ndjson`, parses the N bars, deduplicates by bar timestamp, and feeds V1/V2/V3 directly—**zero OCR errors, zero screenshot overhead, zero FEX tax on Python**.
- **Bonus FEX speedup**: Because `LD_PRELOAD` captures the string before pixel rasterization, you can shrink the chart window / hide orderbook & news panels to cut X11/OpenGL redraw cost during market open (just verify the chart stays active so indicator recalculation runs).
### Route B (Fallback if `LD_PRELOAD` symbol mismatch): Dedicated Export Panel / Compact Window + Fixed Font / Template Match
- If indicator text is split across multiple `drawText` calls (e.g. one label per `DRAWTEXT` / `DRAWNUMBER`), collect by `(y, x)` coordinates in the hook or pack N bars into fewer formatted `STRCAT` lines; if purely falling back to X11 capture, crop only the indicator sub-region via `XShmGetImage` into `/dev/shm` and use fixed-font glyph matching rather than generic OCR.
## 3. Are There Better Ways to Get Data Directly (Zero-Cost, Without Reading Chart Pixels)?
Comparison of 4 non-OpenD direct-data routes (must run 1-minute probe on live FEX `FTNN` to pick):
1. **Local Cache / Disk Files (`lsof -p <FTNN_PID>`)**:
- Probe whether `FTNN` writes K-line history into local SQLite / LevelDB / `.dat` files under `~/.local/share/` or `~/.config/`.
- *Catch*: Historical completed bars often exist in local cache, but the **live current/forming bar** is usually buffered in RAM and flushed slowly/periodically—verify flush latency before relying on it for real-time 1m bars.
2. **CEF Remote Debugging (`--remote-debugging-port=9222`, `127.0.0.1` only)**:
- Only works if the NASDAQ futures K-line chart renders inside `FTWebRender` (CEF) rather than `libMainApp.so` (Qt5). If inside CEF, `Network.webSocketFrameReceived` or JS chart state yields exact bars directly.
3. **TLS / Socket Hook (`SSL_read` / BoringSSL) or Local Proxy**:
- Captures raw network frames before UI rendering (highest theoretical throughput, allows even headless/minimized UI if data still streams).
- *Catch*: Futu's desktop quote protocol typically uses proprietary framing/encryption/Protobuf; requires reverse-engineering message IDs and price scaling (`1e3`/`1e9`) before use.
4. **Conclusion / Best Engineering Trade-off**:
- **Short-to-medium term (fastest reliable win)**: Keep the **last-N-bars custom indicator** + **Guest `LD_PRELOAD` `drawText` hook → `/dev/shm` → ARM64 Python**. It preserves 100% of your existing Android indicator logic & N-bar gap recovery while eliminating OCR completely.
- **Parallel 1-min probe**: Check `xwininfo` (Qt vs CEF) + `lsof` (local cache flush latency) + `nm -D libQt5Gui.so.5 | grep drawText` (exact symbol for the `LD_PRELOAD` hook).
① 現階段 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.