# Lab 4 — Build Plan

## What Lab 4 is
A copy of Lab 3 with 4 targeted fixes based on data analysis from Lab 2 (276K trades) and Lab 3 (25K trades).
Runs in parallel with Lab 2 and Lab 3. New folder, new database, new cron job.

## Why these fixes
- Lab 3 early failure rate: 34% of trades → costs -$3,688 (entire loss)
- Lab 3 without early failure would be: +$2,540 profit
- Score analysis on Lab 2: score 76+ has 13% EF rate vs 22% for below 60 (modest but real)
- Root cause of bad entries: trading when market is falling (breadth), BTC dropping, price ticking down at entry moment

---

## 4 Changes vs Lab 3

### Change 1 — Disable early failure
Remove the early failure exit block from MassStrategyEngine.php entirely.
Trades will only exit via: DYNAMIC STOP, SIGNAL EXIT, MAX HOLD EXIT.

In manageOpen(), delete this block:
```
elseif($age>=(int)LAB3_EARLY_FAILURE_MIN_MS){
    if($grossPct<=(float)LAB3_EARLY_FAILURE_PCT && ...){ $reason='EARLY FAILURE'; }
}
```

### Change 2 — Entry score filter (strategies >= 70 only)
In MassStrategyEngine.php seed() function, only seed strategies where entryScore >= 70.
~320 active strategies instead of 648. Fewer trades, stronger signals.

In seed():
```php
foreach (StrategyFactory::all() as $v => $p) {
    if ((int)$p['entryScore'] < 70) continue;  // ADD THIS LINE
    if (in_array($p['style'], LAB4_DISABLED_STYLES)) continue;
    // ... rest of seed logic
}
```

### Change 3 — Market breadth filter
In manageEntries(), before opening any trade, check breadth_up_pct from context.
If less than 45% of coins are going up → skip all entries this tick.

```php
$breadth = (float)($ctx['breadth_up_pct'] ?? 50);
if ($breadth < 45.0) return;  // broad market falling, skip all entries
```

### Change 4 — Combined entry gate (BTC + micro-momentum)
In manageEntries(), in the READY loop before opening a trade, add:

```php
// BTC direction check
$btcTag = $tags['btc'] ?? '';
if ($btcTag === 'BTC_STRONG_DOWN') { /* skip */ continue; }

// Micro-momentum check — price must be ticking UP at entry moment
$micro15 = (float)($d['micro15'] ?? 0);
$micro30 = (float)($d['micro30'] ?? 0);
if ($micro15 <= 0 || $micro30 <= 0) { /* skip */ continue; }
```

---

## Files to create

### New files (Lab 4 specific)
- `Lab4/config.php` — all LAB4_ constants + LAB2_ aliases
- `Lab4/MassStrategyEngine.php` — copied from Lab3, with changes 1-4 above
- `Lab4/data_lab4/` — data directory (auto-created)

### Copied unchanged from Lab3 (LAB2_ aliases handle them)
- LabDatabase.php
- MarketScanner.php
- MarketGate.php
- MarketClassifier.php
- StrategyFactory.php
- Indicators.php
- Binance.php
- worker.php
- install.php
- runner.php
- tick_api.php
- shard_api.php
- deep_api.php
- deep_run.php
- deep_status_api.php
- health_api.php
- opcache_reset.php
- local_api_guard.php
- schema.sql
- simple.php
- analysis.php
- analysis_build.php
- strategy_market_tags.csv

---

## config.php key values

```php
define('LAB4_DB_NAME',          'tmepulse_lab4_data');
define('LAB4_DB_USER',          'tmepulse_crm_db');
define('LAB4_DB_PASS',          '');              // fill in on server
define('LAB4_RUNNER_TOKEN',     'lab4_2026_c5m8');
define('LAB4_EXPERIMENT_NAME',  'LAB4_STRONG_GATE');
define('LAB4_DATA_DIR',         __DIR__ . '/data_lab4');
define('LAB4_BUILD',            '2026-10-01-lab4');
define('LAB4_WORKER_BASE_URL',  'https://cheerful-lime-chihuahua.167-86-108-123.cpanel.site/lab4');

// Lab 4 specific
define('LAB4_DISABLED_STYLES',      ['RECOVERY', 'PULLBACK', 'BREAKOUT']);  // same as Lab 3
define('LAB4_BLOCKED_REGIMES',      ['BULLISH']);                           // same as Lab 3
define('LAB4_MIN_ENTRY_SCORE',      70);          // NEW — only strong signals
define('LAB4_BREADTH_MIN_PCT',      45.0);        // NEW — min % coins rising to allow entry
define('LAB4_BLOCK_BTC_STRONG_DOWN', true);       // NEW — no trades when BTC crashing
define('LAB4_REQUIRE_MICRO_UP',     true);        // NEW — micro15 > 0 AND micro30 > 0 at entry

// Early failure DISABLED
define('LAB4_EARLY_FAILURE_DISABLED', true);
define('LAB4_WIDE_STOP_SHADOW',     false);

// All LAB2_ aliases → LAB4_ values (so copied files work unchanged)
define('LAB2_DB_NAME', LAB4_DB_NAME);
// ... etc
```

---

## Server setup steps (after uploading)

1. Create database `tmepulse_lab4_data` in cPanel → MySQL Databases
2. Add user `tmepulse_crm_db` with All Privileges
3. Edit `lab4/config.php` → fill in `LAB4_DB_PASS` (use nano, not sed)
4. Run installer: `php ~/...cpanel.site/lab4/install.php`
5. Add cron job: `*/1 * * * * php ~/...cpanel.site/lab4/worker.php`
6. Verify: `curl .../lab4/health_api.php?token=lab4_2026_c5m8`

---

## Expected behaviour vs Lab 3

| Metric | Lab 3 | Lab 4 expected |
|--------|-------|----------------|
| Active strategies | 648 | ~320 |
| Trade volume | high | ~40% of Lab 3 |
| Early failure | 34% of trades | 0% (disabled) |
| Entry gate | regime + vol tag | regime + vol + breadth + BTC + micro |
| Exits | 4 types | 3 types (no early failure) |
| WR target | 37.5% | 50%+ |

---

## What we are testing
Can stronger entry conditions (score 70+, breadth > 45%, BTC not crashing, micro-momentum positive)
combined with letting trades run naturally (no early failure cut)
produce a win rate above 50% and consistent profit?
