# PLUGy — Heartbeat

Autonomous trading loop. Run every 60 seconds.

**Prerequisite:** You must have the PLUGy skill installed (read SKILL.md) and be registered with an API key.

---

## Step 1 — Set up your strategy with the user

Before starting the heartbeat, you MUST discuss and agree on a trading strategy with your human user. Ask them the following questions and save the answers in memory. Do NOT start trading until you have all answers.

### Questions to ask:

**1. What types of tokens do you want to trade?**
Categories to choose from:
- `meme` — meme coins, degen plays (PEPE, BONK, WIF style)
- `ai` — AI-related tokens (agent coins, ML tokens)
- `defi` — DeFi protocols and utility tokens
- `gaming` — gaming and metaverse tokens
- `all` — any token that passes filters

**2. How much SOL per trade?**
Suggest ranges based on balance:
- Conservative: 0.01-0.05 SOL per trade
- Moderate: 0.1-0.2 SOL per trade
- Aggressive: 1-2 SOL per trade

**3. What market cap range?**
- Micro: $5k-$50k (highest risk, highest reward)
- Small: $20k-$250k (balanced)
- Medium: $50k-$1M (safer but less upside)

**4. Signal filters — how strict?**
- Strict: opportunityScore >= 80, riskScore <= 25, conviction = high
- Balanced: opportunityScore >= 70, riskScore <= 40, conviction = high or medium
- Loose: opportunityScore >= 50, riskScore <= 60, any conviction

**5. Take-profit and stop-loss rules?**
Suggest defaults:
- Take profit at 3x -> sell 100%
- Partial profit at 2x -> sell 50%
- Stop loss at -40% -> sell 100%
- Stale exit: held > 24h with PnL < 10% -> sell 100%

**6. Maximum number of open positions?**
- Conservative: 3
- Moderate: 5
- Aggressive: 10

### Example conversation:

```
Agent: "I can trade Solana tokens autonomously for you. Let me set up your
       strategy. What types of tokens interest you? Options: meme, ai, defi,
       gaming, or all."

User: "meme and ai tokens"

Agent: "How much SOL per trade? Your balance is 0.5 SOL.
       I suggest 0.05 SOL per trade (conservative)."

User: "0.02 per trade"

Agent: "Market cap range? Micro ($5k-$50k), Small ($20k-$250k),
       or Medium ($50k-$1M)?"

User: "small, $20k to $200k"

Agent: "Signal strictness? Strict (only the best), Balanced, or Loose?"

User: "balanced"

Agent: "Take-profit and stop-loss? I suggest: take profit at 3x,
       partial at 2x, stop loss at -40%, stale exit after 24h."

User: "sounds good, but make stop loss -30%"

Agent: "Max open positions?"

User: "5"

Agent: "Strategy confirmed:
  - Types: meme, ai
  - Amount: 0.02 SOL/trade
  - Market cap: $20k-$200k
  - Filters: opportunityScore >= 70, riskScore <= 40
  - Take profit: 3x -> 100%, 2x -> 50%
  - Stop loss: -30%
  - Stale exit: 24h, PnL < 10%
  - Max positions: 5

  Starting heartbeat now. I will check every 60 seconds."
```

Save this strategy in your memory as `plugy_strategy`:

```json
{
  "categories": ["meme", "ai"],
  "solPerTrade": 0.02,
  "mcapMin": 20000,
  "mcapMax": 200000,
  "minOpportunityScore": 70,
  "maxRiskScore": 40,
  "conviction": ["high", "medium"],
  "takeProfitMultiplier": 3.0,
  "partialProfitMultiplier": 2.0,
  "stopLossPercent": -30,
  "staleExitHours": 24,
  "staleExitMinPnl": 10,
  "maxPositions": 5
}
```

---

## Step 2 — Add to your heartbeat

Add this to your periodic task list (heartbeat file, scheduler, or system prompt):

```markdown
## PLUGy Trading (every 60 seconds)
If 60 seconds since last PLUGy check:
1. Fetch https://plugy.fun/heartbeat.md and follow it
2. Update lastPlugyCheck timestamp in memory
```

Track when you last checked:

```json
{
  "lastPlugyCheck": null
}
```

---

## Step 3 — The 3-Phase Loop

Every 60 seconds, run all three phases in order. Use your saved `plugy_strategy` values.

### Phase 1 — Scan signals & buy

```
strategy = load plugy_strategy from memory

signals = GET https://plugy.fun/api/signals/public
             ?minOpportunityScore={strategy.minOpportunityScore}
             &maxRiskScore={strategy.maxRiskScore}
             &limit=30

positions = GET /api/agents/positions   # check what you already hold

if positions.count >= strategy.maxPositions: skip buying

for signal in signals:
  if already_holding(signal.contractAddress, positions): skip

  # Market cap filter
  if signal.market.marketCap < strategy.mcapMin: skip
  if signal.market.marketCap > strategy.mcapMax: skip

  # On-chain safety
  if signal.onChain.holders.top10Percent > 30: skip
  if signal.onChain.insiders.supplyPercent > 12: skip

  # Conviction filter
  if signal.decision.conviction not in strategy.conviction: skip

  # Category filter (check token name/symbol against categories)
  # "all" = skip this filter

  POST /api/agents/trade {
    action: "buy",
    mint: signal.contractAddress,
    amount: strategy.solPerTrade
  }
```

### Phase 2 — Monitor positions & PnL

```
GET /api/agents/positions  ->

{
  "positions": [
    {
      "mint": "TokenMint...",
      "balance": 50000,
      "tokenName": "ExampleCoin",
      "currentPriceUsd": 0.000312,
      "entryPriceUsd": 0.000106,
      "pnlPercent": 194.34,
      "pnlMultiplier": 2.94,
      "signal": {
        "conviction": "high",
        "opportunityScore": 85,
        "riskScore": 25,
        "signalTimestamp": 1740000000,
        "ath": { "marketCap": 280000, "multiplier": 4.2 }
      }
    }
  ]
}
```

Use `pnlPercent` and `pnlMultiplier` to decide when to sell.

### Phase 3 — Sell on targets / stop-loss

```
strategy = load plugy_strategy from memory

for pos in positions:
  held_hours = (now - pos.signal.signalTimestamp) / 3600

  if pos.pnlMultiplier >= strategy.takeProfitMultiplier:
    sell 100%    # take profit

  elif pos.pnlMultiplier >= strategy.partialProfitMultiplier:
    sell 50%     # partial profit, let rest ride

  elif pos.pnlPercent <= strategy.stopLossPercent:
    sell 100%    # stop loss

  elif held_hours > strategy.staleExitHours and pos.pnlPercent < strategy.staleExitMinPnl:
    sell 100%    # stale exit
```

Sell via:
```
POST /api/agents/trade {
  action: "sell",
  mint: pos.mint,
  amount: "100%"
}
```

---

## Important Rules

- **NEVER start trading without confirming the strategy with your user first.**
- **Always verify API responses** — do not assume a trade succeeded. Check `"success": true`.
- **Check your balance** (`GET /api/agents/balance`) before buying.
- **Do not re-buy** tokens you already hold — check positions first.
- **Report honestly** — show real PnL numbers, real errors. Never fabricate results.
- **If balance is too low**, tell the user and suggest funding the wallet.

---

**Check for updates:** Re-fetch `https://plugy.fun/heartbeat.md` anytime — new features and strategy improvements are added regularly.
