This document is for Williams Family Trading Dojo members only.

📚 Master Reference v4.2 Build @271 · May 27 2026
← Dashboard 📜 Legacy

Every component. Every rule. Every known failure. — Williams Family Trading Dojo

1 System Overview

MillionaireSensei is a fully-automated options trading system combining TradingView technical signals, a Google Apps Script processing brain, Firebase for state management, Alpaca for trade execution, and a custom Cloud Run brain-bridge service.

Architecture

ComponentTechnologyRole
TradingViewPine Script v6Generates CALL/PUT alerts via 12-strategy execution engine (MS_Execution_V8.1) and 40-ticker screener (MS_Screener_V8.1)
GAS BrainGoogle Apps Script (Code.js @271)Receives webhook alerts, scores signals, places Alpaca orders, writes to Firestore via brain-bridge
FirebaseFirestore + HostingState persistence; hosts the dashboard
Brain-BridgeCloud Run (brainbridge-ctxkltuw3q-wl.a.run.app)Relay between GAS and Firestore; handles trade lifecycle events
HMM OracleCloud Run (hmm-oracle-v3)GaussianHMM on SPY daily data — NORMAL_VOL / HIGH_VOL regime
Alpacapaper-api.alpaca.marketsOptions order execution (paper until Monte Carlo passes)
TelegramTelegram Bot APINotifications for every trade, signal, system event
Jaclau (AI)claude-sonnet-4-6Autonomous AI trader shadowing Johnpaul's strategy

Key URLs and IDs

ResourceURL / ID
Dashboardhttps://millionairesensei.com
GAS /exec endpointhttps://script.google.com/macros/s/AKfycbzLBZ69pMA2MS-oWHIzTpUhCsGo81eBNzf0KnXyrUYMLaiwk5ouTw26hnBGt9gWx2em_Q/exec
Brain-Bridge URLhttps://brainbridge-ctxkltuw3q-wl.a.run.app
Brain-Bridge Revision (good)00025-tud — verified 2026-05-26
HMM OracleCloud Run: hmm-oracle-v3
Alpaca paper accountPA3BA272BSXS — paper-api.alpaca.markets
SecretMillionaire$ensei1968
Current Build@271 — deployed 2026-05-27
2 GAS Brain (Code.js)

The Google Apps Script brain is the central processing unit. It receives TradingView webhooks, scores signals, manages the signal queue, places Alpaca orders, and writes all trade lifecycle events to Firestore via the brain-bridge.

Signal Flow

  1. TradingView fires alert → webhook to GAS doPost()
  2. GAS enqueues signal → processSignalQueue() picks up within 1 minute
  3. GAS scores signal (confluence + backtest memory + HMM regime overlay)
  4. If score passes gate: select option contract via Alpaca options chain
  5. Place order on Alpaca paper account
  6. Push trade_open event to brain-bridge → written to Firestore
  7. Dashboard Engine Room shows live position with trailing stop active
  8. Trailing stop trigger fires every minute → closes position if triggered
  9. trade_close pushed to brain-bridge → Ledger updated, P&L recorded

Key Script Properties

All secrets and config live in GAS Script Properties. Never hardcode in code.
Property KeyPurpose
APPS_SCRIPT_RELAY_SECRETPrimary auth secret: Millionaire$ensei1968
ALPACA_API_KEYAlpaca paper API key
ALPACA_SECRET_KEYAlpaca paper secret key
ALPACA_BASE_URLhttps://paper-api.alpaca.markets/v2 (change ONLY after Monte Carlo pass)
BRAIN_BRIDGE_URLhttps://brainbridge-ctxkltuw3q-wl.a.run.app
TELEGRAM_BOT_TOKENTelegram bot token (sensitive — never log)
MS_APP_VERSIONBase version string (e.g. "4.2"). CONFIG.MS_VERSION getter appends Build @NNN from MS_DEPLOY_NUMBER — Telegram headers show "v4.2 Build @NNN".
MS_DEPLOY_NUMBERForever-incrementing build counter. Current: 271
FRED_API_KEYFRED API key — macro context in morning briefs + VIX fallback
MIN_SCORE_NORMALMinimum signal score in normal volatility (default: 5)
MIN_SCORE_HIGH_VIXMinimum signal score when VIX > 25 (default: 7)
3 Deploy Rules — MANDATORY
⚠️ NEVER break these rules. They encode bugs we have already shipped and paid for.

GAS Deploys (Code.js changes)

Always use REDEPLOY_GAS_AND_INSTALL.bat — never CLASP_PUSH.bat alone.

CLASP_PUSH only updates the source files. The live /exec endpoint is pinned to a versioned deployment ID. It keeps serving old code until clasp deploy runs.

The bat runs all 4 required steps: (1) clasp push, (2) clasp deploy -i DEPLOY_ID, (3) install_ts_trigger, (4) purge_old_versions.

What changedWhich bat
Code.js (any line)REDEPLOY_GAS_AND_INSTALL.bat
index.html onlyDEPLOY_HOSTING_ONLY.bat
Both Code.js + index.htmlRun BOTH bats sequentially
CLASP_PUSH.bat alone⛔ NEVER for Code.js — use only for non-GAS file syncing

index.html Changes

⚠️ NEVER use the Write tool on index.html. It silently truncates files larger than ~8000 lines, losing the closing tags. The JS module is refused, Firebase never initializes, login freezes silently. Always use Edit for targeted changes. (Root cause of R13)

Before every index.html deploy, run the duplicate-const grep:

grep -n "^  const [A-Z_]" firebase/public/index.html | awk -F: '{print $2}' | sort | uniq -d

Any output = duplicate const declarations = parse-time SyntaxError = login spinner freezes with no visible error.

Post-Deploy Verification

After every deploy, run the ms-system-test skill. Quick verify for GAS: call get_option_prices — valid JSON with a prices key = live. Raw string "ok" = stale deployment, run the bat again.

4 Dashboard (index.html)
PanelData SourceKey Behavior
Hero StripFirestore users/{uid}P&L pill, portfolio value. INFLATION: raw + $1,000,000 at display layer ONLY.
Engine RoomFirestore trades + GAS get_option_pricesActive positions with Live/Close prices. HMM regime badge. Trailing stop protection events.
RadarBrain-bridge signalsIncoming TradingView signals. Off-hours signals appear here too (v4.4 behavior).
LeaderboardFirestore users collectionJohnpaul and Jaclau ranked by portfolio value.
Head-to-HeadFirestoreJohnpaul vs Jaclau side-by-side.
Ledger / Activity TapeFirestore tradesClosed trades with entry/exit prices and P&L. Entry price fallback: t.premium.
⚠️ Portfolio inflation (+$1,000,000) is DISPLAY ONLY. Never write inflated value to Firestore, Alpaca, or any calculation.

Market Hours Gate (v4.4 — Build @261+)

Off-hours signals ARE logged to the Radar panel. Telegram notification IS sent. Alpaca order execution IS suppressed. Response does NOT indicate a hard block. The old blocked: true behavior was removed in v4.4.

5 Firebase & Firestore
Collection / PathContentsWriter
users/{uid}Portfolio value, settings (tradingMode, mirrorJaclau), display totalsGAS via brain-bridge
users/{uid}/trades/{tradeId}Full trade lifecycle: all trade_open fields, exitPrice, status, P&LGAS via brain-bridge
users/{uid}/settingstradingMode, mirrorJaclau toggleDashboard UI
system/stateMS_VERSION, last HMM regime, brain-bridge heartbeatGAS + HMM Oracle
radar/{signalId}Incoming signal eventsBrain-bridge
⚠️ Several UI actions appear to work but silently fail at the backend. Always verify in Firestore (not just the button highlight).
ActionMust Verify End-to-End
Trading Mode switchFirestore users/{uid}/settings.tradingMode
Close button clickFirestore trades/{tradeId}.status = 'closed' AND exitPrice populated AND Alpaca position closed
Trailing stopprocessPendingTrailingStops_ trigger listed in GAS project triggers
Liquidate AllGAS returns JSON {ok: true} — NOT an HTML "Page Not Found"
6 Brain-Bridge Service

Cloud Run service relaying between GAS and Firestore. Current good revision: 00025-tud (verified 2026-05-26). Bad revision: 00015-mn2 — never route traffic back.

⚠️ Auth uses an HTTP HEADER, not a body field: X-MS-Secret: Millionaire$ensei1968. Body must contain a type field.
ErrorMeaning
401 UnauthorizedHeader name or value is wrong. Confirm X-MS-Secret (not secret in body).
400 Missing type fieldAuth is WORKING — body needs a type field added.
400 Unknown type: XAuth is WORKING — use a valid type like get_jaclau_today_summary.
7 HMM Oracle

Cloud Run service (hmm-oracle-v3) running GaussianHMM on SPY daily data. Non-blocking advisory overlay — modifies risk sizing, does NOT gate trades.

RegimeMeaningRisk Multiplier
NORMAL_VOLLow volatility, trending conditions1.0 (full position size)
HIGH_VOLElevated volatility, choppy conditions0.5 (half position size)
STALEHMM Oracle has not run today — expected pre-market1.0 (no penalty)

Cloud Scheduler job: hmm-daily-regime-sync — fires 1:15 PM PT (4:15 PM ET) weekdays.
Force a run: Cloud Console → Cloud Scheduler → hmm-daily-regime-sync → Force Run.

8 Alpaca Markets Integration
FieldValue
Paper account IDPA3BA272BSXS
Paper API basehttps://paper-api.alpaca.markets
Live API base (future)https://api.alpaca.markets — only after Monte Carlo review passes
Options WebSocketwss://stream.data.alpaca.markets/v1beta1/indicative-options

OCC Option Symbol Format

Ticker + YYMMDD + C/P + 8-digit strike (strike × 1000, zero-padded).
Example: SPY260620C00500000 = SPY CALL, Jun 20 2026, strike $500.00

⚠️ WebSocket uses abbreviated field names: bp = bid_price, ap = ask_price. NEVER use bid_price or ask_price — they will always be undefined.
9 Trading Strategy Engine

Screener — MS_Screener_V8.1 (Active)

40-ticker scanner — 40 request.security() calls, at the Pine Script limit. Each ticker is evaluated for CALL/PUT confluence using the same 12-strategy logic as the execution chart.

40-Ticker Watchlist (Build @271): AAPL, ADBE, AFRM, AMD, AMZN, APP, ARM, AVGO, COIN, CRM, CRWD, DKNG, GOOGL, GS, IWM, JPM, LLY, META, MRVL, MSFT, MU, NFLX, NVDA, ORCL, PANW, PLTR, PYPL, QQQ, ROKU, SHOP, SMCI, SMH, SNOW, SOFI, SPCX, SPY, TSLA, UBER, V, XYZ

SPCX added 2026-05-27. Alpaca options go live 2026-06-12 — signals will flow automatically from that date.

VIX Architecture (V8.1+)

MS_Screener_V8.1 removed VIX from request.security() to free the 40th slot for SPCX. VIX is now sourced independently by GAS:

getGasVix_()
  1. Yahoo Finance %5EVIX — ~15-second refresh (primary)
  2. FRED VIXCLS — official EOD (fallback)
  CacheService: 60-second cache under key 'GAS_VIX_LIVE_'

MS_Execution_V8.1 retains its own CBOE:VIX call (separate 40-call budget; only 3 calls used on single-symbol chart — fine).

Screener V8.2 (Built, Not Yet Deployed)

MS_Screener_V8.2.pine — 70-ticker v6 dynamic loop using Pine Script v6 array iteration. Reserved for future activation when the 40-ticker limit becomes a constraint.

Execution Chart — MS_Execution_V8.1

Pine Script v6 indicator detecting 12 named strategy types on the live single-symbol chart.

IDStrategyTrigger
S1VWAP Reclaim Call / Rejection PutFresh VWAP cross + volume surge
S2Opening Range Breakout Long/ShortORH/ORL break after 9:30–10:00 ET
S3Opening Range Retest Long/ShortRetesting sealed ORH/ORL
S4Pullback ContinuationTrend intact, returned to VWAP, bouncing
S5Break-and-RetestConsolidating at prior S/R level
S6Failed Breakdown/Breakout ReversalWick + recovery candle
S7Liquidity Sweep ReversalStop hunt → reversal candle
S8Relative Strength/WeaknessTicker outperforms/underperforms SPY by threshold %
S9Compression BreakoutBollinger squeeze release + direction
S10Prior-Day High Reclaim / PDL RejectionPDH/PDL level interaction
S11VWAP Extension Mean ReversionExtreme overextension snap-back
S12Directional Debit SpreadDefault for strong directional alignment
10 Jaclau (AI Trading Agent)

Autonomous AI trading agent powered by claude-sonnet-4-6. Shadows Johnpaul's strategy using paper trades on Alpaca.

SettingValue
AI Modelclaude-sonnet-4-6
Capital allocation$1,000 (Firestore users/jaclau/settings.capital)
mirrorJaclau toggleDashboard Settings drawer — must be ON for autonomous trades
Trading mode requiredBoth (enables paper shadow for Jaclau)
11 Paper Trading Timeline & Monte Carlo
⚠️ DO NOT switch to live trading until Monte Carlo review passes all 5 criteria.
DateEvent
2026-05-26 (done)FIRST Monte Carlo — VERDICT: NOT READY (21 trades, negative EV)
Every Friday after closeRecurring Monte Carlo analysis
Earliest possible live date2026-06-04 — only if Friday May 30 Monte Carlo passes all 5 criteria

Go-Live Criteria (ALL must pass)

MetricCurrentTargetStatus
Win Rate33.3%≥ 45%⛔ BELOW
Avg Win$+35.00≥ $80⛔ BELOW
Avg Loss$-155.57≤ $80⛔ ABOVE LIMIT
Risk/Reward0.22:1≥ 1.5:1⛔ INSUFFICIENT
Expectancy/trade-$100> $0⛔ NEGATIVE EV
Sample size21 trades≥ 50⚠️ TOO SMALL

Required Fixes Before Live Money

FixTarget Impact
Let winners run (hold until +25% minimum gain)Win avg from $35 → $80+
Tighten trailing stop to -15% max lossLoss avg from $155 → $80
Improve entry timing (wait for bar confirmation)Win rate from 33% → 45%+
12 Known Regressions — Fixed, Stay Vigilant
IDBugRoot CauseWatch For
R1$1M inflation not displayingDisplay calculation missing+1000000 at display layer in update_user_summary
R2Activity Tape entry price showing em-dashMissing fallback fieldFallback to t.premium in Ledger display
R3P/L not recording on closeMissing ×100 multiplierP/L formula with options ×100 multiplier
R4get_option_prices returned raw "ok"CLASP_PUSH without REDEPLOYAlways REDEPLOY_GAS_AND_INSTALL.bat
R5Close button not wiredMissing event handlercloseTrade() wired with correct tradeId
R6Trailing stop not firingTrigger not installedinstall_ts_trigger in REDEPLOY bat
R7LIQUIDATE ALL returned HTMLWrong URL constructionURLSearchParams with POST to correct GAS_URL
R8Brain-bridge serving wrong revisionTraffic not updatedRoute 100% to 00025-tud. Never use 00015-mn2.
R9getCredsFromFirestore_ GET vs POST bugWrong HTTP methodChanged to POST
R10Orphaned checkWsServiceHealth triggerOld service removedTrigger deleted
R11LIQUIDATE ALL sent secret as undefinedADMIN_GAS_SECRET inside function scopeMust be at module scope (~line 8421)
R12Login froze (duplicate const)const ADMIN_GAS_SECRET declared twicePre-deploy grep check
R13Login froze (Write tool truncated index.html)Write tool on 8000+ line fileNEVER use Write on index.html — use Edit
13 Claude Skills Reference
SkillWhen to UseWhat It Does
ms-gas-deployAny Code.js change or GAS deployEnforces the 2-step deploy rule
ms-system-testAfter any deploy, pre-market, health checksRuns all 15 tests, saves dated report
ms-hmm-oracleEngine Room OFFLINE, regime staleCloud Run navigation, restart procedures
ms-alpaca-optionsAlpaca options orders, WebSocket quotes, OCC symbolsOrder types, WebSocket field names (bp NOT bid_price)
ms-cloud-archFirestore HWM, Cloud Run WebSocket, GAS triggersFirebase patterns, Cloud Run config
ms-google-signinLogin broken, access denied, whitelistFirebase Auth config, recovery procedures
17 Quick Reference Card

The 7 Rules You Cannot Break

Rule 1

NEVER use CLASP_PUSH alone for Code.js. Always use REDEPLOY_GAS_AND_INSTALL.bat.

Rule 2

NEVER use the Write tool on index.html. Always use Edit for targeted changes.

Rule 3

Run pre-deploy duplicate-const grep before every index.html deploy.

Rule 4

Run ms-system-test after every deploy. Always.

Rule 5

NEVER write portfolio inflation (+$1M) to Firestore or Alpaca. Display layer only.

Rule 6

Verify Trading Mode, Close, Trailing Stop, and Liquidate All END-TO-END in Firestore.

Rule 7

DO NOT switch to live trading until all 5 Monte Carlo criteria pass.

Emergency Procedures

SituationAction
Login spinner freezesRun duplicate-const grep on index.html → check file length (not truncated) → redeploy with DEPLOY_HOSTING_ONLY.bat
get_option_prices returns raw "ok"Run REDEPLOY_GAS_AND_INSTALL.bat — CLASP_PUSH was run without REDEPLOY
Engine Room shows OFFLINELoad ms-hmm-oracle skill → check Cloud Run → force run Cloud Scheduler hmm-daily-regime-sync
LIQUIDATE ALL returns HTMLCheck liquidate handler — must POST to GAS_URL with source='liquidate_all' in body
Brain-bridge returns 401Confirm header is X-MS-Secret (NOT secret in body). Value: Millionaire$ensei1968
Trailing stop not firingRun install_ts_trigger → check GAS triggers for processPendingTrailingStops_