PA Agent Project: Systematic Analysis Report
PA Agent (Price Action Agent) is an open-source (AGPL-3.0) desktop AI decision-support tool for discretionary traders, built on Al Brooks' price action (PA) methodology. Unlike screenshot-recognition tools, it analyzes structured K-line data plus precomputed features, and it deliberately does not connect to brokers or place orders — it only outputs "plan-level" recommendations through a PyQt6 GUI with real-time charts and an AI sidebar.
Key Points
- Design philosophy: Encode Brooks PA expert knowledge into external prompt files and decision trees; use LLMs for "reading the market + single decisions"; use deterministic code for data preprocessing, routing, validation, and safety gates — human-AI collaboration, not black-box auto-trading.
- Architecture: Layered design with an Orchestrator pattern and explicit dependency injection via
AppContext.bootstrap()(Composition Root), coveringconfig/,data/,ai/,orchestrator/,gui/,records/,indicators/,notify/,demo/, andutil/packages. - Three-part structure: externalized knowledge (
prompt_engineering/*.txt, 29 files), program constraints (precomputed features, decision-node engine, strategy router), and two-stage constrained LLM inference with strict JSON schemas. DataSourceABC with factory:MT5Source(default, Windows),TradingViewSource(cross-platform tvDatafeed), plus hidden A-share and yfinance sources.- Immutable
KlineFrame(frozen dataclass): bars newest-first (seq=1= latest closed bar), EMA20/ATR14 warmed up on older buffers, snapshot timestamp. Charts freeze to closed-bar-only snapshots matching what the AI receives. RefreshLoopQThread fetches at configurable intervals (default 1s) with overlap prevention and exponential backoff.- PromptAssembler (~1900+ lines) compiles on-disk Brooks knowledge plus runtime market data into LLM-consumable task packages; handles multi-provider quirks.
- Clients: OpenAI-compatible API (DeepSeek etc.) by default;
openclaw_cs*models route toCursorSdkClient. Streaming, CancelToken, KV-cache hit-rate stats supported. - Five-category validation (syntax / missing field / illegal value / plain text / provider error), pipeline: fence stripping → JSON extraction → truncation repair → jsonschema → business rules → optional coherence checks.
- Auto-retry with anti-cheating: format errors retry with feedback; immutable-field tampering detected; quota errors never retried.
- Decision continuity guardrails: prevent same-structure-level reversals within 3 bars, stale limit orders, and continuing invalidated plans — classic guardrails against LLM "forgetfulness/impulsiveness".
- Three QThreads (main UI, refresh, analysis worker) communicating via
pyqtSignaland a lightweightEventBus;decision_flow_viz.pyrendersgate_trace/decision_traceas an interactive animated decision tree. - Every analysis is persisted as a full
AnalysisRecord(prompts, responses, parsed JSON, strategy files, experience snippets) torecords/pending/; API keys are masked.experience/provides a lightweight file-based RAG (no vector DB) injecting top-N historical cases into Stage 2. FreeChatSessionsupports follow-up Q&A anchored to a completed record, kept separate from the task-mode pipeline.- Testing: ~100+ files across unit, property (Hypothesis), integration, e2e, and live tiers; CI on Windows + Python 3.11; dedicated regression tests for prompt files, router determinism, and schemas.
Core Design Ideas
Hybrid Intelligence: Node Permission Model
decision_nodes.py defines a fine-grained authority model:
| Node Type | Meaning | Examples |
|---|---|---|
| LOCKED_NODES | Program-locked, AI cannot override | 1.1 (data sufficiency), 9.1 |
| AI_PRIMARY_NODES | AI decides, program fills gaps | 1.3, 2.5 |
| OVERRIDABLE_NODES | AI may override with override_reason | 2.3, 2.4, 11.x |
| SAFETY_GATE_NODES | Short-circuit on failure | 1.1, 10.3, 14 |
This embodies "trust neither pure LLM nor pure rules": objective nodes are program-anchored, contextual nodes go to the model, with traceable override records.
Two-Stage Pipeline
TwoStageOrchestrator.submit() runs:
1. Preflight gate — data sufficiency check.
2. Stage 1 (market diagnosis) — outputs cycle_position, direction, detected_patterns, gate_trace, gate_result; gate_result=proceed is a hard gate into Stage 2.
3. Strategy routing — route_strategy_files() loads only the minimal necessary playbook files (token economics), including Brooks nested analysis (recent_spike overlay) and pattern stacking (wedge, MTR, barbed wire). extreme_tr/unknown maps to an empty list, meaning "don't trade".
4. Stage 2 (single-trade decision) — outputs decision (trade/wait/reject), decision_trace, and three prices (entry/stop/target) if trading.
5. Incremental analysis — when prior records exist and only a few new bars arrive, Stage 1 runs incrementally with prior context, saving tokens and preserving continuity; falls back to full analysis on misalignment.
Brooks Philosophy Engineering
Global prompts enforce four thinking modes — spectrum (spike→extreme TR continuum), probability (most reversals fail in trends; most breakouts fail in ranges), inertia (Always In default continuation), and nesting (higher timeframe for direction, lower for entry).
Data Layer
AI Layer and Validation
GUI, Persistence, and Testing
Strengths and Trade-offs
Strengths: full auditability and reproducibility; editable knowledge without Python changes; systematic handling of LLM unreliability; token economics (routing, incremental analysis); schema contracts and strong tests; clear product boundary avoiding auto-trading liability.
Trade-offs: high complexity and steep learning curve; Windows-centric (MT5); a 4000+ line MainWindow needing further extraction; minor cross-source indicator consistency caveats; AGPL compliance needed for commercial closed-source integration.
Design Patterns Present
Dependency injection / Composition Root, abstract factory, strategy, orchestrator, immutable value objects, observer/EventBus, pipeline-with-gates, specification (JsonValidator), anti-corruption layer (normalizers), and knowledge externalization.
Conclusion
PA Agent is not a "ChatGPT wrapper for chart-watching" — it is an engineering realization of Al Brooks' price action methodology as a verifiable, routable, incremental, auditable desktop analysis system: structured market data + program-computed features + externalized domain knowledge → two-stage constrained LLM inference → strict JSON contracts + hybrid decision nodes + multi-layer validation → human-collaborative trading plans. It offers a fairly complete reference implementation for prompt routing, schema validation, program/AI authority division, and incremental analysis continuity.