Dashboard | Kalshi | Paper | Harvest | Zones | Live Tuning | Onboard | CrossArb | Diagnostics | Plan

Executive Summary

PW Trading is a quantitative trading system targeting Polymarket prediction markets. The system detects behavioral overshoots — price moves disproportionate to their fundamental drivers — and executes bounded-risk fade trades (betting on mean reversion) when structural conditions confirm the overshoot.

The core thesis: prediction market prices sometimes overreact to attention spikes, order flow imbalances, and volume surges. By measuring the elasticity of price response relative to driver magnitude, we can identify when a move has gone too far and capture the reversion.

Current Stage
Stage 0
Markets Tracked
10
Trading Active
No
Pipeline Version
V6.3

Why This Approach

The Edge

Prediction markets on Polymarket are driven by retail sentiment. When news breaks or attention spikes, prices often overshoot fair value due to herding, momentum chasing, and thin liquidity at the tails. These overshoots reliably mean-revert within minutes because the underlying event probabilities don't actually change that fast.

Why Elasticity

Instead of predicting direction, we measure how much the price moved relative to how much it should have moved given the driver activity. A high elasticity (ε > 1.3) means the price moved more than the drivers justify — classic overshoot territory. This is a structural signal, not a directional bet.

Why 16 Gates

A single signal is never enough. The 16-gate pipeline ensures we only trade when every structural condition aligns: sufficient liquidity, driver validity confirmed, reflexivity checked (not chasing a real information cascade), classifier confident, fee-aware edge positive, and risk limits clear. Any single gate failure blocks the trade entirely.


System Architecture

Polymarket WebSocket | v wsManager.ts — Connects to wss://ws-subscriptions-clob.polymarket.com | v registry.ts — Maintains live order books for 10 markets (20 tokens) | +——> edgeEngine.ts [EXISTING] 5 structural edge formulas, event-driven | +——> behavior/ [NEW — V6.3 Pipeline] | +——> marketState.ts Rolling price history + depth + event counts +——> drivers.ts Z-score computation (volume, attention, flow) +——> elasticity.ts Multi-timescale ε (15s, 60s, 5min) +——> classifier.ts 5-feature overshoot classifier +——> reflexivity.ts Lead-lag R ratio validation +——> pipeline.ts 16-gate ordered evaluation +——> diagnostics.ts Distribution tracking + periodic reports +——> index.ts Entry point + hooks

Data Flow

Every WebSocket event (book snapshot or price change) flows through the registry, updates the live order book state, then immediately feeds into the behavioral pipeline. The pipeline runs synchronously on every event — no polling, no batching. At ~270 pipeline runs per minute across 10 markets, the overhead is negligible.


Build Stages

Stage 0 — Pipeline Infrastructure Diagnostics Running
Deploy the full V6.3 behavioral pipeline in logging-only mode. No trades placed. Evaluate every price event through the 16-gate pipeline and log full feature vectors for all candidates where ε > 0.8. Collect telemetry data required for Stage 1.
Deployed: 2025-02-28 — 8 new files in behavior/, 2 files modified
Status: Pipeline running on top-50 markets by 24h volume (Khamenei $64M, Iran regime, Premier League, Fed rates, Bitcoin hourly). Pipeline now flows through Gates 4–7 for the first time. Awaiting volatility events to push ε past 0.8 threshold.
Gate funnel (post 24h-volume fix): G2 passes 52%, G3 passes 95% of survivors, G7 (driver) is now the active filter at 68% pass. Max ε = 0.7 on quiet Sunday afternoon.
Remaining: Need ε > 0.8 on liquid markets (news, match results, rate decisions) to validate Gates 8–16. Memory stability over 24h+.
Stage 1 — Paper Trading Planned
Shadow-execute fades with no real orders. Log hypothetical P&L, entry/exit timestamps, position tracking. Validate that the pipeline produces actionable signals before risking capital.
Entry criteria: Stage 0 diagnostics clean for 12+ hours, ε distribution verified, no memory drift, driver baselines stable
Abort conditions: >70% of paper fades are losers after 50 samples, or mean fade P&L is negative with 95% confidence
Duration: Minimum 48 hours or 50 fade events, whichever is longer
Stage 2 — Microstructure Validation Planned
Connect to Polymarket's CLOB API for order placement (no live orders yet). Validate fee math against real fee schedule, test order construction, verify fill assumptions.
Key validations: Fee rate confirmation (assumed 1%), order format correctness, API authentication flow, rate limit behavior
Stage 2.5 — Dashboard Integration Planned
Add behavioral pipeline visualization to the trading dashboard. Show live ε values, gate pass/fail state, candidate history, and paper trade P&L. Mandatory before any live trading.
Stage 3 — Controlled Live ($75 cap) Planned
First real capital deployment with hard-capped position sizes ($75 max per fade). Single market at a time, manual review of first 5 trades.
Escalation criteria: Sharpe > 1.0 after 30 fades, win rate > 55%, max drawdown < $200, no single-fade loss > $50
Kill switch: 3 consecutive losses or total drawdown > $150 pauses all trading
Stage 4 — Gradual Escalation Planned
Increase position size caps incrementally based on demonstrated edge. Multi-market concurrent fading enabled after portfolio exposure controls validated.
Escalation steps: $75 → $150 → $300 → $500
Each step requires: 20+ fades at current level, positive Sharpe, no kill-switch triggers
Stage 5 — Full Autonomy Planned
Fully autonomous operation with all V6.3 features active: hedged fade mode, continuation filter, TTL randomization, regime-conditioned reversion targets. Human oversight via dashboard alerts only.
Stage 6 — Live Trading Module Deployed
Full live trading infrastructure deployed across 6 implementation phases. Mirrors the fastTrader 5-track paper logic for real capital deployment on Polymarket via CLOB order relay through a dedicated Toronto VPS (134.122.39.253).
Deployed: 2026-03-04
Components:
  • CLOB Relay — Toronto VPS at 134.122.39.253 relays orders to Polymarket CLOB API, low-latency execution
  • AES-256-GCM Encryption — All relay traffic encrypted end-to-end, credentials never stored in plaintext
  • Multi-User Onboarding/onboard.html UI for user wallet setup, API key provisioning, and account activation
  • Live Trading Engine — Mirrors fastTrader 5-track logic (Moderate, Aggressive, Gravity, Deep, Harvest) with real order execution
  • Dashboard with Kill Switches/live.html with per-track and global kill switches, live P&L, position monitoring
  • Relay Health Monitoring — Continuous relay connectivity checks, latency tracking, auto-reconnect on failure
Status: Ready for first user onboarding. Paper trading continues in parallel for live vs paper comparison.

Current Status

Markets Monitored
100
Min 24h Volume
$514K
Max 24h Volume
$64M
Gate 2 Pass Rate
52%
Gate 3 Pass Rate
95%
Gate 7 Pass Rate
68%
Max ε (current run)
0.7
Deepest Gate Reached
G7
ε > 0.8 Candidates
0
Would-Trade
0

24h Volume Fix Results (2026-03-01)

Critical fix: market selection was using lifetime volume instead of 24h volume. This pulled stale, established markets ($9–$99 24h volume at bottom) instead of actively traded ones.

Paper Trading Engine Deployed (2026-03-02)

Cross-Platform Arb Detection Deployed (2026-03-02)

Infrastructure Deployed (2026-03-01)

Live Trading Module Deployed (2026-03-04)

Stage 0 Exit Checklist

Must complete before proceeding to Stage 1.


16-Gate Pipeline

Every potential trade must pass all 16 gates in order. Gates are ordered cheapest-rejection-first for CPU efficiency — the most common rejections (price floor, liquidity) happen before expensive computations (classifier, reflexivity).

# Gate What It Checks Status
1 Regime Check Flow regime must be ATTENTION_SPIKE or BUILDING_ATTENTION Stubbed — defaults to PASS
2 Price Move Floor 60s price move ≥ 1.0¢ (MIN_ABS_MOVE) Live
3 Liquidity Volume ≥ $10K, depth ≥ $300 within 2¢, spread ≤ 1.5¢ Live
4 Resolution Risk No imminent market resolution (UMA oracle check) Stubbed — needs UMA integration
5 Propagation Imminent No correlated market about to cascade Stubbed — needs correlation tracking
6 Propagation Window Not inside a cross-market propagation wave Stubbed — needs propagation matrix
7 Driver Validity CombinedDriverZ ≥ 1.0 + at least one driver passes absolute floor Live
8 Elasticity Multi-timescale gate: (ε₁₅ > 1.30 AND ε₆₀ > 1.30) OR (ε₁₅ > 2.50 AND ε₆₀ > 0.80) Live
9 Reflexivity Lead-lag R ≤ 4.0 (not chasing a real information cascade) Live
10 Classifier 5-feature overshoot classifier confidence ≥ 0.65 Live (f3, f5 stubbed)
11 Fee-Aware Edge Net edge per share > 0 after 2× fee deduction (most markets: 0% fee) Live (update fee rate)
12 Stop Geometry Stop distance > spread (trade is executable) Live
13 Impact Share Order size < 30% of available depth (no self-impact) Stubbed — no sizing yet
14 Risk Limits Max concurrent fades not exceeded Stubbed — no fades active
15 Portfolio Exposure Total exposure within group and portfolio caps Stubbed — no positions
16 Size Viability Computed position size ≥ minimum order ($5) Stubbed — no sizing in Stage 0

Live = fully computed from WebSocket data  |  Stubbed = defaults to PASS, will be implemented in later stages


Next Steps

Live Trading (Active)

  1. Live Trading Module deployed — 6 phases implemented: CLOB relay, encryption, onboarding, live engine, dashboard, health monitoring
  2. Pipeline-aligned — live engine receives identical WOULD_TRADE signals as paper trader from 16-gate pipeline
  3. Single-position close — close individual positions via dashboard button (market-sell via CLOB relay)
  4. Dashboard data alignment — all trades visible, DB stats bar, on-chain split, DB fallback for positions
  5. Close OKC Thunder test trade — use new Close button on dashboard
  6. Address zero pipeline signals — per spec failure condition A: if <2 signals/day for 3 days, loosen tightest gate by 10–15%
  7. Monitor live vs paper comparison — validate that live execution matches paper trade signals and P&L expectations

Waiting On (Let It Cook)

  1. Volatility event on liquid markets — Iran/Khamenei news, Premier League results, Fed rate decisions, Bitcoin moves. Need ε > 0.8 to validate Gates 8–16 path
  2. 24h memory stability — 476MB RSS at 12h (no leak), need full 24h+ confirmation
  3. Delta snapshot validation — verify 30-min snapshots show meaningful per-window data after next few cycles

Stage 1: Paper Trading Validation (Active)

  1. Paper trade execution engine deployed
  2. Position tracker with mark-to-market P&L
  3. Exit logic (target hit, stop loss, TTL expiry)
  4. Full trade lifecycle logging (signal → entry → hold → exit → P&L)
  5. Accumulate 50+ paper trades to validate P&L distribution
  6. Evaluate win rate, expectancy, Sharpe proxy
  7. Tune revert fraction, stop multiple, hold TTL based on results
  8. Define Stage 1 success/failure criteria thresholds

Paper Trading Projections — Check Friday March 7

Baseline set 2026-03-03 from 26 captured WOULD_TRADE signals (11 unique positions) observed March 1–2. All signals passed all 16 gates. Paper trader was wired after these signals fired, so actual paper trades start accumulating from March 3 onward.

Observed Signal Profile (March 1–2 data)

Signal rate ~1/hour during active events (sports, crypto hourly)
Unique positions 11 from 26 raw signals (deduped by market+side)
Market types Sports (LoL, NBA, NHL), crypto hourly, politics (rare)
Median entry price ~$0.55  |  Median 60s move: ~23¢
Reflexivity 82% CAUSAL (strongest signal for mean-reversion)
Classifier 100% OVERSHOOT, median confidence 0.83

Per-Trade Economics ($50 notional)

Exit Type Avg P&L Trigger
Target hit +$11.10 Price reverts 50% of spike within 3 min
TTL expire +$2.03 Partial revert, closed at 3 min timeout
Stop loss −$34.79 Price continues 1.5x against, hits stop

Friday March 7 Projections (50 trades × $50 = $2,500 deployed)

Scenario Target / Stop / TTL Net P&L ROI
Optimistic 25 / 5 / 20 +$144 +5.8%
Moderate (expected) 20 / 5 / 25 +$99 +4.0%
Conservative 17 / 7 / 26 −$2 ~0%
Pessimistic 12 / 12 / 26 −$232 −9.3%

Friday Scorecard (fill in actual results)

Metric Projected Actual Verdict
Total paper trades ~50
Target hit rate 35–50%
Stop rate 10–15%
Net P&L +$50 to +$150
Avg trade P&L +$1 to +$3
Expectancy +$0.50 to +$2.50

Key assumption: 3-min TTL captures most of the revert. Prediction market overreactions on binary outcomes (sports, crypto hourly) typically revert within 30–120s. The asymmetric risk (win +$11 / lose −$35) requires ≥40% target-hit rate to be profitable. 82% CAUSAL reflexivity and 100% OVERSHOOT classification are favorable indicators.
Risk factor: Breakeven is ~76% target-hit rate in pure target-vs-stop. The TTL cushion (+$2 avg) lowers this to ~40% effective breakeven when 50% of exits are TTL. If stop rate exceeds 20%, the strategy is unprofitable.

Stage 2 Prep (Account & API Setup)

  1. Create Polymarket account + determine jurisdiction (international vs US)
  2. Set up wallet + export private key securely
  3. Install @polymarket/clob-client SDK on VPS
  4. Generate L2 API credentials from private key
  5. Set token approvals (if EOA wallet)
  6. CLOB REST read access working (orderbooks, midpoints, tick sizes, fees)
  7. Update Gate 11 to use per-market fee rates from CLOB API (most = 0%)
  8. Fund with small test amount ($5–10 USDC on Polygon)
  9. Place + cancel a $1 test order to verify full auth flow
  10. Test withdrawal path (round-trip: exchange → Polymarket → exchange)

See Funding & Account Setup for full details.


Risks & Challenges

High Risk

  • Baseline poisoning — If a market enters a sustained high-activity regime, rolling baselines shift and z-scores deflate, potentially missing real overshoots
  • Reflexivity false negatives — Real overshoots with lag-side driver activity (news arriving after the move) could be incorrectly blocked as "reactive"
  • Thin liquidity at tails — Prices near 0.02 or 0.98 have very thin books; our depth checks may pass but actual fill quality degrades

Medium Risk

  • Fee assumption — Using 1% fee rate but most Polymarket markets have zero fees. Gate 11 is over-conservative — needs per-market fee rate from API. Resolved in Stage 2.
  • Book refill spoofing — Classifier f1 (bookRefill) can be gamed by placing and canceling orders. P6 persistence check added but not yet implemented
  • Stubbed gates — 7 of 16 gates are stubbed (defaulting to PASS). In production these could allow trades that should be blocked
  • 5-minute ε estimation — The 5-minute elasticity window is estimated via decay factor until the system has 5 minutes of data; early estimates may be unreliable

Operational Risk

  • WebSocket disconnection — If the Polymarket WS feed drops, price history develops gaps. Stale data could produce false ε readings on reconnect
  • VPS stability — Single-server deployment with no failover. Service restart clears all in-memory state (price history, baselines)
  • Memory growth — Rolling windows (330s price history, 100-sample baselines, 300s event buffers) should be bounded, but bugs in trim logic could cause slow leaks

Mitigations in Place

  • P11 baseline poisoning guard — Baselines use coefficient-of-variation stability check
  • 60s diagnostics — Memory, baselines, distributions reported every minute for early detection
  • Stage gating — No capital at risk until Stages 0 + 1 validation complete
  • Kill switches — K1-K10 circuit breakers defined (3 consecutive losses, drawdown cap, exposure limits)
  • $75 initial cap — Stage 3 limits max single-fade exposure; total portfolio drawdown capped at $150

Opportunities

Structural Advantages

  • Sub-second event response — Pipeline runs synchronously on every WS event. Faster than any human trader and most bots polling on intervals
  • Multi-timescale confirmation — Requiring ε confirmation across 15s AND 60s windows filters out noise that single-window systems would trade on
  • Reflexivity validation — The lead-lag R ratio is a novel filter that most prediction market bots lack entirely. It prevents the most expensive mistake: fading real information
  • Fee-aware gating — Many retail strategies ignore fees. Our Gate 11 ensures positive expected value after fees before any trade is placed

Growth Vectors

  • Market expansion — Currently tracking top 10 by volume. Expanding to 50+ markets increases candidate surface area without proportional risk increase
  • Cross-market correlation — Stubbed gates 5-6 (propagation) could become a significant edge source. Correlated markets that haven't moved yet are alpha
  • External signals — Stubbed driver (EXTERNAL_SIGNAL) could incorporate Twitter/X sentiment, news APIs, or on-chain activity for earlier driver detection
  • Hedged fade mode — V6.3 includes a hedged fade design (fade + opposite-side partial hedge) that reduces max loss per trade. Not yet implemented but architecturally planned
  • Multi-exchange — The elasticity framework is exchange-agnostic. Could extend to Kalshi, Manifold, or other prediction markets

Funding & Account Setup

Complete checklist for going from zero to trade-ready on Polymarket. All items must be completed before Stage 3 (first live capital).

Regulatory Notice

  • US persons: The international Polymarket platform (polymarket.com) is geo-blocked for US users per CFTC settlement. Using a VPN violates terms and risks fund freezing.
  • Polymarket US launched Dec 2025 as a CFTC-regulated Designated Contract Market (DCM). Requires full KYC, trading through regulated FCMs, and is limited to approved contract types.
  • International users: Generally unrestricted access. Some countries are blocked (check Polymarket's restricted countries list).
  • Determine your jurisdiction first — this affects which platform, API, and onboarding flow you use.

Setup Checklist

# Task Details Status When Needed
1 Create Polymarket Account Sign up at polymarket.com with email/Google (creates proxy wallet) or connect an external wallet (MetaMask). KYC triggered at high-volume thresholds only (international). TODO Stage 2
2 Set Up Wallet Option A (Recommended): Use Polymarket's proxy wallet (email signup). Gasless transactions, simpler setup.
Option B: Use your own EOA (MetaMask). More control, requires manual token approvals and gas management.
TODO Stage 2
3 Export Private Key Required for programmatic trading. If using proxy wallet: go to polymarket.com/settings or reveal.magic.link/polymarket to export. If EOA: you already have it.
Store securely. Never commit to git. Use env variable or secrets manager.
TODO Stage 2
4 Note Funder Address Your deposit address visible at polymarket.com/settings. For proxy wallets this is the proxy contract address (NOT your underlying EOA). For EOA wallets this is your wallet address. TODO Stage 2
5 Acquire USDC Buy USDC on any major exchange (Coinbase, Binance, Kraken). Starting capital for Stage 3: $200–$500 recommended ($75 max per fade × buffer for multiple concurrent positions + drawdown room). TODO Stage 3
6 Fund Polymarket Wallet Send USDC to your Polymarket deposit address over the Polygon network (chain ID 137). Select “Polygon” as withdrawal network on your exchange.
Wrong network = permanent loss. Send a small test amount ($5) first.
USDC contract: 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174
TODO Stage 3
7 Install SDK Install the official TypeScript CLOB client:
npm install @polymarket/clob-client ethers@5
Alternative: Python client pip install py-clob-client
TODO Stage 2
8 Generate API Credentials Derive L2 API creds from your private key programmatically. Returns: apiKey, secret (base64), passphrase. Used for all authenticated API requests (orders, cancels, balance checks). No separate registration portal needed. TODO Stage 2
9 Set Token Approvals EOA wallets only (proxy wallets skip this). Approve 3 exchange contracts to spend your USDC and Conditional Tokens:
• CTF Exchange: 0x4bFb...982E
• Neg Risk CTF Exchange: 0xC5d5...80a
• Neg Risk Adapter: 0xd91E...296
TODO Stage 2
10 Store Secrets on VPS Set up secure credential storage on trading.professionalwinner.us:
• Private key in environment variable (never in code/git)
• API creds (apiKey, secret, passphrase) in env or .env file
.env in .gitignore (already should be)
TODO Stage 2
11 Test API Read Access Verify the SDK can read market data from the VPS. Public endpoints require no authentication: order books, prices, market metadata. This validates network connectivity and SDK installation. TODO Stage 2
12 Test API Write Access Place and immediately cancel a small limit order ($1, far from market) to verify the full auth flow: L1 signing, L2 headers, order construction, cancel endpoint. Confirms the system can trade when enabled. TODO Stage 2
13 Verify Fee Schedule Confirm actual fees for target markets via API (feeRateBps field). Most markets have zero fees. Fees only on: 5/15-min crypto, NCAAB, Serie A. Update Gate 11 fee rate per market. TODO Stage 2
14 Set Up Withdrawal Path Test withdrawal flow before committing significant capital. Withdraw a small amount of USDC on Polygon back to your exchange. Confirm the full round-trip: exchange → Polymarket → exchange. TODO Stage 3

API Endpoints

CLOB API (Trading)
clob.polymarket.com
Gamma API (Metadata)
gamma-api.polymarket.com
WebSocket (Live Data)
ws-subscriptions-clob...
Data API (Positions)
data-api.polymarket.com

Authentication Architecture

L1: Private Key (EIP-712 signing) | +——> Signs order payloads (every order, locally) +——> Derives L2 API credentials (one-time) | v L2: API Credentials (HMAC-SHA256) | +——> apiKey, secret, passphrase +——> 5 headers per request: POLY_ADDRESS, POLY_API_KEY, | POLY_SIGNATURE, POLY_TIMESTAMP, POLY_PASSPHRASE +——> Used for: posting orders, canceling, checking balances | v SDK handles both layers automatically | +——> @polymarket/clob-client (TypeScript) +——> py-clob-client (Python)

Available Order Types

TypeBehaviorOur Use Case
GTC Good-Til-Cancelled — rests on book until filled or cancelled Primary — fade entry orders (limit)
GTD Good-Til-Date — auto-expires at specified UTC timestamp TTL exits — self-canceling orders
FOK Fill-Or-Kill — fill entirely and immediately, or cancel entirely Exit orders — guaranteed full fill
FAK Fill-And-Kill — fill what you can, cancel remainder Aggressive entry — when speed matters

Fee Structure (Updated)

Good News: Most Markets Have Zero Fees

  • The majority of Polymarket markets charge no trading fees
  • Fees only apply to: 5-min crypto, 15-min crypto, NCAAB, Serie A
  • Fee formula: fee = shares × feeRate × (p × (1-p))^exp — decreases toward price extremes
  • Maker orders always have zero fees (plus rebates from taker fees)
  • Impact on our system: Gate 11 (FEE_RATE = 0.01) is too conservative for most markets. Should be updated to use per-market fee rates from the API (feeRateBps field). This change makes our edge calculation more favorable — more trades pass Gate 11.

Capital Planning

StageCapital RequiredMax ExposurePurpose
Stage 0-1 $0 $0 Logging + paper trading only
Stage 2 $5–10 $1 (test order) API validation, test order + cancel
Stage 3 $200–500 $75 per fade First live trades, $150 drawdown cap
Stage 4 $500–2,000 $500 per fade Escalation: $75 → $150 → $300 → $500
Stage 5 TBD TBD Based on demonstrated edge and capacity

Withdrawal Options

API Rate Limits

EndpointLimitOur Usage
CLOB general9,000 / 10sWell within limits
Market data1,500 / 10sUsing WS instead (no polling)
POST /order3,500 burst / 10sMax ~5 fades/min expected
DELETE /order3,000 burst / 10sCancel on stop/TTL only
Gamma API4,000 / 10sStartup load only (10 markets)

Modifications Log

Chronological record of design changes and implementation decisions.

2026-03-05 — Kalshi Paper Trader + Cross-Signal Detection Deployed
Kalshi as Signal Source:
Built Kalshi paper trading simulator to generate data for improving Polymarket trading. Runs same fade logic on Kalshi’s 4,085 markets (10s orderbook polls).

New files: kalshi/kalshiState.ts (price history buffer), kalshi/kalshiPaperTrader.ts (paper trader + cross-signal detection).
Cross-signal lead detection: When Kalshi moves and Poly hasn’t yet, flags as “Kalshi leads” — predictive signal for Poly entries.
DB: kalshi_paper_trades table with cross-match fields.
Dashboard: Kalshi Paper Trader panel with stats, open positions, cross-signal feed.
Also deployed: Kalshi exchange connection (email/password auth, positions, balance), wallet activity ledger (Polymarket on-chain fills), P&L recomputation fix at engine init.
2026-03-04 — Pipeline Tuning: G3 Spread Gate Widened Deployed
Data-Driven Gate Tuning (Change 6):
Backtest of 2,906 paper trades revealed G3 spread gate (1.5%) was blocking profitable trades. Trades with spread >1.5% had higher win rate (63.8% vs 63.2%) and better avg P&L ($1.43 vs $1.17).

Change: spread <= 0.015spread <= 0.050 in behavior/pipeline.ts G3.
Baseline: G3 was rejecting 17.7% of evaluations reaching it (4,091/23,135).
Expected: G3 pass rate → ~99%+. More flow to G7+.
Next: Lower ε60 candidate threshold (0.8→0.3) and G8 ELASTIC_THRESHOLD (1.30→0.30). Backtest shows ε60 0.30–0.50 zone is most profitable (69.4% win, $1.19 avg, 923 trades).

Parameter Simulation Panel:
GET /api/live/simulate — backtests 8 pipeline configs against paper trade data
• Dashboard table shows trades, win%, avg P&L, total P&L for each config
• Active config highlighted with ★ marker

Modified: behavior/pipeline.ts, server/routes/live.ts, public/live.html
2026-03-04 — Pipeline Alignment + Single-Position Close Deployed
Live Engine → 16-Gate Pipeline Alignment:
The live engine previously ran its own duplicate gate logic (checkEntry()) separate from the authoritative 16-gate pipeline. This meant live and paper could diverge on which signals to trade.

Fix: Removed all entry logic from liveTrader.onPriceUpdate() (now exits only). Added liveTrader.onSignal(candidate) that receives CandidateLog from the pipeline’s setOnWouldTrade() callback — same signal source as the paper trader. Changed pipeline.ts from single callback to array so both paper and live receive every WOULD_TRADE signal. Wired in marketRegistry/index.ts during init.

Single-Position Close:
• New closeSinglePosition() in liveTrader.ts — finds position in-memory or DB, market-sells via CLOB relay FOK order, updates status to closed_manual
• New POST /api/live/close/:tradeId route
• Frontend forceClose() button now calls real API (was a dead alert())
• Added closed_manual to LiveTradeStatus type union

Pipeline Gate Monitor:
• Added live 16-gate visualization to /live.html — pass/reject bars per gate, bottleneck ID
• Shows pipeline runs, candidate count, max ε, bottleneck gate in real-time via WS

Live Stats Cards:
• Replaced minimal DB stats line with full stats grid: Trades, Open, Win Rate, Net P&L, Expectancy, Best/Worst Trade, Avg Hold, Today P&L
• Added best_trade, worst_trade, avg_hold_min to LiveStats interface and DB reader

On-Chain → DB Reconciliation:
GET /api/live/reconcile — compares on-chain vs DB, identifies mismatches
POST /api/live/sync — imports missing on-chain positions into DB, fixes stale entries
• Dashboard reconciliation bar with Sync button, auto-checks every 30s

Dashboard Data Fixes:
• All Trades table: removed filter that hid open trades
• Positions endpoint: DB fallback when in-memory is empty (post-restart)
• Imported 3 on-chain trades missing from DB (Man City, Arsenal, Man United)
• Deleted 4 flood_import test entries
• On-chain portfolio: split active vs resolved, account summary uses active only
• Added DB stats bar (closed/open/W-L/P&L/avg)

Modified: behavior/pipeline.ts, live/liveTrader.ts, live/types.ts, marketRegistry/index.ts, server/routes/live.ts, public/live.html
2026-03-04 — Relay Transparent Proxy + Dashboard Redesign Deployed
Relay Fix — Transparent Proxy:
The CLOB SDK calls multiple endpoints (/tick-size, /neg-risk, /order, etc.) on whatever host it’s initialized with. The relay only had POST /relay, causing all orders to fail with “Cannot GET /tick-size” then “403 Forbidden”. Fixed by adding a catch-all transparent proxy (app.all('*')) that forwards ALL requests to clob.polymarket.com. Auth via UFW firewall (only NJ IP allowed), not header-based.

Zero Orders Root Cause:
After relay fix, orders reached Polymarket but returned “no match” — the extreme-zone markets targeted by the engine have zero ask-side liquidity (books completely empty at <5¢ or >95¢ prices). Added pre-flight orderbook check in orderExecutor.ts: fetches the CLOB orderbook before placing FOK orders, skips if no asks exist. Saves wasted round-trips and provides clear logging.

Dashboard Redesign (live.html):
• New Account Summary banner at top: Cash + Positions + Vault = Total, with P&L and % return
• Separated “Polymarket Portfolio” (real on-chain positions from data API) from “Engine Positions” (bot-managed trades)
• Fixed duplicate /positions route — renamed on-chain to GET /api/live/on-chain
• All sections collapsible (click header to toggle)
• Portfolio table now shows Cost + Value + P&L per position

Modified: pw-clob-relay/index.js, live/orderExecutor.ts, server/routes/live.ts, public/live.html
2026-03-04 — Wallet Generation + Funding Flow Deployed
Added wallet generation and USDC funding flow to the onboarding wizard. Users can now create a fresh Polygon wallet directly from the onboard page without needing MetaMask or Polymarket access.

Changes:
• New "New Wallet" option in Step 1 alongside Magic and External wallet types
POST /api/live/generate-wallet — creates random wallet via ethers.Wallet.createRandom(), encrypts private key with AES-256-GCM
• New Step 3: Fund Wallet — shows wallet address, QR code, exchange funding instructions, and a balance checker for USDC + USDC.e on Polygon
POST /api/live/balance — checks native USDC + bridged USDC.e balances via Polygon RPC
POST /api/live/fund-confirm — transitions state to 'funded'
• Onboarding now 6 steps (was 5): Wallet Type → Setup → Fund → Capital → Tracks → Go Live
• New onboarding state funded between wallet_set and capital_set
• New wallet type generated in addition to magic and external
• Equity input max capped at on-chain balance for generated wallets

Off-Ramp (Withdraw + Export):
POST /api/live/withdraw — server-side USDC transfer to any destination address (decrypts key, builds tx, sends on Polygon). Blocks if positions open.
POST /api/live/export-key — returns decrypted private key for MetaMask import. Requires confirmation phrase.
• Wallet Management panel on /live.html — collapsible section with balance display, withdraw form (destination + amount + token selector), and key export with safety warnings.
2026-03-04 — Live Trading Module Deployed Deployed
Live Trading Module deployed — 6 phases implemented: CLOB relay (Toronto VPS at 134.122.39.253), AES-256-GCM encryption, multi-user onboarding, live trading engine (mirrors fastTrader 5-track logic), dashboard with kill switches, relay health monitoring.

1. CLOB Relay (Toronto VPS):
Dedicated relay server at 134.122.39.253 handles order placement, cancellation, and position queries against the Polymarket CLOB API. Low-latency execution path separate from the main trading server.

2. AES-256-GCM Encryption:
All communication between the trading server and relay is encrypted end-to-end using AES-256-GCM. Wallet private keys and API credentials are never transmitted or stored in plaintext.

3. Multi-User Onboarding:
/onboard.html provides a guided UI for new user setup: wallet configuration, API key provisioning, risk parameter selection, and account activation.

4. Live Trading Engine:
Mirrors the fastTrader 5-track logic (Moderate, Aggressive, Gravity, Deep, Harvest) with real order execution via the CLOB relay. Same entry signals, exit logic, zone awareness, and track configs as paper trading — but placing real orders.

5. Dashboard with Kill Switches:
/live.html provides real-time monitoring of live positions, P&L, and trade history. Per-track and global kill switches allow immediate halt of trading at any level.

6. Relay Health Monitoring:
Continuous connectivity checks to the relay, latency tracking, and automatic reconnection on failure. Health status visible on the live dashboard.

Next: Onboard first user via /onboard.html, monitor live vs paper comparison.
2026-03-03 — Dollar Transparency on Paper Dashboard Deployed
Added full dollar amount transparency to paper.html. All data already existed in DB + WebSocket payload but wasn’t rendered.

1. Capital Summary Banner (new top section):
Capital at Risk (sum of notionalSize for open positions), Net P&L (all tracks), Total $ Won, Total $ Lost, Unrealized P&L, Total Trades (all tracks).

2. Tier Comparison — $ Won / $ Lost rows:
Per-track breakdown of gross dollars won (winCount × avgWin) and lost (lossCount × avgLoss), color-coded green/red.

3. Open Positions table — Stake, Shares, MFE, MAE columns:
Each open position now shows: notionalSize ($), share count, Max Favorable Excursion (best unrealized), Max Adverse Excursion (worst unrealized).

4. Recent Trades table — Stake, Shares, MFE, MAE columns:
Each closed trade now shows the same dollar context — how much was risked, peak gain during hold, peak drawdown during hold.

Frontend-only change — no backend modifications, no service restart needed.
Modified: public/paper.html
2026-03-03 — 3-Page Dashboard Split Deployed
paper.html had 12 sections crammed onto one page — too much data for comprehension. Split into 3 logical pages with clear purpose:

1. paper.html (Overview):
Quick glance — experiment badges, tier comparison, conservative/moderate/aggressive stats, open positions, recent trades. Removed 5 heavy sections (extreme scoreboard, sub-zones, price zones, phantom trades, per-market P&L).

2. harvest.html (Settlement Harvester) — NEW:
Settlement strategy monitoring — harvest track stats, harvest vs fade comparison, settlement-eligible markets (extreme-zone markets with endDate within 30 days), harvest positions with settlement countdown, harvest trade history. New harvestEligible array added to WS broadcast payload.

3. zones.html (Zone Analysis) — NEW:
Deep analysis — extreme zone scoreboard, sub-zone breakdown, price zone analysis, phantom trades (per-gate counterfactual), per-market P&L breakdown. All sections moved from paper.html.

4. Nav Updated Across All Pages:
Added Harvest + Zones links to nav on all 7 pages (index, kalshi, paper, crossarb, diagnostics, plan, + new pages).

5. Kalshi Performance Fix:
4,097 Kalshi markets were being serialized at 4Hz and rendered into DOM every 250ms, freezing the browser. Capped broadcast to top 200 markets + 100 edges. Throttled Kalshi page DOM render to 1x/sec. Reduced Kalshi startup delay from 5s to 1s.

Modified: server/wsBroadcast.ts, public/paper.html, public/harvest.html (new), public/zones.html (new), public/index.html, public/kalshi.html, public/crossarb.html, public/diagnostics.html, public/plan.html, kalshi/registry.ts
2026-03-03 — Settlement Harvesting Track (Backtest-Driven) Deployed
Backtested 834 historical trades (v1+v2): settlement harvesting beats pure fade $1.67 vs $0.45 per trade. Key insight: at inner extreme (10-15¢) settlement dominates ($286 vs $20 fade), but at ultra-extreme (<5¢) fade wins because 5% wrong = $50 loss on large positions.

1. Harvest Track:
Extreme-only, settlement fallback — when fade TTL expires or stops, holds to market settlement instead of closing. Only enters markets settling within 48 hours. 25 max open, 5-min TTL for fade attempt, then hold to settlement. 72-hour zombie cap safety valve.

2. MarketBook endDate:
Polymarket Gamma API endDate now stored on MarketBook and refreshed every 15 minutes. Used for settlement proximity gate (only enter if settling within maxHoursToSettlement).

3. TrackConfig Extensions:
settlementFallback (hold to settlement on TTL/stop), maxHoursToSettlement (proximity gate).

Modified: paper/types.ts, paper/fastTrader.ts, marketRegistry/types.ts, marketRegistry/registry.ts, server/reviewTrigger.ts, public/paper.html
2026-03-03 — Extreme Zone Expansion: Freeze Baseline + Experiments Deployed
Extreme zone is the only profitable zone (76 trades, +$65, 78.9% WR). Tainted data archived as v2 (488 trades). Clean signal + experimental tracks deployed:

1. Elasticity Gate (All Fast Tracks):
All fast tracks now require minimum epsilon60 before entry (default 0.5, per-track configurable). Filters noise/permanent price shifts without the full 16-gate pipeline. Epsilon values populated on positions.

2. Early Bail on Zero MFE:
If MFE still 0 after 90 seconds, signal was permanent shift — bail early instead of waiting for full TTL.

3. Gravity Track (Extreme-Only Harvester):
Lower entry bar (0.5¢ move, e60>0.3), shorter TTL (2min), faster cooldown (15s), 20 max open. Hypothesis: higher frequency captures more total P&L in the structural edge zone.

4. Deep Track (Ultra-Extreme Only):
Trades only <8¢/>92¢, 45% revert target (vs 30%), e60>0.2. Hypothesis: deep extremes revert harder, higher targets achievable.

5. Expectancy-Delta Alert:
Immediate email alert if expectancy and avg P&L diverge by >$2.00 after 50 trades on any track.

6. Dashboard Upgrades:
Dynamic tier columns (auto-discover tracks), experiment status badges with delta vs baseline, extreme sub-zone breakdown panel (price bucket comparison across tracks).

Modified: paper/types.ts, paper/fastTrader.ts, db/readers.ts, server/routes/paper.ts, server/wsBroadcast.ts, server/reviewTrigger.ts, public/paper.html
2026-03-03 — Data-Driven Strategy v2 (351-Trade Analysis) Deployed
Deep analysis of 351 trades revealed stops destroying all profit. Three data-driven changes + clean reset:

1. Extreme Zone: Remove Stops Entirely
73% WR in extreme zone but stops consumed all target profit. At extreme prices (<15¢/>85¢), the 0/1 boundary IS the natural stop. Now only TTL + boundary handle exits. Stop set to 0.99/0.01 (effectively unreachable).

2. Leaning Zone: Widen Stops 3×
42 leaning stops ate all target profit. Stop widening increased from 1.5× to 3.0×. Gives more room for reversion before getting shaken out.

3. Disable Moderate Extreme Entries
Moderate track extreme zone: 28 trades, negative expectancy, -$58. Moderate thresholds don’t work for extreme prices. Now skips entry when zone === 'extreme' && track === 'moderate'.

4. Clean Reset (paper_trades_v1 archive)
365 old trades archived to paper_trades_v1, main table truncated. All alert state files cleared. Clean measurement under new rules starting from zero.

Modified: paper/fastTrader.ts (stop removal, leaning widen 1.5→3.0, moderate extreme block)
2026-03-03 — Zone-Aware Strategy + Market Expansion Deployed
Data-driven adjustments based on 207 trade analysis. Two changes to flip the numbers:

1. Share Cap (MAX_SHARES = 500):
At extreme prices ($0.03), $50 notional = 1,667 shares. A tiny adverse move = catastrophic loss. Moderate extreme zone lost $40.63 from just 2 stopped trades. Share cap limits max exposure. At $0.03 entry: 500 shares × $0.03 = $15 notional (vs $50 uncapped).

2. Zone-Aware Stop Widening:
Stops are the #1 profit killer. 40 leaning-zone stops on aggressive = -$72.64, wiping all wins.
  • Extreme zone: 2.0× wider stops (boundary provides natural protection)
  • Leaning zone: 1.5× wider stops (reduce stop rate, let more revert)
  • Midrange: unchanged
3. Market Expansion (50 → 100):
150 of top 200 Polymarket markets are at extreme prices. Doubling coverage from 50 to 100 dramatically increases extreme zone trading opportunities.

4. Extreme Zone Cooldown Reduction:
100% win rate → 30s max cooldown for extreme zone entries (vs 3-5 min normal). Faster re-entry on proven-profitable zone.

Modified: paper/fastTrader.ts (zone classification, share cap, stop widen, cooldown), marketRegistry/registry.ts (MARKET_LIMIT 50→100)
2026-03-03 — Alert System v2 Rewrite Deployed
Old review trigger was broken: fired on stale ghost data (100 conservative trades that were actually moderate/aggressive from before track filter fix), permanently disarmed both triggers. No daily emails, no milestone emails, no Friday deadline email would have come.

Complete rewrite with 3 independent alert channels:
  • Daily Summary at 8 AM CT — full report email every morning
  • Milestones at 250, 500, 1000, 2000 total trades (all tiers combined)
  • Friday Deadline March 7 12:00 CT — comprehensive Go/No-Go review
Each email now includes: tier comparison (11 metrics), price zone breakdown, top 10 markets by P&L, phantom gate verdicts, explicit “Next Steps & Triggers” section.

State tracking: Separate files (.review_milestones, .review_deadline_fired, .review_daily_last) — never one-shot again. Failed sends retry on next 5-min check.

Destination: jayson@professionalwinner.com (env: ALERT_EMAIL)

Modified: server/reviewTrigger.ts (complete rewrite)
2026-03-03 — Data Intelligence Overhaul + Price Zone Discovery Deployed
Major shift in analytical lens: moved from “how are our trades doing?” to “where is the money, and what are we missing?” Discovered critical price zone segmentation and deployed counterfactual phantom tracking.

KEY DISCOVERY — Price Zone Alpha:
Analysis of 176 paper trades revealed three distinct strategy zones by entry price:
  • Extreme (<15¢ / >85¢): 16 trades, 100% win rate, $16.49 profit, $1.03 expectancy. Markets near 0/1 boundaries revert almost every time due to hard floor/ceiling. This is the low-hanging fruit.
  • Leaning (15-30¢ / 70-85¢): Mixed results. Aggressive: 93 trades, 62% WR, -$8.02 net. Moderate: 30 trades, 63% WR, +$20.63.
  • Midrange (30-70¢): Noisy, barely profitable. High variance, low edge.
KEY DISCOVERY — Stop Loss Problem:
Moderate tier: 13 stopped trades = -$67.72 loss, exceeding all target_hit profit ($58.17). Stops are too tight relative to move size, especially in leaning zone. One catastrophic trade: $0.037 entry × 1,351 shares → -$37.16 from a 2.75¢ move. Extreme prices need share caps or reduced notional.

KEY DISCOVERY — Market Concentration:
Only 6 unique markets across 176 trades. Iran Strait of Hormuz = 84 trades alone. Not 176 independent samples — more like 6 hypotheses tested repeatedly. Per-market P&L table now exposes this.

New capabilities deployed:
  • Phantom Trade Tracker (paper/phantomTracker.ts): Tracks counterfactual P&L for every rejected pipeline signal. Per-gate verdict shows which gates are COSTING money vs SAVING money.
  • Price Zone Analysis: DB-driven zone breakdown (extreme/leaning/midrange) for moderate & aggressive. Shows trades, win rate, P&L, target hits, stop losses per zone.
  • Per-Market P&L: Breakdown by individual market × track. Exposes market concentration risk.
  • Entry condition capture: New DB columns spread_at_entry, price_move_60s, fee_rate_bps on every trade. Real fee rates from CLOB API (currently 0 bps for all geopolitical/political markets).
  • Moderate & Aggressive stat cards on dashboard alongside conservative.
Bug fixes:
  • Conservative paper trader was loading ALL tracks’ trades on restart (missing track filter in readPaperTrades calls). Dashboard showed 100 ghost trades from moderate/aggressive. Fixed.
Fee research (Polymarket): Majority of markets have zero fees. Only crypto (1H/4H/daily/weekly), NCAAB, and Serie A have taker fees (peak 1.56% at 50¢, dynamic curve). Gate 11’s 1% fee assumption is too conservative for current market mix.

New files: paper/phantomTracker.ts, paper/feeHelper.ts
Modified: paper/types.ts, paper/paperTrader.ts, paper/fastTrader.ts, db/writers.ts, db/readers.ts, behavior/pipeline.ts, behavior/index.ts, marketRegistry/index.ts, server/wsBroadcast.ts, public/paper.html

Next action: Let phantom data + zone data accumulate through Friday. Conservative stays untouched. Evaluate zone-aware strategy adjustments based on data.
2026-03-03 — Multi-Tier Paper Trading (Parallel Strategy Testing) Deployed
Added 2 parallel paper trading tracks alongside the conservative 16-gate pipeline for faster statistical comparison. All paper-only, zero risk.

Tier 1 (Conservative): Full 16-gate pipeline, 1¢ min move, ≤1.5% spread, 5 max open, 50% revert, 3m TTL. ~1/hr signals.
Tier 2 (Moderate): Price action + liquidity, 1.5¢ min move, ≤3% spread, 8 max open, 40% revert, 5m TTL, 5m cooldown. ~10-20/hr.
Tier 3 (Aggressive): Pure price action, 0.7¢ min move, ≤5% spread, 12 max open, 30% revert, 8m TTL, 3m cooldown. ~30-60/hr.

Key insight: Moderate uses a HIGHER price floor (1.5¢) than conservative's 1¢ but skips all behavioral gates — it selects for bigger dislocations and bets on mean-reversion of significant moves without needing classifier/reflexivity confirmation. Aggressive casts the widest net with the lowest bar (0.7¢).

Key questions: Does behavioral pipeline add value? (T1 vs T2). Does selectivity matter? (T2 vs T3).

New file: paper/fastTrader.ts — config-driven multi-track trader with in-memory state, cooldowns, DB persistence.
Modified: paper/types.ts (+track field, +TrackConfig), behavior/index.ts (multi-callback array), db/writers.ts (+track column + ALTER TABLE), db/readers.ts (+track filter, +readPaperStatsByTrack), marketRegistry/index.ts (+fastTrader init & callback), server/routes/paper.ts (+/api/paper/tracks), server/wsBroadcast.ts (+tracks payload), server/reviewTrigger.ts (multi-tier email comparison), public/paper.html (tier comparison table, track badges)

Target by Friday: Conservative ~50, Moderate ~500+, Aggressive ~1500+ trades for actionable P&L distributions.
2026-03-03 — Alert System v2 (Multi-Trigger) Armed
Complete rewrite of review trigger. Old system was one-shot (fired on stale ghost data, permanently disarmed). New system has three independent alert types:

Alert 1 — DAILY SUMMARY (8:00 AM CT every day):
Full report with tier comparison, zone analysis, per-market P&L, phantom tracker verdicts. Sent to jayson@professionalwinner.com. Includes “Next Steps & Triggers” section with exact milestone distances.

Alert 2 — MILESTONES (250, 500, 1000, 2000 total trades):
Fires when total trades across ALL tiers (not just conservative) hits each milestone. Each milestone fires independently. Full report at each milestone.

Alert 3 — FRIDAY DEADLINE (Fri March 7 12:00 CT):
Comprehensive review email regardless of trade count. Go/No-Go decision point for real capital.

Email contents (all alerts): Tier comparison table (9 metrics + spread/move), price zone analysis (extreme/leaning/midrange × track), top 10 markets by P&L, phantom tracker per-gate verdicts, explicit next steps with milestone distances.

Bug fixed: Old trigger fired on stale in-memory data (100 ghost conservative trades from before track filter fix). .review_triggered file permanently disarmed both triggers. New system uses separate state files for milestones, deadline, and daily.
2026-03-03 — Paper Trading Projections Baseline Set
Analyzed 26 captured WOULD_TRADE signals (11 unique positions) from March 1–2. All signals passed all 16 gates. Signal rate: ~1/hr during active events (sports, crypto hourly). Signal quality: 82% CAUSAL reflexivity, 100% OVERSHOOT classifier, median ε60 = 2.3.

Per-trade economics ($50 notional): Target hit avg +$11.10, TTL expire avg +$2.03, Stop loss avg −$34.79. Asymmetric risk/reward (1:0.33) requires high win rate + TTL cushion.

Friday March 7 target: ~50 trades, moderate scenario +$99 net P&L (+4% ROI on $2,500 deployed). Breakeven requires ≥40% target-hit rate when 50% of exits are TTL. Scorecard table added to Next Steps section for Friday review.

Note: Paper trader was wired after these 26 signals fired (deployed ~23:10 March 2). Actual paper trade accumulation begins March 3. The projections assume continued ~1 signal/hr during event-rich hours (sports evenings, crypto hourlies).
2026-03-02 — Cross-Platform Arb Detection Complete
Fuzzy text matching between 50 Polymarket and 4000+ Kalshi markets using Jaccard similarity with inverted index and entity boost. Cross-platform edge engine computes |polyMid - kalshiMid| - 2% fees with window tracking. Real-time updates on every Poly WS tick for matched markets.

New files: crossArb/types.ts, crossArb/matcher.ts, crossArb/edgeEngine.ts, crossArb/index.ts, server/routes/crossArb.ts, public/crossarb.html
Modified: kalshi/registry.ts (+runMatcher after pollEvents), marketRegistry/registry.ts (+runMatcher after refreshMarkets), marketRegistry/edgeEngine.ts (+updateCrossEdge in checkMarket), marketRegistry/index.ts (+initCrossArb), db/writers.ts (+cross-arb tables/writes), db/readers.ts (+cross-arb reads), db/index.ts (+exports), server/app.ts (+crossArb routes), server/wsBroadcast.ts (+crossArb payload), all HTML pages (+CrossArb nav link)
Result: 13+ matched pairs on first run (0.55–0.88 scores). High-confidence matches: Judy Shelton/Rick Rieder/Christopher Waller Fed chair (0.875), Alireza Arafi Supreme Leader (0.857).
2025-02-28 — Stage 0 Deployed Complete
Initial deployment of V6.3 behavioral pipeline. 8 new files created in behavior/. Pipeline hooks added to registry.ts (2 call sites). Behavior initialization added to index.ts. Build verified, service restarted, health check passed.
2025-02-28 — Build Fix: PriceEntry Import Complete
reflexivity.ts imported PriceEntry from marketState.ts but it was defined in types.ts. Fixed import path. TypeScript compilation passed with zero errors.
2025-02-28 — Diagnostics Instrumentation Complete
Added diagnostics.ts with ε distribution tracking, gate counters, baseline stability reporting, and memory monitoring. Lowered ε log threshold from 1.2 to 0.8 for validation. Added getBaselineStats() to drivers.ts. Modified pipeline.ts to call recordGateResult() and recordEpsilon(). 60s periodic reports confirmed working.
2025-02-28 — Funding & API Research Complete
Researched complete Polymarket onboarding flow: account setup, wallet types (EOA vs proxy), USDC on Polygon funding, CLOB API authentication (L1/L2), SDK options, fee structure, order types, withdrawal paths, and regulatory status. Key finding: most markets have zero trading fees (our 1% assumption is too conservative). Gate 11 update queued for Stage 2. Added Funding & Account Setup section with 14-item checklist. Added build plan page at /plan.html with nav links from dashboard.
2026-02-28 — 11-Hour Diagnostic Review & Expansion Complete
Full diagnostic review after 11 hours of Stage 0 operation (155K pipeline runs). Key finding: all candidates came from illiquid sports markets; Gate 3 (liquidity) killed 100%. Changes made:
  • Expanded from 10 → 50 markets (top by volume from Gamma API)
  • Added 15-minute market refresh cycle with WS reconnect on change (registry.ts: refreshMarkets() + startRefreshCycle(); wsManager.ts: reconnect())
  • Lowered Gate 3 volume floor: $10K → $5K (pipeline.ts)
  • Lowered classifier strong-feature count: 3 → 2 (types.ts)
  • Added behavior panel to dashboard — pipeline stats, gate funnel, ε distribution (behavior.js, diagnostics.ts: getSnapshot(), wsBroadcast.ts: behavior data in WS updates)
  • Created CLAUDE.md project instructions and comprehensive memory files for session continuity
2026-02-28 — Post-Expansion Validation Complete
First data after expansion shows dramatic improvement: 80K pipeline runs in 18 min, 17,733 candidates > ε 1.2 (22%), classifier now firing OVERSHOOT labels (conf 0.84–0.92). Gate 2 pass rate jumped from 0.6% to 64%. Gate 3 remains the bottleneck — strongest signals come from short-duration crypto prediction markets (Solana/Bitcoin 5-min windows) with thin liquidity. Key observation: High-volume markets (ETH range, Netflix, Real Madrid) have stable baselines (stability >0.7) and active books, but haven't produced elastic overshoots yet. Need to observe over longer window (12h+) to see if liquid markets generate Gate 3-passing signals.
2026-02-28 — Diagnostics History Page Complete
Added /diagnostics.html page with 30-minute automated snapshots. Backend takes snapshots at :00 and :30 each hour (plus one on startup), stores up to 48 (24 hours rolling). API at /api/diagnostics/history. Page shows trend strip (latest metrics), expandable snapshot cards with full gate tables, epsilon/driver/price-move distributions. Auto-refreshes every 60s. Nav link added to main dashboard.
  • diagnostics.ts: startSnapshotCycle(), getSnapshotHistory()
  • app.ts: /api/diagnostics/history endpoint
  • public/diagnostics.html: Full frontend with trend strip + snapshot cards
2026-03-01 — Kalshi Data Collection & Dashboard Complete
Phase 1 of cross-platform arb detection. Kalshi market data collection running parallel to Polymarket. REST polling via https module (Node native fetch triggers Kalshi rate limits).
  • 4089 markets from 1000 events loaded, 60s event refresh cycle
  • Top 20 orderbooks polled every 10s (400ms stagger, ~2 req/s of 20 budget)
  • 3160 edges computed (intra-Kalshi sell/buy edges + spreads)
  • Non-blocking init — Kalshi failures never affect Polymarket pipeline
New files:
  • kalshi/types.ts — API + internal type definitions
  • kalshi/registry.ts — REST polling with pagination + orderbook stagger
  • kalshi/edgeEngine.ts — Intra-Kalshi edge computation
  • kalshi/index.ts — Init entry point + re-exports
  • server/routes/kalshi.ts — Debug API (/debug/kalshi/markets, /edges, /status)
  • public/kalshi.html — Dashboard with markets table, edge scanner, poll status
Modified: app.ts (route mount), wsBroadcast.ts (kalshi WS payload), marketRegistry/index.ts (non-blocking init call), nav links on all pages.
Next: Phase 2 — cross-platform market matching + arb detection between Polymarket and Kalshi.
2026-03-01 — MariaDB Persistent Storage + Adminer Complete
All trading data was in-memory and lost on restart. Added MariaDB for persistent storage with Adminer web admin at /adminer (protected by same cookie auth).
  • MariaDB 10.6 installed with 256MB buffer pool, 50 max connections
  • 4 tables: diag_snapshots, kalshi_market_snapshots, kalshi_edge_snapshots, poly_edge_history
  • Adminer at /adminer via PHP-FPM 8.1, Caddy route with cookie auth
  • mysql2 connection pool (5 connections), fire-and-forget writes, non-fatal
  • DB-backed diagnostics history: /api/diagnostics/history?hours=N reads from DB with in-memory fallback (survives restarts)
New files:
  • db/pool.ts — mysql2 connection pool + testConnection()
  • db/writers.ts — Fire-and-forget writers for all 4 tables
  • db/readers.tsreadDiagSnapshots(hours) for history API
  • db/index.ts — Barrel re-exports
Modified: marketRegistry/index.ts (DB test on boot), behavior/diagnostics.ts (persist snapshots), kalshi/registry.ts (persist markets + edges after event polls), marketRegistry/edgeEngine.ts (persist closed Polymarket edges), server/app.ts (DB-backed diagnostics history with ?hours=N param).
Design rules: All writes fire-and-forget (no await in hot path). If MariaDB is down, app runs identically to before. Kalshi edges only written after 60s event polls (not 10s orderbook polls) to control volume.
2026-03-01 — Tiny File Manager Complete
Installed Tiny File Manager at /files for web-based file browsing, editing, uploading, and downloading. Single PHP file served by PHP-FPM 8.1 via Caddy. Protected by same cookie auth as all other tools. Root path set to /home/jayson. Dark theme, hidden files visible. www-data added to jayson group for read access.
2026-03-01 — Duplicati Backup Complete
Installed Duplicati v2.2.0.3 backup system with web GUI at /backup and CLI at duplicati-cli. Runs as systemd service on port 8200 (localhost only), proxied through Caddy with cookie auth. Supports S3, SFTP, Backblaze, local, and 30+ other backup targets. Encrypted, deduplicated, scheduled backups with web-based restore.
2026-03-01 — Kalshi Data Retention Policy Complete
Kalshi snapshot tables were growing at ~3.3 GB/day with no pruning (2.9M market rows + 2.2M edge rows in first 12h, 1.6 GB total). Added automated 7-day retention policy.
  • Hourly prune via setInterval in Kalshi registry init + one run at startup
  • DELETE ... LIMIT 500000 per table per cycle to avoid long-running locks
  • Targets kalshi_market_snapshots and kalshi_edge_snapshots where poll_ts < 7 days ago
  • Fire-and-forget, non-fatal — same pattern as all DB writes
  • Expected steady-state: ~23 GB cap (vs unbounded growth)
Modified: db/writers.ts (pruneKalshiSnapshots()), db/index.ts (re-export), kalshi/registry.ts (hourly timer).
2026-03-01 — Market Selection Fix: 24h Volume + Delta Snapshots Complete
Two critical fixes to the Polymarket pipeline:
  • Market selection by 24h volume: Changed Gamma API query from order=volume (lifetime) to order=volume24hr. Was pulling stale high-total-volume markets; now gets the 50 most actively traded markets. Bottom market now has $500K+ 24h volume vs $9 before.
  • Volume field fix: market.volume now stores m.volume24hr instead of m.volume (lifetime). Gate 3 liquidity check uses this value.
  • Delta-based diagnostics: Snapshots now store per-window deltas (pipeline runs, candidates, distribution buckets, gate counts) instead of cumulative totals. Restarts no longer produce misleading zero snapshots. Old cumulative data truncated.
Impact on gate funnel (first 2 minutes):
  • Gate 2 pass rate: 0.09% → 52%
  • Gate 3 pass rate: 0% → 95%
  • Gate 7 now active filter (68% pass) — first time pipeline flows past Gate 3
  • Max ε = 0.7 (Sunday afternoon, awaiting news/events for higher volatility)
Modified: registry.ts (API query + volume field), diagnostics.ts (delta snapshots), diag_snapshots table truncated.
2026-03-01 — PWSESSID Auth (Shared PW Login) Complete
Replaced hardcoded pw_trade_token with real PW auth system. Trading app now shares the same login session as PW CRM via PWSESSID cookie.
  • Auth flow: PWSESSID cookie → auth.professionalwinner.us/auth/validate-session.php → identity_id, email, role
  • 5-min session cache to avoid hitting auth server on every request
  • WebSocket auth upgraded to async PWSESSID validation
  • Login redirect to auth.professionalwinner.us/trading-login/ (dedicated login page)
  • Caddy updated: adminer/files/backup routes now check PWSESSID
  • Removed dead auth.ts file and /api/login endpoint
Modified: server/authMiddleware.ts (rewritten), server/app.ts, server/wsBroadcast.ts, server/routes/health.ts, public/login.html, public/js/app.js, public/diagnostics.html, public/plan.html, /etc/caddy/Caddyfile.
2026-03-01 — Dedicated Trading Login Page Complete
Created auth.professionalwinner.us/trading-login/ — a dedicated login page for the trading app (matching the pattern of CRM’s crm-login/). Dark themed to match the trading UI. After login, redirects directly to trading.professionalwinner.us instead of the app chooser.
  • Auth server: trading-login/index.php created on Hestia
  • Trading app: server/app.ts AUTH_LOGIN_URL → trading-login/
  • Login page: public/login.html button updated to trading-login/
2026-03-02 — Paper Trading Engine + CLOB Client Complete
Deployed paper trading engine and Polymarket CLOB REST client. Paper trader opens simulated positions on WOULD_TRADE signals with target/stop/TTL exit logic, tracks live P&L via price callbacks, persists to paper_trades DB table. CLOB SDK installed for read-only market data (orderbooks, tick sizes, fee rates). Book validator runs every 5min comparing WS-derived vs REST prices.
  • New files: paper/types.ts, paper/paperTrader.ts, server/routes/paper.ts, api/clobClient.ts, api/bookValidator.ts, public/paper.html
  • Modified: behavior/pipeline.ts (setOnWouldTrade callback), behavior/index.ts (setOnPriceUpdate callback), marketRegistry/index.ts (wire paper + book validator), db/writers.ts (paper write/update), db/readers.ts (paper read/stats), server/app.ts (mount /api/paper), server/routes/debug.ts (CLOB routes), server/wsBroadcast.ts (include paper in broadcast), public/index.html (Paper Trader nav link)
  • NPM: @polymarket/clob-client (72 new packages)

V6.3 Hardening Patches (P1–P14)

The V6.3 design incorporates 14 hardening patches identified through adversarial stress testing. These patches address fragile assumptions, uncovered failure modes, and internal inconsistencies from earlier design iterations (V6.0 → V6.2).

Patch Name What It Does Status
P1Depth ShareUse depth share instead of volume share for impact estimationIn Gate 13
P2Resolution RiskBlock fades on markets approaching resolutionStubbed (Gate 4)
P3Fee FilterNet edge must be positive after 2× fee deductionIn Gate 11
P4Stop GeometryStop distance must exceed spreadIn Gate 12
P5Partial FillHandle partial fills in position trackingStage 2
P6Refill PersistenceSpoof defense: verify book refill persists for 15sStage 2
P7Propagation GuardBlock fades during cross-market propagation wavesStubbed (Gate 5-6)
P8Multi-Timescale GateRequire ε confirmation across 15s AND 60s windowsIn Gate 8
P9Target RandomizationRandomize reversion targets to avoid predictable exitsStage 3
P10Group Exposure CapCap exposure per correlated market groupStubbed (Gate 15)
P11Baseline GuardDetect and handle baseline poisoning via CV stabilityIn diagnostics
P12Stop NoiseAdd volatility buffer to stop distanceStage 3
P13Regime ReversionCondition reversion targets on flow regimeStage 3
P14TTL RandomizationRandomize hold TTL × Uniform(0.85, 1.15)Stage 3
Last updated: 2026-03-04 — Live Trading Module deployed (CLOB relay, encryption, onboarding, live engine, kill switches, health monitoring)