PANDORA — Technical spec · trading agent (for the dev)
Spec for the dev who will build the agent. Goal: costable. Closes the gaps found in the audit (algorithmic glossary, data schemas, score formula, anti-overfit protocol, feasibility). Method = academy-notes + greeks-bible-reference. Vision/ask = Vision Brief. The formulas/weights below are an explicit v1 to calibrate, not fixed laws — but they exist (a dev can start from there).
0.0 Vision, phasing & golden rules (framing — read first)
PANDORA is not a trading robot. It is a deterministic multi-source decision engine, augmented by an LLM (peripheral), that industrializes a human trading method at scale — 7% human coverage → 100% machine, without degrading quality. An augmented quant decision system project; AI is a component, not the core. Golden rule: before the autonomous agent, we build the best scanner in the world. V1 scope & architecture: V1-BUILD-SCOPE.
3 layers, never to be mixed: V1 Scanner (the brain, deliverable in 8-10 weeks — includes the gamma squeeze detector §6.3 + rotation by family §6.2: these are method setups, not companion work) → V2 Companion (portfolio risk/discipline/calendar/explanatory LLM) → V3 Agent (memory/IBKR/execution/learning).
Golden rules (non-negotiable): 1. The LLM NEVER decides. Deterministic = perceives→filters→scores→ranks. LLM (V2) = explains / challenges / summarizes only. 2. In V1 we LOG, we do not learn. The moat = the proprietary decision dataset, not learning (V3). 3. No broker execution in V1. It is a decision engine, not a trading robot. 4. Every setup comes out EXPLAINED (contributions per feature, §5) — a score without the "why" is unusable. 5. GEX = vulnerability, NEVER direction. GEX = throttle/regime/de-risk (+ squeeze fuel); direction comes from structure/trend/charts. We never code GEX as a directional entry signal. (Touchstone: academy-notes ⭐.)
0. Product decisions (revised after CTO feedback — June 2026)
| Topic | Decision |
|---|---|
| Product | Decision engine / copilot that industrializes the method at scale. Autonomy is the roadmap (V3), not the MVP. |
| Data | UW + Skylit + Trading Volatility, all 3 as soon as possible (degraded start on 2 while waiting for the Skylit API). |
| MVP (V1) | Deterministic scanner: 500+ tickers → features → rules (incl. gamma squeeze §6.3 + family rotation §6.2) → explained score → top 10 → dashboard → journal. Without LLM decider, IBKR, memory, coach, portfolio, calendar. |
| TA (V1) | Deterministic on OHLC (S/R, trend via Price>SMA50>SMA200 / HH+HL / breakout). LLM-vision review = V2. |
| LLM | V2, outside the decision path: explains / challenges / summarizes. |
| Learning | V1 = logging (proprietary dataset). Weight recalibration / LLM memory = V3. |
| Autonomy / execution | Hybrid IBKR = V3 (paper→live). Out of MVP. |
| TA annotation (Léo) | annotates TradingView charts → labels for the dataset (feeds the TA-vision in V2+). |
| Discipline | Every score/strategy goes through the gauntlet (§7) before deployment. |
| Team | 1 senior full-stack Python dev + founders, multiplied by AI. Léo + Gab = product/method/validation. 2nd profile only if a specific bottleneck proves it. |
0.1 Data plan & kickoff
Sources = UW + Skylit + Trading Volatility (Léo already subscribes to UW + Skylit → zero marginal cost; TV via tv-mcp,
free tier available). All three behind an abstraction layer (§2) → we start on what is accessible
(UW + TV) and plug in SkylitProvider when the Skylit API ships, without touching the engine. Honest constraint:
Skylit has no public API yet → rich Skylit data is gated on its release; we run degraded on 2 sources meanwhile.
While waiting for the Skylit API — $0 engine sandbox: prove the pipeline (deterministic engine + quality_score §5 +
journal §3) on tv-mcp in demo mode (no key, no subscription), which serves real GEX data. This is
not production data — it is the test bench that validates scoring/journal work before the Skylit API exists.
1. uvx tv-mcp (or hosted remote https://tv-mcp-...run.app/mcp, streamable-http).
2. Plug TradingVolatilityProvider behind the §2 interface; map the tools (§2.1).
3. Run the engine on the 8 demo tickers → validate the Talon template + the journal.
4. When the Skylit API ships: SkylitProvider (same interface) becomes the production source. tv-mcp stays the backup
adapter if the Skylit schedule slips.
Verified on 19/06/2026 (demo server, no key):
tools/listreturns the 16 tools announced (get_ticker_state,explain_ticker,get_market_structure,get_signals,get_levels,get_series,get_gamma_curve,get_gamma_by_expiration,get_gex_by_strike,get_options_volume,rank_top_setups,run_screener,get_trade_setup,list_capabilities,server_info,get_auth_status). Calls tested:get_ticker_state AAPL→ expected move + IV sigma wings + gamma structure (max_gamma_strike, flip);get_gex_by_strike AAPL→ real per-strike GEX (e.g. strike 250: call 952 965 / put −2 053 066 / net −1 100 101). The per-strike data needed bymap()really comes out, for free —get_series(history) is still to test for the §7 backtest. Enough to prove the engine without waiting for the Skylit API.ToS: internal use (Léo's personal trading) = the providers' personal/non-commercial scope (OK). Future commercialization would trigger a commercial/redistribution license (TradingVolatility has a dedicated tier; Skylit to confirm). To anticipate, not a blocker.
0.2 What the agent EXECUTES — the V1 flow (read before the components)
The concrete sequence, in order. This is the job. Sections §2-§6 detail each building block.
PHASE 0 · Market read (1× in the morning)
Reads the global regime — trinity SPX/SPY/QQQ, GEX/DIX dark-pool, VIX + term structure (contango/backwardation) → directional bias of the day + risk-on/off. This read sets the aggressiveness of everything else (throttle) and is shown at the top of the dashboard. → MarketRead (§3).
PHASE 1 · Per ticker (over 500+) 1. Ingests: per-strike GEX/VEX maps, OI/ΔOI, flow, dark pool, IV (rank/term), OHLC, short interest/CTB. 2. Reads the map: King Node, floor, ceiling, pivot (gamma flip), air pockets, gatekeepers · +/−gamma regime · day type. 3. Qualifies the nodes: real vs hedge (ΔOI), fresh vs delivered (taps). 4. Detects setups — 3 categories: - a · Structure/method: pattern (reverse rug…), price at a fresh extreme in discount (OTE), RR≥3:1, confluence (aligned dark pool, GEX×VEX, trinity). - b · Gamma squeeze pending (§6.3). - c · IV-expansion into earnings (separate category — earnings 7-12d, IV rank↑, inverted term → capture the IV ramp; see iv-expansion). 5. Builds the plan — intraday first, extendable to swing: direction (call/put), entry (node tap/OTE), stop (1 node beyond), node-to-node intraday targets + swing target if the level holds, DTE. 6. Score 0-100 + the why (contributions per feature §5), aligned with the day's bias (phase 0). 7. Family tag (§6.2).
PHASE 2 · Cross-universe 8. Aggregates by family → hot families / families in rotation (§6.2). 9. Gates (RR, midpoint, hedge-only, regime against §6) + ranking → top 10 (consistent with the day's bias). 10. Dashboard (market read + top 10 by family) + logs every decision → dataset (§7).
1. Architecture
Data adapter (interface, swappable provider: tv-mcp/TradingVolatility [interim, available] · Skylit [target] · UnusualWhales/ORATS)
→ DataBundle{ticker} : map nodes, dark pool, flow, IV, OI(+ΔOI), price+history
↓
Deterministic engine (per ticker, parallel, ~750 tickers):
map_read → node_validity → flow/OI → clean+RR → method filters → confluence → quality_score
↓
LLM arbiter (top-N only, ANNOTATOR not decider): read + flags; can NOT override the gates
↓
Output: ranked setups (Talon template) → cockpit + journal (DB)
↓
Memory loop: decision+outcome → weight recalibration (walk-forward, frozen baseline mandatory)
↓
Macro gate (PANDORA regime + VIX term structure) = global throttle
Principles: deterministic first (fast/reproducible/free over ~750); LLM only as top-N arbiter; abstract data (no lock-in); idempotence (same inputs → same outputs, except the LLM which is isolated); score model versioning (every setup tags the weight version that produced it).
1.1 Software architecture (module tree)
pandora/
adapters/ # uw/ · skylit/ · tv/ (external I/O, swappable)
core/ # ⚠ 100% PURE PYTHON — zero API, zero LLM, zero broker
features/ # map_read, nodes, fresh/delivered, OTE, RR…
rules/ # patterns (reverse_rug…), gamma_squeeze, iv_earnings, trinity
scoring/ # quality_score + explainability (contributions)
market/ # market read (bias/risk-on-off, throttle)
filters/ # hard gates
engine.py # orchestrates per ticker → Setup
families/ # tag + rotation (familles.csv + aggregation)
journal/ # decisions + outcomes → dataset (append-only DB)
orchestrator/ # scheduler (daily run), parallelism ~750 tickers
llm/ # PERIPHERAL: generate_explanation(setup), review_top() [V2]
portfolio/ # sizing, risk, caps [V2]
execution/ # ibkr/ [V3]
api/ ui/ # cockpit / dashboard
Non-negotiable architecture rule: core/ is testable without network (deterministic, idempotent). Adapters, the LLM, the broker and the UI are peripheral layers plugged around it — never inside core/. That is what makes V1 deliverable, testable and reproducible.
2. Data adapter interface (to implement per provider)
class DataProvider(Protocol):
def universe(self) -> list[str]: ... # ~750 tickers
def map(self, ticker: str) -> Map: ... # GEX(/VEX) nodes per strike
def dark_pool(self, ticker: str) -> list[DarkPoolPrint]: ...
def flow(self, ticker: str) -> FlowSummary: ... # call/put, sweeps, blocks, net premium
def iv(self, ticker: str) -> IVData: ... # iv, iv_rank, iv_percentile, term structure
def oi(self, ticker: str) -> dict[float, OI]: ... # OI + ΔOI per strike
def prices(self, ticker: str, lookback_days=180) -> PriceSeries: ...
Implementations: SkylitProvider (production source — active subscription, target API), TradingVolatilityProvider
($0 engine sandbox + backup, see §2.1), UnusualWhalesProvider / OratsProvider (alternatives). Error
handling mandatory: if a source is missing
on a ticker → degraded score + missing:<source> flag, never a crash; if >X% of tickers fail in the run →
alert, run marked partial.
2.1 Reference adapter: tv-mcp (TradingVolatility) — available now
Key finding: TradingVolatility publishes an open-source MCP server (tv-mcp, PyPI, MIT license, v0.2.0
June 2026) that wraps its v2 API and exposes directly to an LLM agent per-strike GEX, gamma flip, levels,
flow, OI, IV and a cross-ticker ranking. Keyless demo mode on 8 tickers (AAPL, VIX, META, AMZN…) →
we can prototype the full agent today, without a subscription. Auth = Authorization: Bearer <key> or
X-Api-Key (env TV_API_KEY), stdio transport (local agent) or HTTP+SSE (hosted).
tv-mcp → our interface mapping (the adapter translates, the engine stays agnostic):
| Our need | tv-mcp tool |
|---|---|
| map() per-strike GEX nodes | get_gex_by_strike (net GEX + call/put contributions), get_gamma_curve |
| pivot / floor / ceiling / max pain / expected move | get_levels (views json/tradingview/tos) |
| regime + assembled read | get_market_structure, explain_ticker |
| iv() / oi() | get_ticker_state (include CSV), get_options_volume (+ include=iv) |
| prices() historical series | get_series (metrics CSV, window 30d→2y) |
| universe + cross-ticker pre-filtering | rank_top_setups, run_screener |
Honesty (important tradeoff): tv-mcp already provides a generic opportunity score (
rank_top_setups) and a raw plan (get_trade_setup: bias/entry/stop/target) → the data AND the base ranking are commoditizing. Consequence for the scope: we NO LONGER have to rebuild the GEX maths (hard point #2 of the brief largely lifted) nor reinvent an API. The tv-mcp ranking does NOT replace our score: it serves as a pre-filter (reduce ~750 → top-N candidates at near-zero cost), then our quality_score (§5) + our method gates (§6) re-score according to the Skylit doctrine (real-vs-hedge ΔOI, fresh-vs-delivered, OTE, RR, Pika/Barney patterns) — absent from tv-mcp. The differentiator = the method overlay + the learning loop (§7), not the feed. That is what makes the project more costable (less to code) and the edge sharper (what we build is what nobody else has).
2.2 Features → Unusual Whales endpoints map (verified 23/06/2026)
Programmable production source = Unusual Whales (REST
https://api.unusualwhales.com,Authorization: Bearer, OpenAPI available, ~109 endpoints, official MCP). Skylit has NO public API (verifieddocs.skylit.ai: core-concepts yes, API no) → Skylit stays the method/UI layer (Heatseeker GEX+VEX), not a data source. UW feeds the engine; tv-mcp = sandbox/backup. Every §5 feature has a real endpoint:
| Engine need | UW endpoint | Key fields |
|---|---|---|
map() per-strike GEX/VEX (King/floor/ceiling/pivot) |
/api/stock/{t}/greek-exposure/strike · /spot-exposures/strike · /greek-exposure/strike-expiry |
gamma/delta/vega per strike, $ per 1% |
| aggregated gamma regime + flip | /api/stock/{t}/greek-exposure · /spot-exposures (per minute) |
net GEX/DEX/vanna/charm |
flow() (sweep/block, opening/closing, side) |
/api/stock/{t}/flow-recent · /api/option-trades/flow-alerts · /full-tape/{date} |
premium, ask/bid side, size, tags |
oi() + ΔOI (real-vs-hedge, oi_build) |
/api/stock/{t}/oi-change · /api/market/oi-change |
ΔOI per strike (sorted desc) |
dark pool (darkpool×node interaction) |
/api/darkpool/{t} · /api/darkpool/recent |
price, size, premium |
| net premium by family (rotation §6.2) | /api/net-flow/expiry |
net prem by moneyness/expiry/tide |
iv(): IV, IV rank, term structure |
/api/stock/{t}/iv-rank · /volatility/term-structure · /volatility/realized · /volatility/stats |
IV, rank, ATM term, RV |
| max pain | /api/stock/{t}/max-pain |
per expiry (120d) |
| short interest / DTC / FTD (gamma squeeze §6.3) | /api/shorts/{t}/interest-float · /ftds · /volume-and-ratio · /data |
SI%, float, FTD, borrow/rebate |
| universe pre-filter (~750 → top-N) | /api/screener/stocks · /screener/option-contracts |
50-80+ filters |
Scope consequence: the 13 features of §5 and the squeeze inputs (§6.3) are all covered by real UW endpoints — including short interest/DTC (the only gap in the previous sources). The
UnusualWhalesProvideradapter (§2) maps this table; the engine stays agnostic. Exact schemas to freeze against the OpenAPI at dev time (/api/openapi).
3. Data dictionary (schemas)
@dataclass
class Node: strike:float; gex:float; vex:float|None; oi:int; d_oi:float; sign:str # "+gamma"|"-gamma"
@dataclass
class Map: ticker:str; spot:float; asof:str; nodes:list[Node]; regime:str # "+gamma"|"-gamma"|"mixed"
@dataclass
class OI: oi:int; d_oi:float # open interest + ΔOI (day over day) per strike
@dataclass
class DarkPoolPrint: price:float; size_usd:float; ts:str; growing:bool # DP print: level, $ size, timestamp, growing?
@dataclass
class FlowSummary: call_prem_usd:float; put_prem_usd:float; net_prem_usd:float; sweeps:int; blocks:int # aggregated flow, signed net premium (>0 = call-dominant)
@dataclass
class IVData: iv:float; iv_rank:float; iv_pct:float; term_structure:str # iv 0-1, rank/pct 0-100, term: "contango"|"backwardation"|"flat"
@dataclass
class PriceSeries: index:list[str]; open:list[float]; high:list[float]; low:list[float]; close:list[float] # daily OHLC, index = ISO dates
@dataclass
class MarketRead: # PHASE 0 — bias of the day (§0.2), shown at the top of the dashboard, global throttle
asof:str; bias:str; risk:str # bias "long"|"short"|"neutral" ; risk "on"|"off"
trinity:str; gex_dix:str; vix:float; term_structure:str # SPX/SPY/QQQ alignment; GEX/DIX regime; vol
@dataclass
class Setup:
ticker:str; family:str; asof:str; direction:str # family = theme/sector; direction "long"|"short"
setup_type:str # "structure" | "squeeze" | "iv_earnings" (§0.2 phase 1.4)
entry_ote:float; stop:float; targets:list[float]; rr:float
target_swing:float|None # intraday plan (targets) extendable to swing if the level holds
timeline:str # "intraday" → "swing"
quality_score:float; verdict:str # "GO"|"WATCH"|"PASS"
conviction:float; uncertainty:float # conviction 0-1 WITH its uncertainty (§6.4.4)
days_to_earnings:int|None; near_opex:bool; macro_event:str|None # catalysts (§6.4.3)
checks:dict[str,str]; weights_version:str; read:str
@dataclass
class Decision: setup:Setup; human_action:str; ts:str
@dataclass
class Outcome: ticker:str; asof:str; realized_r:float; hold_days:int
@dataclass
class Book: # portfolio state (§6.4.1)
positions:list[dict]; risk_used:float; exposure_by_family:dict[str,float]
net_exposure:float; drawdown:float; consec_losses:int # → circuit breaker / caps
Journal = append-only JSONL/DB. Explicit mapping (no spread). Every setup tags weights_version.
4. Algorithmic glossary (executable definitions, v1)
- King Node =
argmax(|node.gex|)over the relevant strike window (spot ±X%). - Floor =
argmax(|gex|)among nodesstrike < spot; Ceiling = same withstrike > spot. - Pivot (gamma flip) = strike where cumulative GEX changes sign (interpolation between 2 adjacent strikes).
direction_bias = "long" if spot > pivot else "short". - Regime = sign of net GEX at spot (
+gammaif net>0 else-gamma);mixedif |net| is below a threshold. - Real vs Hedge:
real = d_oi > +oi_threshold over N days(growth);hedge = far-OTM AND d_oi decreasing. Parameters: oi_threshold, N (day over day or 3-5d) — to calibrate. - Fresh vs Delivered: count the taps (price passes through the node's deflection zone: ±$0.5 QQQ/SPY, ±$5 SPX) over recent history.
fresh = 0 tap, probability ~80%/66%/33% at the 1st/2nd/3rd. - Price pivots (for the OTE): swing highs/lows via fractals/ZigZag (lookback param). Discount = retracement of the last swing into the OTE zone (fib 0.5–0.786, sweet spot 0.618–0.65) →
entry_ote. - RR =
(target − entry) / (entry − stop)withtarget= next real node / −gamma pocket reachable via an air pocket,stop= 1 node beyond the extreme. Gate: rr ≥ 3.0 (2.0 floor). - Air pocket = strike segment where
Σ|gex|< threshold (low exposure between 2 nodes). - Patterns (deterministic booleans — layout of gamma signs around spot; thresholds
sto calibrate):
reverse_rug (bullish): spot > pivot AND floor_gex > +s AND ceiling_gex < -s # +gamma below / −gamma above, spot holds
rug (bearish): spot < pivot AND ceiling_gex > +s AND floor_gex < -s # +gamma above / −gamma below, rejection
pika_cloud (pinned): +gamma density around spot > threshold → gravity well, mean-revert
beach_ball: |spot − node| crossed then reclaimed (overshoot of a node) → reversion, NOT breakout
whipsaw (no-trade): −gamma regime AND conflicting trinity signals
rainbow (no-trade): no dominant node (max|gex| / Σ|gex| < threshold) → no bias
Each pattern = a testable -> bool function. Charts-first can be coded too: Price>SMA50>SMA200 OR HH+HL OR breakout of an annotated level.
5. Quality score (the central piece — v1 spec)
Form: 0-100 score = weighted sum of normalized features, with explicit interaction terms (confluence is NOT purely additive — e.g. dark pool aligned with a node = cross term).
raw = Σ_i w_i · f_i (+ interaction terms w_jk · f_j · f_k)
score = 100 · sigmoid(raw) # bounded 0-100
Features f_i (normalized 0-1 or z-score, closed v1 list): | feature | definition | sign | |---|---|---| | discount | OTE depth / proximity to the pullback MA (EMA55, otherwise EMA144) — max when price taps the MA (§5.1) | + | | trend | daily EMA stack 13/21/55 — invariant EMA21>EMA55 = live trend (§5.1) | + long / − short | | rr | clamp(rr/4, 0, 1) | + | | node_quality | dominant King + clean floor/ceiling (King's share of |gex|) | + | | fresh | 1 if 1st tap, 0.5 if 2nd, 0 if 3rd+ | + | | real_node | normalized ΔOI (real>0, hedge<0) | + | | flow_align | call/put net premium in the setup's direction (z-score) | + | | oi_build | ΔOI at the target strike | + | | iv_gate | long: IV↓ → +, short: IV↑ → + | + | | darkpool×node | interaction: DP level aligned with a node (±tol) | ++ | | index_support | macro regime + SPY/QQQ trend in the direction | + / penalty if against | | pattern | rug/reverse-rug = +, whipsaw/rainbow/midpoint = strong penalty | ± | | gamma_squeeze | composite pre-squeeze score (§6.3), asset & family | + (long/call) |
5.1 · trend & discount — daily EMA stack 13/21/55 (locked 07/07/2026)
Master invariant: EMA21 > EMA55 = "live trend". We only look for LONGS if true. Two entry profiles:
- Wave 3 · trend-follow: EMA13 > EMA21 > EMA55 stacked → enough (no need to wait for price ≥ EMA13). trend strong +, discount low (price extended). Stop trailed on the EMA21 + structure (exit on close < EMA21 AND break of the last higher-low).
- Wave 2 / 4 · pullback: EMA21 > EMA55 held + price that taps the EMA55 (primary target) or the EMA144 (deeper flash dip). trend + (structure intact), discount high (price glued to the MA = entry zone). Risk floor = just below the tapped MA.
- Bear · mirror: EMA13 < EMA21 < EMA55 (reverse stack), price below all 3 → trend negative → §6 "trend-against" gate blocks the long; shorts eligible.
Structural invalidation (invalidation field of the notification): EMA21 crosses below EMA55 (the trend dies) OR acceptance below EMA144/233.
Confluence = "the extra" (cross term, NOT additive): when the pullback MA coincides at the same price with a GEX node (→ node_quality↑), a horizontal S/R, or a dark pool (→ darkpool_aligned↑), the darkpool×node term (w=1.2) compounds quality. The MA gives the structural WHERE; Skylit stacked on top = multiplicative confirmation.
Reference MAs (Léo's setup): daily EMA 13/21/55/144/233 + daily SMA200 + weekly EMA21. A single set of MAs drives entry, stop AND invalidation — deterministic.
5.2 · Flow — signed options flow (the WHO / WHEN)
Detail: flow-layer-reference.md. The §5 score has two halves — the WHERE (structure §5.1 + nodes) and the WHO (signed flow). Flow features: flow_align (signed net premium, aggressor), real_node/oi_build (ΔOI real vs hedge), darkpool_aligned (interaction). Flow pulls the trigger at the OTE tap ("buyers are coming back"). v1 mode = score contributor + config flag to promote it to a hard gate post-gauntlet. Discipline: nothing directional without |t| ≥ 2 OOS.
5.3 · Chart-first — HTF horizontal S/R (the chart leads, GEX confirms)
Detail: chart-first-levels-reference.md. Direction & levels come from the CHART: EMA structure (§5.1) + HTF horizontal S/R (daily/weekly swing H/L, S/R flips, round numbers, consolidation edges). GEX/VEX/flow confirm (a wall at the level? an air pocket below?) — never the origin of direction (touchstone). The HTF S/R anchors the node → strengthens node_quality + the darkpool×node cross term + adds an sr_confluence check. Works both ways: support+GEX = long; resistance+GEX = short/no-long. E.g. IBM: 300 = HTF resistance (S/R flip) × GEX King node −$2.68M ★ → rejection, air pocket down to ~292.5 (negative GEX).
Target — and anti-leakage (critical): the score predicts the realized ex-post R, measured at the market price at
exit (time-stop / fixed horizon, e.g. 5-10 trading days), NOT the plan's theoretical RR. ⚠️ Trap to avoid: the
rr feature (planned ratio), discount (which defines the entry) and node_quality (which defines the target) are
inputs readable at t0; the label is the result realized afterwards. Strict rule: entry/stop/target are
frozen at t0, the realized_r label comes from the real fills/exit (Outcome.realized_r, §3) — never recomputed
from the features. Otherwise we regress the target on transforms of itself (leakage → inflated hit rate).
v1 weights (numeric, versioned weights_v1 — codable starting point, to recalibrate): features normalized
0-1; raw = (Σ wᵢ·fᵢ + cross terms) − b, score = 100·sigmoid(raw).
| feature | w | | feature | w |
|---|---|---|---|---|
| discount | 1.0 | | real_node | 1.0 |
| trend | 0.8 | | flow_align | 0.5 |
| rr | 0.5 | | oi_build | 0.4 |
| node_quality | 0.8 | | iv_gate | 0.3 |
| fresh | 0.6 | | index_support | 0.5 (−0.8 if against) |
| pattern | +1.0 / −1.0 | | darkpool×node (cross) | 1.2 |
| gamma_squeeze | 0.6 (long/call) | | | |
Bias b = 3.5 (centers the sigmoid: an average setup with ~3-4 active features → score ~50). Threshold s_go = 70
(GO), 45 ≤ score < 70 → WATCH, < 45 → PASS — subject to the §6 hard gates. Calibration: these weights are
v1 "expert guess" and now written down; recalibration = regularized regression (ridge/shrinkage) on the
journal, walk-forward only (§7).
Reconciling the existing scores (to settle BEFORE dev): the repo already contains two scorers different from this spec —
pandora/research/quality_score.py(100-pt additive, modules A-E, hard-coded thresholds, verdictsREADY/WAIT_H4/WATCH/SKIP) andlab/scanner_poc.py(confluence 0-10, verdictsGO/WATCH/PASS). Decision made: the §5 above is THE target spec;quality_score.py= legacy (to migrate or deprecate), the POC = test bench (its numeric weights fed v1). Unified verdict vocabulary =GO/WATCH/PASS(alignSetup.verdict§3). All new code writes theweights_version.
5.4 The REAL model (beyond the scorecard) — the quant chain
The §5 formula (weighted sum → sigmoid, expert-guess weights) is a heuristic scorecard, not a model: guessed weights, no learned target, no validation. The model is the chain below. The
weights_v1are only the codable starting point; the truth is learned. A linear model on good features beats a sophisticated model on bad ones.
- Clean label (anti-leakage). Target =
realized_rat a fixed horizon (5-10 trading days), with costs (fees + slippage), signed by direction.entry/stop/targetfrozen at t0; the label comes from the real fills/exit (§3Outcome), never recomputed from the features. Otherwise we regress the target on transforms of itself → inflated hit rate. - Features = raw primitives, normalized CROSS-SECTIONALLY. Not the vendor composites (we proved that TV's
opportunity_scoreis noise, 23/06). Each feature = z-score within the universe, per day → removes regime drift, makes setups comparable across tickers on the same day. - Learned model, from simple to complex. First regularized logistic (ridge/L2) → outputs an interpretable
P(win), whose coefficients replaceweights_v1. Boosted trees (capturing non-linear interactions) only if the linear model is beaten out-of-sample. Never the reverse. - Calibration → probability → sizing. Calibrated
P(win)(isotonic / Platt onrealized_r>0) → EV gate (EV≤0→ no trade) → bounded half-Kelly (§6.1). The score is only useful calibrated into a real probability. - Validation = purged gauntlet (non-negotiable). Purged + embargoed walk-forward (López de Prado): overlapping horizons leak between train and test → purge mandatory. + Deflated Sharpe (corrects multiple testing), bootstrap, crisis replay, with costs. Feature selection by microstructure thesis + cross-fold stability, never by in-sample R².
- Statistical honesty (LLN). The edge only materializes after hundreds of independent decisions.
weights_v1= priors; as long as N is low, nothing is proven — present it as such. The forward dataset + journal (§7) are the moat because they are what closes this loop.
5.5 Pattern extraction from primitives (UW = data, not a score)
We do NOT swallow vendors' composite scores. We extract the primitives and build features with a microstructure thesis. Classic mistakes that kill an edge if skipped:
- Opening vs closing: a trade that opens (OI↑ the next day via
oi-change) ≠ one that closes. Only the opening trade is positioning. → compareflow-recentwithoi-changeD+1. - Sweep vs block: sweep = urgent aggression (often retail/momentum); block = negotiated institutional. Different predictive content — keep the tag, do not aggregate blindly.
- Strip multi-legs: a credit spread / condor is NOT a directional bet. Do not map a bought call leg of a spread as "bullish". Multi-leg detection mandatory before signing
flow_align. - Per-strike GEX → the map:
greek-exposure/strike(+spot-exposures/strike) gives King node, floor/ceiling, pivot (gamma flip). It is the vulnerability/structure (the WHERE), never direction (touchstone). - Dark pool × node: a big DP print aligned with a GEX node (±tol) = the
darkpool×nodecross term (§5). Accumulation below price vs distribution into strength. - IV up WITH price (
volatility/realized+ price): spot-up vol-up = abnormal upside demand = gamma squeeze precursor (§6.3), not noise. - Inverted term structure into earnings (
volatility/term-structure) = IV-expansion category (§0.2 phase 1.4c). - Family rotation (cross-section):
net-flow/expiry+ GEX aggregated by family, D/D → rotation IN/OUT (§6.2).
The method's patterns (rug, reverse-rug, pika/barney, slingshot) are boolean rules on top of these primitives (§4) — detected, not guessed. The predictive value of each pattern goes through the gauntlet (§5.1) before being weighted.
6. Hard filters (gates — blocking, outside the score)
rr < 2.0→ PASS · price at the midpoint → PASS · trend against the setup → PASS · macro regime against (backwardation for an aggressive long) → degrade/de-risk · hedge-node-only (no real node) → PASS.
6.1 Sizing — EV → half-Kelly (the piece that keeps the edge alive)
The signal says what, sizing says how much — and sizing is what kills or saves a real edge (Thorp: 19 years without a losing year thanks to sizing, not the signal). We size by expectancy, not by feel.
- The score → a win probability. The
quality_score(§5) is calibrated (via the journal, walk-forward) into a realp = P(win), not an abstract grade. Calibration = isotonic / Platt regression onrealized_r > 0. - Expectancy (EV) per setup, hard gate.
EV = p·W − (1−p)·LwhereW,Lcome from the plan (entry/stop/targets, sob = W/L≈ the RR).EV ≤ 0→ we do not take it, whatever the score (adds to the §6 gates). - Size = bounded half-Kelly.
f* = (p·b − (1−p)) / b(Kelly). We deploy ½·f (half-Kelly = institutional standard, smoother equity curve), capped* by:f_maxper position (e.g. 2% of capital), total gross exposure, and the regime throttle below.f* ≤ 0⇒ size 0 (consistent with the EV gate). - Regime throttle (soft-switching). The final size is multiplied by a regime factor
∈ [0,1]from the regime read (GEX/DIX positioning + HMM statistical layer if validated in the gauntlet, see R&D): we reduce in a hostile regime (×(1 − P_bear)), we push in a supportive regime. Soft (probability-weighted) rather than binary → less turnover, less whipsaw at transitions. - Hybrid execution (link §0).
auto_size = min(half_kelly, size_cap)executed via IBKR; above the cap → human validation. The auto part is never > half-Kelly. - Why it matters (LLN). The edge only materializes after many independent decisions (law of large numbers): positive EV + half-Kelly + high N = convergence to the mean. That is exactly why the forward dataset + journal are the moat (§7), and why a low N (today) proves nothing yet — to be presented honestly.
6.2 Families & rotations (cross-sectional view — "compile what a human cannot see")
Talon style: reason by family/theme, not just ticker by ticker. Aggregate flow/positioning/IV by family to anticipate rotations = typically the data a human cannot compile in real time → direct cross-sectional edge.
- Family taxonomy: each ticker belongs to a family (defensive · financials · AI/datacenter · semis · quantum · photonics · nuclear/uranium · biotech · energy · crypto-proxy · consumer…).
ticker → familymapping (maintained table + GICS sector as a base; custom themes take priority, aligned with the Talon families). →Setup.familyfield (§3). - Systematic tag: every suggestion comes out with its family → the cockpit groups by family (like Talon). "When the agent suggests a stock, it adds it to a family."
- Rotation detection: from the cross-sectional panel (net flow, GEX/positioning, dark pool, IV aggregated by family, day over day) → momentum/positioning score per family → ranking: rotation IN (family strengthening: inflowing flow, growing nodes, expanding IV) vs rotation OUT (weakening). Output = family ranking + Δ vs D-1 / D-5.
- Usage = confluence booster: setup aligned with an incoming rotation → conviction ↑ (
family_rotationfeature, to fold into the §5 score in v2); against an outgoing rotation → caution/penalty. Rotation weights, it does not create the trade. - Validation: the predictive value of family rotation = to prove in the gauntlet on the accumulated cross-sectional panel (like any signal). Not a given before ~N days of data.
- ⚠ Data source: aggregation by family / rotation requires daily data. The free TV demo serves a ~daily snapshot (verified: 18/06 then 22/06) → collectable for free. The real constraint = making collection reliable (a cron that runs — ideally a cloud cron, not the Mac on standby). UW later for richer data / guaranteed freshness.
6.3 "Gamma squeeze pending" detector (asset & family → boosts the score)
Spot the self-reinforcing mechanics early: calls → MM short gamma → hedge by buying → price rises → strikes flip ITM → even more hedging. Several data points combined, never an isolated signal. It is the quantified version of the method's −gamma slingshot up (academy §13 playbook), with extra confirmations.
Inputs collected (most already in our sources; ⚠ short interest / days-to-cover = via Unusual Whales): | signal | indicative threshold | source | |---|---|---| | call/put volume ratio | ≥ 3-5× | flow | | call OI stacked just above spot (ascending clusters) | big call nodes > spot | map / OI | | price approaching a big call strike | spot→strike distance ↓ | map + price | | IV rising WITH price (spot-up vol-up = abnormal, upside demand) | IV·price corr > 0 over N d | IV + price | | high short interest + days-to-cover ↑ | high SI, rising DTC | UW | | expanded spot volume | ≥ 2-3× average | price/volume | | strikes flipping ITM fast | n strikes crossed | spot vs strikes | | dealers short gamma above spot (positive feedback) | GEX < 0 above | GEX | | high total call delta (MMs heavily long stock as hedge) | Σ call delta ≥ ~0.25 | options | | high cost to borrow (CTB) (on top of short interest) | CTB / borrow fee ↑ | UW |
Instrument & strike (the "position early" side): exposure via LEAPS / near calls (ITM or just OTM); target the strikes just above spot with big OI (where dealer hedging kicks in); enter early, before the crowd. Risk-managed sizing = bounded half-Kelly (§6.1).
- Composite score:
gamma_squeeze ∈ [0,1]= weighted fraction of conditions met (≥ k conditions = "pending"). Computed per asset AND aggregated by family (§6.2) — a family where several names light up = thematic rotation / squeeze (strong signal). - Boosts the quality score (§5):
gamma_squeezefeature (weight ~0.6) on aligned long/call setups; does not apply to / penalizes a short. - Sizing & execution: a squeeze = violent & asymmetric move → −gamma doctrine (absorb the overshoot, enter when it stalls) + bounded half-Kelly (no overexposure to the parabolic move).
- Honest: a pre-squeeze ≠ a squeeze (many abort → see the AMKR "different case"). It is probabilistic fuel, validated in the gauntlet like any signal — not a guarantee.
6.4 Companion layer (V2) — what turns the engine into a companion
The engine (§1-§6.3) finds and sizes trades. The companion manages the book, keeps the discipline, watches the calendar and explains — that is what a human alone cannot sustain, and it is the trust relationship.
6.4.1 PORTFOLIO risk brain (not just per trade)
- Concentration by family (§6.2): exposure cap per family (e.g. ≤ 25% of total risk) — an Nth long in a saturated family → reduced/refused.
- Effective correlation: rolling correlation matrix (returns) of open positions → N correlated positions count as < N bets; penalizes correlated additions.
- Heat (simultaneous risk):
Σ (entry−stop)·sizeover the book ≤ budget (e.g. ≤ 6-10% of capital at risk at any time t). - Drawdown circuit breaker: book drawdown > threshold OR K consecutive losses → size ÷ 2 until it stabilizes (same logic as the instability kill-switch).
- Net exposure / regime: net (long−short) bounded by the macro regime (risk-on/off, contango/backwardation).
- → Final size =
min(half-Kelly §6.1, portfolio constraints). Schema:Bookstate (§3).
6.4.2 Behavioral discipline coach
AI as an emotional guardrail, deterministic from the journal (§3). It recommends, the human decides (consistent with the AI-human architecture). - Overtrading (trades/day > baseline, non-A+ entries) · Revenge trade (< T min after a loss, size ↑ / conviction ↓) · Chasing (entry outside the deflection zone = violates "direct tap") · Discipline drift (% of trades respecting the RR/fresh/no-midpoint gates falling). - Outputs:
WAIT · NUDGE · STOP-today · NO-TRADE(hostile regime + 0 A+ setup). - Honest: assumes a real journal (N≈0 today) → built through use (§7). This is the companion differentiator.
6.4.3 Calendar & catalysts
- OPEX (monthly/quarterly + weeklies): as it approaches, flag that the GEX map will reshuffle (expiring nodes) → caution on setups backed by nodes close to expiry; post-OPEX = new map.
- Earnings: directional long with earnings in X d → IV crush / gap flag (unless it is an IV-expansion-into-earnings play, see the dedicated doc — there it is the setup, not the risk).
- Macro blackout (FOMC/CPI/NFP) → reduce aggressiveness (link to the §6.1 throttle).
- Data: earnings calendar (UW) + macro + options expirations. Schema:
Setup.days_to_earnings,near_opex,macro_event.
6.4.4 Explainability & conviction (trust)
Every suggestion comes out with a clear read (the 2-3 factors that carried the score) + a conviction WITH its uncertainty — not a bare point score (rule: report an interval, not a point). conviction 0.6 ± 0.2 ≠ 0.9 ± 0.05 → different sizing and presentation. Fields Setup.conviction, Setup.uncertainty.
6.4.5 Transparent paper book (the living proof)
The agent keeps a paper book and shows its honest forward P&L (already forward_track.csv) — at once the proof (forward, not backtest), the fuel for the coach (§6.4.2) and for recalibration (§7). Nothing is hidden.
6.5 Companion roadmap (V2 → V3)
- Trade lifecycle: post-entry management — trail on rolling floors/ceilings, node-to-node partials, exit when "the map no longer pays you" (academy §7). Most tools stop at the entry; a companion stays with you until the exit.
- Personal memory: meta-labeling on Léo's decisions → the agent adapts to his style, his winning patterns, his real tolerance.
- Proactive intraday alerting: ping when a tracked setup taps its node / regime flips / squeeze lights up (cron + push already there).
- Gauntlet on demand: "does this type of setup really work?" → the agent runs the gauntlet and answers, with proof.
7. Memory loop & anti-overfit (the moat = a risk if done badly)
- Target: does the score recalibrated at t predict
realized_rat t+1 better, out-of-sample, than a frozen-weight score (mandatory baseline)? - Protocol: anchored walk-forward (reuse the PANDORA gauntlet: pre-registration, costs, Deflated Sharpe). Quantified minimum N: ≥ 50 independent decisions per segment before any recalibration (watch the effective N < raw N: picks from the same day/regime are correlated → deduplicate by regime). Quantified deployment criterion: the recalibrated score only replaces the frozen baseline if its OOS ΔSharpe > 0 with a bootstrap CI (95%) excluding 0 (otherwise the baseline is kept). Shrinkage/regularization mandatory. Weight versioning.
- Honest status: real journal at N≈0 today (
/journalshows 5 illustrative DEMO trades). So the learning loop is an untested hypothesis, not an acquired moat — to be presented as such. - LEARNING GATE (hard): no memory / recalibration / RL before ≥ 1000 logged decisions. Before that threshold we do not learn (we would be optimizing on nothing) — we log to build the dataset. Learning is V3, conditional on this gate.
- Honest: the edge is not fully backtestable without per-strike GEX/flow history → proof = forward/paper, slow, low N. tv-mcp nuance:
get_series(window up to 2y) gives a history of aggregated metrics (gamma/regime/levels at ticker level) → allows a partial backtest of the aggregated signals (regime, gamma flip), not of per-strike detail. Success metric = beat the frozen baseline OOS, otherwise we do not deploy the recalibration.
8. Operational feasibility (to cost against the real API docs)
- Timing: Skylit maps are live and update during the US session. Run = pre-market prep (~1h before the open) + continuous scan during the session. Check with the Skylit API the exact availability windows (latency, intraday update frequency, pre-open state).
- Volume: naively ~750 tickers × ~5 endpoints = ~2500-3000 requests/run. tv-mcp optimization:
rank_top_setups/run_screenerrank server-side in 1 call → we only pull per-ticker detail (get_gex_by_strike,get_levels,get_series) on the pre-filtered top-N (~30-50), i.e. ~150-250 req/run. Still check rate limits + quotas; does the run fit in the window? Compute duration + cost/run. - LLM: annotator (low temperature, JSON schema output) on the top-N only (N≈20-30); cannot override the deterministic gates. Cost = N × prompt_size × runs/month.
- Missing data: degraded score + flag, never a crash.
9. Non-functional & SLA (quantified — the dev must meet them)
| SLA | V1 target |
|---|---|
| Universe | ~750 tickers / run |
| Run duration | < 15-20 min (deterministic, parallel) |
| Frequency | 1×/day (before the open); intraday = V2+ |
| Run cost | ~€0 deterministic (LLM out of V1; in V2: top-N only, < a few €/run) |
| Error tolerance | ≤ 5% of tickers failed per run (skip + log, no global crash) |
| Data freshness | post-US-close snapshot, dated for the next day |
- Idempotence/reproducibility (debug + outcome attribution) · monitoring/alerting (failed/partial run, drift in the number of setups) · score versioning · market calendar (holidays, half sessions, earnings) · secrets (API keys in .env, never committed). |
|
| - Security — keys, not prompts: "do not delete / do not send" is a suggestion, not a guarantee. We control at the permissions level: read-only & scoped keys by default (data, calendar, etc.); destructive/outbound actions (V3 broker) behind explicit rights. If the agent can technically do it, we assume one day it will → we block it through rights, not through the prompt. | |
| - Second memory (seed of the 2nd brain): the journal (decisions + outcomes, plain-text/DB) + the method docs are designed from V1 as the compounding queryable memory — base of the "trading 2nd brain" North Star (see V1-BUILD-SCOPE). |
10. Acceptance criteria (definition of "done" per phase)
- P1: full daily run over ~750 tickers, data ingested + maps rebuilt, < target window, monitoring OK.
- P2: quality_score computed + setups in the Talon template; discriminating score (GOs outperform PASSes on a control sample); hard gates effective.
- P3: LLM arbiter (annotator) + memory loop; recalibration beats the frozen baseline OOS (otherwise disabled).
- P4: forward/paper tracking; forward hit rate ≥ target over N picks.
- Unit tests on every glossary definition (§4) + the score (§5) + the adapter (§2, with fixtures).
11. Suggested stack
Python (reuses PANDORA: gauntlet, metrics, journal) · product data = Skylit (active subscription) → target Skylit API;
engine sandbox on tv-mcp demo ($0, uvx tv-mcp) while waiting for the API; adapters behind the §2 interface →
switch without touching the engine · light DB (journal/memory) · run orchestrator (cron/launchd → cloud) · LLM via
API (arbiter — can call tv-mcp directly, it is an MCP server). The existing prototype (lab/scanner_poc.py,
pandora/skylit/) is the base for the re-scoring + journal.