# VWAP + Multi-Indicator T-Trading Panel

做T (T-trading) = buying/selling around an existing position to lower cost basis via intraday swings.
Best for high-volatility stocks with 10%+ daily ranges (e.g. quantum stocks, biotech, meme stocks).

## Indicator Stack for T-Trading

| Indicator | What it tells you | T-trading signal |
|-----------|-------------------|------------------|
| **VWAP** | Intraday volume-weighted avg price (the "fair value" today) | Price > VWAP = sell zone; < VWAP = buy zone |
| **RSI(14)** | Overbought/oversold momentum | >70 = overbought (sell); <30 = oversold (buy) |
| **Bollinger(20,2)** | Volatility channel | Touch upper band = sell; touch lower band = buy |
| **ATR(14)** | Average True Range — how much it swings per period | Higher ATR = better for T-trading |
| **Volume ratio** | Current vol vs average | >1.5x = confirming move; <0.5x = weak/noisy |

## VWAP Calculation (from 30-min candles)

```python
def calc_vwap(candles):
    """Volume-Weighted Average Price"""
    cum_pv, cum_vol = 0, 0
    for c in candles:
        typical = (float(c.high) + float(c.low) + float(c.close)) / 3
        vol = float(c.volume)
        cum_pv += typical * vol
        cum_vol += vol
    return cum_pv / cum_vol if cum_vol else 0
```

⚠️ VWAP resets each trading day. Use intraday candles (5min, 30min), NOT daily candles.

## RSI Calculation

```python
def calc_rsi(candles, period=14):
    closes = [float(c.close) for c in candles]
    if len(closes) < period + 1:
        return None
    gains, losses = [], []
    for i in range(1, len(closes)):
        diff = closes[i] - closes[i-1]
        gains.append(max(diff, 0))
        losses.append(max(-diff, 0))
    avg_gain = sum(gains[-period:]) / period
    avg_loss = sum(losses[-period:]) / period
    if avg_loss == 0:
        return 100
    rs = avg_gain / avg_loss
    return 100 - (100 / (1 + rs))
```

## Bollinger Bands

```python
def calc_bollinger(candles, period=20, std_mult=2):
    closes = [float(c.close) for c in candles]
    data = closes[-period:]
    mid = sum(data) / period
    std = (sum((x - mid)**2 for x in data) / period) ** 0.5
    return mid + std_mult * std, mid, mid - std_mult * std  # upper, mid, lower
```

## Composite Scoring System

Combine all indicators into a single score for clear buy/sell signals:

```python
score = 0  # Range: -100 (strong buy) to +100 (strong sell)

# VWAP
if price > vwap:  score += 20    # above VWAP = sell bias
else:             score -= 20    # below VWAP = buy bias

# RSI (30-min timeframe preferred for T-trading)
if rsi_30m > 70:  score += 25    # overbought
elif rsi_30m < 30: score -= 25   # oversold

# Bollinger position
boll_pct = (price - boll_low) / (boll_up - boll_low)
if boll_pct > 0.8: score += 20   # near upper band
elif boll_pct < 0.2: score -= 20 # near lower band

# Volume confirmation
if vol_ratio > 1.5: score += 10  # volume confirms move

# Decision
if score > 30:  action = "SELL (reverse T)"
elif score < -30: action = "BUY (forward T)"
else:            action = "WAIT"
```

## T-Trading Execution Modes

### Manual (Alerts Only)
- Cron monitors price every 10-15 min during market hours
- Notifies user when price hits key levels
- User manually places order

### Semi-Automatic (Recommended for retail)
- Cron monitors price + calculates indicator score
- Auto-submits limit orders when score hits threshold
- Notifies user of every order placed
- Auto-cancels stale orders when price moves away

### Script Architecture
```
~/.hermes/scripts/
├── rgti_t_panel.py          # Manual: run on-demand for indicator dashboard
├── rgti_alert.py            # Alerts only: cron job, silent when no signal
└── rgti_auto_monitor.py     # Semi-auto: cron + auto-place orders + notify
```

## Cron Setup (US Market Hours)
```
# Every 10 min during 9:00-15:59 ET (Mon-Fri)
*/10 9-15 * * 1-5

# Every 15 min (less aggressive)
*/15 9-15 * * 1-5
```

## Key Pitfalls
- **VWAP needs intraday candles**: Daily VWAP is meaningless. Use 5min or 30min candles.
- **RSI on 5min is noisy**: Use 30min RSI for T-trading decisions, 5min only for entry timing.
- **Don't T-trade low-volume stocks**: Need volume >1M daily for reliable fills.
- **GTC + OutsideRTH for auto-orders**: Use `GoodTilCanceled` + `OutsideRTH.AnyTime` so orders work pre-market, regular hours, and after-hours.
- **Position availability**: `available_quantity` (settled, sellable) ≠ `quantity` (total incl unsettled). Check before selling.
- **5-min cooldown between orders**: Prevent rapid-fire order spam; state file tracks last action time.
