Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add 10 SOL trading experiment documentation and setup script
nrpo2c654afb781e
diff --git a/data/changelog.json b/data/changelog.jsonindex 142b42bdf..47b08023c 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-03",+ "title": "Autonomous trading experiment — take initials, hold a moon bag, never dump the whole bag",+ "summary": "You can now give one agent a real budget and let it trade newer pump.fun launches under a disciplined, documented risk policy. It only buys projects between $10k and $100k market cap, never buys pump.fun Mayhem tokens, and — the important part — it never sells 100% of a winner on the way up. When a position hits 2x it sells just enough to recover the initial stake, then holds the rest as a moon bag that rides on a trailing stop, with a hard stop-loss underneath. Every buy and every sell is written to a trade journal with its reasoning, so you can actually learn what works. Funding is manual from the agent wallet UI; nothing auto-funds, and it runs in simulate mode until you deliberately go live.",+ "tags": [+ "feature"+ ],+ "link": "/docs/trading-experiment"+ },{"date": "2026-07-03","title": "Copy a trader straight from the Live Trading Theater",diff --git a/docs/trading-experiment.md b/docs/trading-experiment.mdnew file mode 100644index 000000000..59a320154--- /dev/null+++ b/docs/trading-experiment.md@@ -0,0 +1,149 @@+# The 10 SOL trading experiment++Give one autonomous agent a real budget (≈10 SOL), let it trade newer pump.fun+launches under a disciplined risk policy, and **learn what works** from a decision+journal. This doc is the full spec: the rules, the math, how to fund it from the+UI, how to run it safely (simulate first), the kill switches, and how to read the+journal.++Everything here runs on the existing sniper worker (`workers/agent-sniper/`) and+the arm API (`api/sniper/strategy.js`). Nothing new moves money on its own.++## The thesis++Get in early on newer projects, but never make the classic mistake of dumping the+whole bag on the first pump. Instead: recover your initial stake once the trade+works (~2×), then hold the rest as a "moon bag" and let it run, protected by a+trailing stop. Cap the downside with a hard stop-loss. Record *why* every buy and+sell happened so the strategy can actually be improved.++## The rules (and the math)++| Rule | Setting | Why |+|---|---|---|+| **Entry universe** | market cap **$10k–$100k** | newer / newer-established projects, not dust and not already-run |+| **No Mayhem** | pump.fun Mayhem tokens are always skipped | owner rule — higher-fee, buyback-less mode; enforced in the worker (see below) |+| **Quality filters** | socials required, skip serial launchers (>10 launches) | cheap signal filters |+| **Position size** | ~2.5% of budget per trade (0.25 SOL at 10 SOL), 20%/day cap | survive a losing streak |+| **Take initials** | at **2× entry**, sell enough to recover the cost basis | de-risk to "house money" without selling the whole position |+| **Moon bag floor** | always keep **≥15%** of the position | a full exit on the way up is impossible by construction |+| **Let it run** | remainder rides on a **25% trailing stop** | capture the upside a too-early full sell would miss |+| **Hard stop-loss** | **35%** below entry, always | the non-negotiable downside cap; stop-loss wins every conflict |+| **Time stop** | 24h | don't hold a dead position forever |++### Take-initials math (`workers/agent-sniper/exit-logic.js` → `decideLadderedExit`)++When a position first reaches `initials_out_multiple`× entry, sell the fraction+that returns the cost basis:++```+sellFraction = min( entry / current_value , 1 − moonbag_floor )+```++- At **2×**: `entry / (2·entry) = 0.5` → sell half, keep half. You've recovered+ your whole stake and still hold 50% for free.+- At **5×**: `0.2` → sell 20%, keep 80%.+- The `1 − moonbag_floor` cap guarantees the sell is **never** the whole bag+ (default floor 15%, so the sell never exceeds 85%).++After the take-initials leg, the position stays **open** with the moon bag, its+trailing-stop high-water is reset to the remaining value (so the pre-sale peak+doesn't instantly trip the trailing stop), and the ladder is marked recovered so+it fires exactly once. The remainder then exits only on the **trailing stop**,+the **stop-loss**, the optional take-profit ceiling, or the **timeout** — all+full exits of what remains.++Priority order (stop-loss always wins): `stop_loss → signal_flip → trailing_stop+→ take_initials → take_profit(ceiling) → timeout`.++The ladder is **opt-in**: a strategy with no `initials_out_multiple` keeps the+classic single-shot full-exit behavior, so existing strategies are unchanged.++### No-Mayhem enforcement (`workers/agent-sniper/mayhem-gate.js`)++`isMayhemMode` lives on the pump.fun bonding curve, not the new-mint firehose, so+it's read from the curve (one cached read per mint) and checked as **gate 0** in+`executeBuy` — before any throttle, wallet decrypt, or position row — so it covers+**every** trigger path (new_mint, intel, alpha, first_claim, radar, swarm). On by+default (`SNIPER_MAYHEM_FILTER=0` disables; `SNIPER_MAYHEM_STRICT=1` also skips+when the curve can't be read). A Mayhem mint is skipped with reason+`mayhem_excluded`.++## Funding it from the UI++The agent trades from its **own** custodial Solana wallet — funded by you, never+auto-funded from a platform master (`auto_fund_enabled` stays **false**).++1. Open the agent's wallet hub: **`/agent/<agentId>/wallet#deposit`**.+2. Send ~10 SOL from your own wallet (Phantom/Solflare/Backpack) to the shown+ address, or scan the Solana-Pay QR. The tab shows the balance land live.+3. The arm screen (`/arm`) shows the funded balance + runway so you can confirm+ the 10 SOL arrived before enabling.++## Running it++### 1. Arm the strategy++```bash+node scripts/trading-experiment-setup.mjs --agent <agentId> --user <userId> --budget-sol 10+# add --dry-run to preview the exact config without writing+```++This stages the strategy **disabled** by default (fund + review first). It sets+the full policy above and leaves auto-funding off.++### 2. Simulate first — prove it before real money++Run the worker in **simulate** mode (`SNIPER_MODE=simulate`). It scores, applies+the mcap gate, applies no-Mayhem, and computes laddered exits **without+broadcasting**. Watch the journal:++```+GET /api/sniper/journal?network=mainnet&agent_id=<agentId>+```++Confirm: a $10k–$100k non-Mayhem mint passes; a Mayhem mint is skipped; a >$100k+or <$10k mint is skipped; a position at 2× takes initials and keeps a moon bag; a+position at −35% exits on the stop.++### 3. Go live — deliberately++Set `SNIPER_MODE=live`, enable the strategy (`--enable`, or toggle from the UI).+Real SOL now moves from the agent wallet only.++### Kill switches (in escalation order)++1. `kill_switch = true` on the strategy — stop this agent's new buys (open+ positions still exit on their rules).+2. `SNIPER_GLOBAL_KILL=1` — halt all new buys across every agent.+3. Disable the strategy (`enabled = false`).++## Learning from it — the journal++Every decision is recorded in `trading_journal` with its reasoning:++- **entry** — trigger, market cap, score, size, price impact, firewall verdict.+- **take_initials** — the fraction sold, the leg PnL, "moon bag riding".+- **exit** — the reason (trailing/stop/timeout) and the leg PnL.++Read it at `GET /api/sniper/journal`. Because it captures the *why*, not just the+PnL, you can compare what actually worked — which entry conditions led to winners,+whether 2× initials was too early or too late, whether the 25% trail gave back too+much — and tune the next run. That is the whole point of the experiment.++## Files++- Risk policy config: `scripts/trading-experiment-setup.mjs`+- Laddered exit math: `workers/agent-sniper/exit-logic.js` (`decideLadderedExit`)+- Partial-sell execution: `workers/agent-sniper/executor.js` (`executeSell`)+- No-Mayhem gate: `workers/agent-sniper/mayhem-gate.js`+- Journal: `workers/agent-sniper/journal.js`, read via `api/sniper/journal.js`+- Strategy fields: `api/sniper/strategy.js`, migrations+ `20260703150000_sniper_laddered_exit.sql`, `20260703160000_trading_journal.sql`+- Funding UI: `/agent/:id/wallet` deposit tab, `/arm`++## Related++- [STRUCTURE.md](../STRUCTURE.md) — surface map+- Auto-funding is off by default platform-wide — see the sniper auto-fund consent+ gate (`agent_sniper_strategies.auto_fund_enabled`).diff --git a/public/changelog.json b/public/changelog.jsonindex 107eddb91..4b64f9621 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-03T10:37:41.589Z",+ "generated_at": "2026-07-03T10:41:02.675Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex afc42e82b..3dea47d71 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-03T10:37:41.569Z",+ "generated_at": "2026-07-03T10:41:02.659Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/run-migrations.mjs b/scripts/run-migrations.mjsindex 5490d6380..900423927 100644--- a/scripts/run-migrations.mjs+++ b/scripts/run-migrations.mjs@@ -20,14 +20,41 @@ const args = new Set(process.argv.slice(2));const DRY_RUN = args.has('--dry-run');const CHECK = args.has('--check');-// Split SQL text into individual statements, respecting dollar-quoted blocks-// and single-line (--) comments.+// Split SQL text into individual statements, respecting dollar-quoted blocks,+// single- and double-quoted literals (with '' / "" escapes), and single-line+// (--) comments.function splitSql(text) {const stmts = [];let current = '';let inDollarQuote = null;+ let inSingleQuote = false;+ let inDoubleQuote = false;let i = 0;while (i < text.length) {+ if (inSingleQuote) {+ if (text[i] === "'" && text[i + 1] === "'") {+ current += "''";+ i += 2;+ continue;+ }+ if (text[i] === "'") {+ inSingleQuote = false;+ }+ current += text[i++];+ continue;+ }+ if (inDoubleQuote) {+ if (text[i] === '"' && text[i + 1] === '"') {+ current += '""';+ i += 2;+ continue;+ }+ if (text[i] === '"') {+ inDoubleQuote = false;+ }+ current += text[i++];+ continue;+ }if (inDollarQuote === null) {// Skip single-line comments (copy them verbatim up to the newline).if (text[i] === '-' && text[i + 1] === '-') {@@ -37,6 +64,16 @@ function splitSql(text) {i += line.length;continue;}+ if (text[i] === "'") {+ inSingleQuote = true;+ current += text[i++];+ continue;+ }+ if (text[i] === '"') {+ inDoubleQuote = true;+ current += text[i++];+ continue;+ }// Detect dollar-quote opening tag.const dollarMatch = text.slice(i).match(/^(\$[^$]*\$)/);if (dollarMatch) {diff --git a/scripts/trading-experiment-setup.mjs b/scripts/trading-experiment-setup.mjsnew file mode 100644index 000000000..4f7f1cd09--- /dev/null+++ b/scripts/trading-experiment-setup.mjs@@ -0,0 +1,118 @@+#!/usr/bin/env node+// scripts/trading-experiment-setup.mjs+//+// Arm ONE agent with the "10 SOL trading experiment" strategy — the concrete,+// reproducible config that encodes the owner's risk rules:+//+// - Buy only newer projects: market cap $10k–$100k.+// - NEVER buy pump.fun "Mayhem" tokens (enforced in the worker; no flag needed+// here — the gate is on by default).+// - Take initials at 2× (recover the cost basis), keep a 15% moon bag minimum,+// let the rest ride on a 25% trailing stop. NEVER a 100% exit on the way up.+// - Mandatory 35% stop-loss (hard downside cap).+// - Sized for a ~10 SOL budget: 0.25 SOL/trade, 2 SOL/day, ≤4 concurrent.+//+// It NEVER moves money: it does not fund the wallet (auto_fund stays off — the+// owner funds the agent from the UI deposit tab) and it arms the strategy in+// SIMULATE posture by leaving it disabled unless --enable is passed. Prints the+// exact config and the funding + go-live checklist.+//+// Usage:+// node scripts/trading-experiment-setup.mjs --agent <agentId> [--user <userId>]+// [--network mainnet|devnet]+// [--budget-sol 10] [--enable] [--dry-run]+//+// --dry-run print the strategy JSON and exit (no DB write) — the default when+// DATABASE_URL is unset.+// --enable arm it enabled=true. Omit to stage it disabled (recommended:+// fund + review, then enable from the UI).++const args = process.argv.slice(2);+const opt = (name, def) => {+ const i = args.indexOf(`--${name}`);+ return i >= 0 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : def;+};+const flag = (name) => args.includes(`--${name}`);++const SOL = 1_000_000_000n;+const agentId = opt('agent', null);+const userId = opt('user', null);+const network = opt('network', 'mainnet');+const budgetSol = Number(opt('budget-sol', '10'));+const enable = flag('enable');+const dryRun = flag('dry-run') || !process.env.DATABASE_URL;++if (!agentId) {+ console.error('Missing --agent <agentId>. This is the agent whose wallet will trade.');+ process.exit(1);+}++// Sizing derived from the budget: risk ~2.5% of the pot per trade, ~20%/day.+const perTradeSol = Math.max(0.01, Math.round(budgetSol * 0.025 * 1000) / 1000);+const dailyBudgetSol = Math.max(perTradeSol, Math.round(budgetSol * 0.2 * 1000) / 1000);+const toLamports = (sol) => (BigInt(Math.round(sol * 1e9))).toString();++const strategy = {+ agent_id: agentId,+ user_id: userId,+ network,+ enabled: enable,+ kill_switch: false,+ trigger: 'new_mint',+ // Entry universe: newer projects, $10k–$100k market cap.+ min_market_cap_usd: 10_000,+ max_market_cap_usd: 100_000,+ require_socials: true, // skip no-socials launches (a cheap quality filter)+ max_creator_launches: 10, // skip serial launchers+ // Sizing for the ~10 SOL pot.+ per_trade_lamports: toLamports(perTradeSol),+ daily_budget_lamports: toLamports(dailyBudgetSol),+ max_concurrent_positions: 4,+ slippage_bps: 500,+ max_price_impact_pct: 10,+ // The laddered exit: take initials at 2×, keep ≥15% moon bag, trail 25%.+ initials_out_multiple: 2,+ moonbag_min_pct: 15,+ trailing_stop_pct: 25,+ take_profit_pct: null, // no ceiling — let the moon bag run on the trailing stop+ stop_loss_pct: 35, // mandatory hard downside cap+ max_hold_seconds: 86_400, // 24h time-stop+ // Funding stays MANUAL — the owner deposits from the UI; no master auto-fund.+ auto_fund_enabled: false,+};++console.log('\n=== 10 SOL trading experiment — strategy ===\n');+console.log(JSON.stringify(strategy, null, 2));+console.log(`\nBudget ${budgetSol} SOL → ${perTradeSol} SOL/trade, ${dailyBudgetSol} SOL/day, ≤4 concurrent.`);+console.log('Entry: $10k–$100k mcap, socials required, no serial launchers, NO Mayhem tokens.');+console.log('Exit: take initials at 2× (keep ≥15% moon bag), trail 25%, hard stop 35%, 24h timeout.');++if (dryRun) {+ console.log('\n[dry-run] No DB write. Set DATABASE_URL and drop --dry-run to arm.\n');+ printChecklist();+ process.exit(0);+}++const { sql } = await import('../api/_lib/db.js');+const cols = Object.keys(strategy);+const vals = Object.values(strategy);+// Build an INSERT … ON CONFLICT that mirrors the arm API's upsert.+const colList = cols.join(', ');+const placeholders = cols.map((_, i) => `$${i + 1}`).join(', ');+const updates = cols.filter((c) => !['agent_id', 'network'].includes(c)).map((c) => `${c} = excluded.${c}`).join(', ');+const query = `insert into agent_sniper_strategies (${colList}, updated_at)+ values (${placeholders}, now())+ on conflict (agent_id, network) do update set ${updates}, updated_at = now()+ returning id, enabled`;+const [row] = await sql.query(query, vals);+console.log(`\nArmed strategy ${row.id} (enabled=${row.enabled}) for agent ${agentId} on ${network}.`);+printChecklist();++function printChecklist() {+ console.log('\n=== Before it trades real money ===');+ console.log(' 1. Fund the agent wallet from the UI: /agent/' + agentId + '/wallet#deposit (send ~' + budgetSol + ' SOL).');+ console.log(' 2. Run the worker in SIMULATE first (SNIPER_MODE=simulate) and watch /api/sniper/journal.');+ console.log(' 3. Confirm: 10k–100k mints pass, Mayhem mints are skipped (mayhem_excluded), a 2× position takes initials + keeps a moon bag.');+ console.log(' 4. Go live deliberately: SNIPER_MODE=live and enable the strategy. Kill switches: strategy kill_switch, or SNIPER_GLOBAL_KILL=1.');+ console.log(' 5. Auto-funding stays OFF (auto_fund_enabled=false) — top up manually from the UI.\n');+}