#!/bin/bash
# TSX Swing Trade Daily Scan
# Runs every weekday at 9am MDT via cron (system timezone: America/Edmonton).

REPO=/media/usb/claude/SwingTrader
LOG=$REPO/daily_run.log
HOME=/home/neilm
export HOME

# Abort if USB drive is not mounted
if [ ! -d "$REPO" ]; then
    echo "$(date) ERROR: $REPO not found. Is the USB drive mounted?" >> /tmp/swingtrader_error.log
    exit 1
fi

echo "=== $(date) ===" >> "$LOG"

/home/neilm/.local/bin/claude -p \
  --dangerously-skip-permissions \
  --allowedTools "Bash,Read,Write,WebSearch,WebFetch" \
  2>&1 >> "$LOG" << 'PROMPT'
Run my daily TSX swing trade scan. Get today's date by running: date +%Y-%m-%d

**Step 1 — Read these two files before doing anything else:**
- /media/usb/claude/SwingTrader/screen_criteria.json  (all filter rules)
- /media/usb/claude/SwingTrader/positions.json         (currently held positions)

**Step 2 — Run these 4 web searches in parallel:**
1. TSX swing trade setups canada.swingtradebot.com today
2. TSX stocks strong buy technical rating above 200 day moving average site:barchart.com
3. TSX breakouts technical analysis site:theglobeandmail.com/investing
4. Canadian swing trade candidates TSX site:tradethatswing.com OR site:canada.swingtradebot.com

**Step 3 — For every stock the screeners return, extract only:**
ticker, price_cad, rsi_14, macd_histogram_positive, above_200d_ema, next_earnings_date, pe_ratio

Immediately discard any stock where: RSI <35 or >65, price below 200d EMA,
earnings within 3 trading days, or market cap <$500M CAD.

**Step 4 — Score each surviving candidate (keep only scores 3-5):**
+1 price above 200d EMA
+1 pullback to 20d or 50d EMA
+1 RSI between 35-55
+1 volume declining on the pullback
+1 MACD crossed or about to cross positive

**Step 5 — Check each open position in positions.json against these exit rules:**
- Stop hit → EXIT
- Earnings within 3 trading days → EXIT
- Held 3+ days with no progress toward T1 → EXIT (time stop)
- A new candidate scores 4+ and this position scores 2 or less → flag SWAP
- Otherwise → HOLD, note whether T1 or T2 has been hit

**Step 6 — Write the output file.**
Use today's actual date in the filename.
Path: /media/usb/claude/SwingTrader/swing_trade_YYYY-MM-DD.json

Use null for any field you cannot confirm. No prose guesses.

Schema:
{
  "scan_date": "",
  "macro_notes": "",
  "signals": {
    "new_buys": [
      {
        "rank": 1,
        "ticker": "",
        "company": "",
        "sector": "",
        "price_cad": null,
        "setup_type": "",
        "setup_score": null,
        "rsi_14": null,
        "macd_positive": null,
        "above_200d_ema": null,
        "pe_ratio": null,
        "next_earnings": "",
        "entry_zone_cad": "",
        "stop_cad": null,
        "t1_cad": null,
        "t2_cad": null,
        "t3_cad": null,
        "green_flags": [],
        "red_flags": []
      }
    ],
    "holds": [
      {
        "ticker": "",
        "days_held": null,
        "current_price_cad": null,
        "stop_intact": null,
        "t1_hit": null,
        "t2_hit": null,
        "action": ""
      }
    ],
    "exits": [
      {
        "ticker": "",
        "exit_reason": "",
        "action": "EXIT full position"
      }
    ],
    "watchlist": [
      {
        "ticker": "",
        "waiting_for": ""
      }
    ]
  },
  "excluded": [
    { "ticker": "", "reason": "" }
  ]
}

Rules:
- Do NOT read agent_and_tips.md. All criteria are in screen_criteria.json.
- Step 2 screener searches come first. Then for each candidate that survives Step 3,
  run one focused follow-up search to confirm: RSI, MACD, 200d EMA position, and
  next earnings date. Search format: "[TICKER] TSX RSI MACD 200 day EMA earnings date [MONTH YEAR]"
- If a primary screener is inaccessible, substitute: "[MONTH YEAR] TSX swing trade candidates
  technical analysis RSI MACD" as a replacement search.
- Cap total searches at: 4 screener + 1 per surviving candidate (max 10 candidates = 14 searches max).
PROMPT

echo "=== done ===" >> "$LOG"
