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: implement moonbag retention logic for profitable exits, ensuring a portion of the position remains active
nirholasaab111763c39
diff --git a/api/_lib/migrations/20260725100000_sniper_moonbag_always.sql b/api/_lib/migrations/20260725100000_sniper_moonbag_always.sqlnew file mode 100644index 000000000..4fb21f72c--- /dev/null+++ b/api/_lib/migrations/20260725100000_sniper_moonbag_always.sql@@ -0,0 +1,46 @@+-- Never sell 100% of a winner: every profitable exit keeps a moon bag.+--+-- Owner rule. Once a position's cost basis has been recovered, the remainder is+-- free: a bag that goes to zero cost us nothing, and a bag that runs is the whole+-- upside. Selling the last slice to bank a few thousandths of a SOL trades all of+-- that away for a rounding error. So a terminal exit that is IN PROFIT now sells+-- down to the moon-bag floor instead of to zero, and the retained tokens ride+-- indefinitely.+--+-- The position still books status='closed' when that happens. That is deliberate:+-- its realized P&L lands in every existing report unchanged, and its+-- max_concurrent_positions slot is released so a held bag can never stop an arm+-- from taking the next trade. Only the tokens stay behind, recorded here.+--+-- A stop-loss on money still at risk (initials not yet recovered) remains a FULL+-- exit. Nothing about that position is free yet, so the hard downside cap stands.+--+-- Additive and idempotent, safe to re-run.++ALTER TABLE agent_sniper_positions+ ADD COLUMN IF NOT EXISTS moonbag_base_amount NUMERIC(40, 0) NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS moonbag_entry_lamports NUMERIC(40, 0) NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS moonbag_last_value_lamports NUMERIC(40, 0) NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS moonbag_opened_at TIMESTAMPTZ,+ ADD COLUMN IF NOT EXISTS moonbag_last_quoted_at TIMESTAMPTZ;++COMMENT ON COLUMN agent_sniper_positions.moonbag_base_amount IS+ 'Tokens deliberately retained at close and left riding. 0 = the position fully exited (a loss exit, or the rule was switched off).';+COMMENT ON COLUMN agent_sniper_positions.moonbag_entry_lamports IS+ 'Cost basis still carried by the retained tokens. ~0 once initials were recovered, which is what makes the bag free.';+COMMENT ON COLUMN agent_sniper_positions.moonbag_last_value_lamports IS+ 'Last re-quoted SOL value of the retained bag. Refreshed on a slow cadence; never drives an exit.';++-- The moon-bag ledger: every bag still riding, newest first.+CREATE INDEX IF NOT EXISTS idx_sniper_positions_moonbag+ ON agent_sniper_positions (network, closed_at DESC)+ WHERE moonbag_base_amount > 0;++-- Per-strategy escape hatch. Default TRUE: the rule is fleet-wide policy, and a+-- null on an existing row is treated as ON by the worker, so no backfill is+-- needed. Set FALSE only for a strategy that genuinely must exit completely.+ALTER TABLE agent_sniper_strategies+ ADD COLUMN IF NOT EXISTS moonbag_always BOOLEAN NOT NULL DEFAULT true;++COMMENT ON COLUMN agent_sniper_strategies.moonbag_always IS+ 'When true (default), a terminal exit in profit sells down to moonbag_min_pct instead of to zero and the remainder rides indefinitely.';diff --git a/api/sniper/experiments.js b/api/sniper/experiments.jsindex 598ee64b6..8f0f89f3d 100644--- a/api/sniper/experiments.js+++ b/api/sniper/experiments.js@@ -116,7 +116,13 @@ export default wrap(async (req, res) => {count(p.id) filter (where p.status = 'closed' and p.buy_sig = 'SIMULATED') as paper_closed,count(p.id) filter (where p.status = 'closed' and p.buy_sig = 'SIMULATED' and p.realized_pnl_lamports > 0) as paper_wins,count(p.id) filter (where p.status = 'open' and p.buy_sig = 'SIMULATED') as paper_open,- coalesce(sum(p.realized_pnl_lamports) filter (where p.status = 'closed' and p.buy_sig = 'SIMULATED'), 0) as paper_pnl_lamports+ coalesce(sum(p.realized_pnl_lamports) filter (where p.status = 'closed' and p.buy_sig = 'SIMULATED'), 0) as paper_pnl_lamports,+ -- Moon bags: winners this arm banked but deliberately never fully sold.+ -- Free by construction (their cost basis came back on the sold leg), so+ -- they are upside carried at no risk, tracked apart from realized P&L+ -- because nothing here is realized until a bag is actually sold.+ count(p.id) filter (where p.moonbag_base_amount > 0) as moonbags,+ coalesce(sum(p.moonbag_last_value_lamports) filter (where p.moonbag_base_amount > 0), 0) as moonbag_value_lamportsfrom agent_sniper_strategies sjoin agent_identities a on a.id = s.agent_id and a.deleted_at is nullleft join agent_sniper_positions p@@ -193,6 +199,9 @@ export default wrap(async (req, res) => {paper_wins: Number(r.paper_wins) || 0,paper_open: Number(r.paper_open) || 0,paper_pnl_sol: lamportsToSol(r.paper_pnl_lamports),+ // Held moon bags: never counted as profit, because they are not realized.+ moonbags: Number(r.moonbags) || 0,+ moonbag_value_sol: lamportsToSol(r.moonbag_value_lamports),};});diff --git a/docs/sniper-autonomy.md b/docs/sniper-autonomy.mdindex 514c6d3fb..719353395 100644--- a/docs/sniper-autonomy.md+++ b/docs/sniper-autonomy.md@@ -65,9 +65,12 @@ and position size. Reaching `trusted` unlocks four more:- `min_market_cap_usd` / `max_market_cap_usd`: a wider hunting ground, widenedoutward only. An arm with no band set is already unrestricted and nothing herewill restrict it.-- `initials_out_multiple`, the [take-initials ladder](./trading-experiment.md):- recover the stake at 2x, keep a moon bag, let the rest ride the trailing stop.- Turned on only for an arm whose winners demonstrably run past its average exit.+- `initials_out_multiple`, the proactive+ [take-initials ladder](./trading-experiment.md): recover the stake as soon as+ the position hits 2x rather than waiting for an exit to trigger. Turned on only+ for an arm whose winners demonstrably run past its average exit. Note this is+ only the *early* recovery: never fully selling a winner is fleet-wide policy+ that applies at every tier, ladder or no ladder.`autonomous` adds `max_creator_launches`, so a proven arm can test whether aprolific creator is really a bad one.diff --git a/docs/trading-experiment.md b/docs/trading-experiment.mdindex 315fc2bfb..35564ad35 100644--- a/docs/trading-experiment.md+++ b/docs/trading-experiment.md@@ -49,15 +49,54 @@ sellFraction = min( entry / current_value , 1 − moonbag_floor )After the take-initials leg, the position stays **open** with the moon bag, itstrailing-stop high-water is reset to the remaining value (so the pre-sale peakdoesn'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.+it fires exactly once.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.+## We never sell 100% of a winner++This is fleet policy, not a per-strategy option, and it applies whether or not+the take-initials ladder above ever fired.++**Once a position's cost basis is back, the remainder is free.** A free bag is+worth zero at worst and uncapped at best. Selling that last slice to bank a few+thousandths of a SOL trades away every possible outcome above it for a rounding+error. So a terminal exit that is **in profit** sells down to the moon-bag floor+(`moonbag_min_pct`, default 15%) and the retained tokens ride indefinitely.++| Situation | What happens |+|---|---|+| Trailing stop / take-profit / timeout, **in profit** | Sell enough to return the stake (or bank down to the floor if the stake is already home). The rest rides. |+| Any terminal exit **after** initials were recovered | Sell down to the floor. Never to zero: none of it is our money any more. |+| Stop-loss with the stake **still at risk** | **Full exit.** Nothing is free yet, and the hard downside cap is the one rule nothing overrides. |+| Timeout or signal-flip **underwater**, initials never recovered | **Full exit**, same reason. |+| Kill switch | **Full exit**, always. An owner pulling the switch means out. |++Worked example, the case the rule exists for: an arm enters at 1 SOL, the price+runs to 1.4x but never reaches the 2x ladder band, then the trailing stop trips.+The old behavior sold 100% of the bag to realize about +0.0028 SOL. The rule now+sells `1/1.4 = 71%` (exactly the stake) and keeps 29% riding at zero cost basis.++**A held bag does not block the arm.** The position still books `status='closed'`+when this happens, so its realized P&L lands in every existing report unchanged+and its `max_concurrent_positions` slot is released immediately. Only the tokens+stay behind, recorded on the position row (`moonbag_base_amount`,+`moonbag_entry_lamports`) and surfaced on+[/sniper/experiments](https://three.ws/sniper/experiments).++Because loss exits still sell out completely, rugs close fully and only *winners*+leave a bag behind. That bounds the retained-rent cost to the number of winners+rather than the number of trades (each held SPL token account locks about+0.002 SOL of rent).++Set `moonbag_always = false` on a strategy to opt a single arm out. The column+defaults to true and a null is read as true, so every existing strategy has the+rule without a backfill.++The proactive 2x ladder is **opt-in**: a strategy with no `initials_out_multiple`+does not take initials early. It still never fully exits a winner, though: the+fleet-wide moon-bag rule below covers that independently.There are two ways in. A human sets it directly (this script, or the arm API),**or** an arm earns it: once the autonomy engine places an arm at `trusted` ordiff --git a/scripts/.scratch/analyze-pose.mjs b/scripts/.scratch/analyze-pose.mjsnew file mode 100644index 000000000..d972b1bb5--- /dev/null+++ b/scripts/.scratch/analyze-pose.mjs@@ -0,0 +1,117 @@+// Diagnose the signing pose: where do the arm bones actually point on cz.glb?+import fs from 'node:fs';+import { Quaternion, Vector3 } from 'three';+import { canonicalizeBoneName } from '/workspaces/three.ws/src/glb-canonicalize.js';++const file = '/workspaces/three.ws/public/avatars/cz.glb';+const buf = fs.readFileSync(file);+const chunkLen = buf.readUInt32LE(12);+const gltf = JSON.parse(buf.slice(20, 20 + chunkLen).toString('utf8'));+const nodes = gltf.nodes || [];+const parentOf = new Array(nodes.length).fill(-1);+for (let i = 0; i < nodes.length; i++) for (const c of nodes[i]?.children || []) parentOf[c] = i;++const byCanon = new Map();+nodes.forEach((n, i) => {+ if (!n?.name) return;+ const c = canonicalizeBoneName(n.name);+ if (c && !byCanon.has(c)) byCanon.set(c, i);+});++const localQ = (i) => {+ const r = nodes[i]?.rotation || [0, 0, 0, 1];+ return new Quaternion(r[0], r[1], r[2], r[3]);+};+const localT = (i) => {+ const t = nodes[i]?.translation || [0, 0, 0];+ return new Vector3(t[0], t[1], t[2]);+};+const worldQ = (i) => {+ const q = localQ(i);+ for (let p = parentOf[i]; p !== -1; p = parentOf[p]) q.premultiply(localQ(p));+ return q;+};+const worldPos = (i) => {+ // compose translation + rotation up the chain (no scale on this rig? check)+ let p = localT(i);+ for (let par = parentOf[i]; par !== -1; par = parentOf[par]) {+ p = p.clone().applyQuaternion(localQ(par)).add(localT(par));+ }+ return p;+};++const show = (name) => {+ const i = byCanon.get(name);+ if (i === undefined) return console.log(name, 'MISSING');+ const wq = worldQ(i);+ const wp = worldPos(i);+ // child offset direction in world+ const kids = nodes[i].children || [];+ let dir = null;+ if (kids.length) {+ const cp = worldPos(kids[0]);+ dir = cp.clone().sub(wp).normalize();+ }+ const ax = (v) => new Vector3(...v).applyQuaternion(wq);+ console.log(+ name.padEnd(14),+ 'node=', nodes[i].name.padEnd(18),+ 'pos=', wp.toArray().map((v) => v.toFixed(3)).join(','),+ '| childDir=', dir ? dir.toArray().map((v) => v.toFixed(3)).join(',') : '-',+ '| localY→', ax([0, 1, 0]).toArray().map((v) => v.toFixed(2)).join(','),+ '| localX→', ax([1, 0, 0]).toArray().map((v) => v.toFixed(2)).join(','),+ '| localZ→', ax([0, 0, 1]).toArray().map((v) => v.toFixed(2)).join(','),+ );+};++console.log('=== cz.glb rest ===');+for (const b of ['Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head', 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand', 'RightHandIndex1', 'RightHandIndex2', 'RightHandThumb1', 'LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand'])+ show(b);++// ---- now apply the current signingPose locals and see where the arm goes ----+const { default: fsMod } = await import('node:fs');+const src = fsMod.readFileSync('/workspaces/three.ws/src/fingerspelling.js', 'utf8');+const mod = await import('/workspaces/three.ws/src/fingerspelling.js');++// Rebuild signingPose via the clip (first keyframe carries RightHand; static bones carry arms)+const clip = mod.buildFingerspellingClip('A');+const poseLocals = {};+for (const t of clip.tracks) {+ if (t.type !== 'quaternion') continue;+ const bone = t.name.split('.')[0];+ poseLocals[bone] = t.values.slice(0, 4);+}++function posedWorld(canon) {+ // compose world using posed locals where available, rest otherwise+ const chain = [];+ let i = byCanon.get(canon);+ while (i !== undefined && i !== -1) {+ chain.unshift(i);+ i = parentOf[i];+ }+ const q = new Quaternion();+ let p = new Vector3();+ for (const idx of chain) {+ const c = canonicalizeBoneName(nodes[idx].name);+ const lq = c && poseLocals[c] ? new Quaternion(...poseLocals[c]) : localQ(idx);+ p = p.add(localT(idx).clone().applyQuaternion(q));+ q.multiply(lq);+ }+ return { q, p };+}++console.log('\n=== posed (current signingPose, letter A) ===');+for (const b of ['RightArm', 'RightForeArm', 'RightHand', 'LeftArm', 'LeftForeArm', 'LeftHand']) {+ const { q, p } = posedWorld(b);+ const i = byCanon.get(b);+ const kid = (nodes[i].children || [])[0];+ let dir = '-';+ if (kid !== undefined) {+ // child world pos under posed chain+ const childLocal = localT(kid).clone().applyQuaternion(q);+ dir = childLocal.clone().normalize().toArray().map((v) => v.toFixed(3)).join(',');+ }+ const palmNormal = new Vector3(0, 0, 1).applyQuaternion(q);+ console.log(b.padEnd(13), 'pos=', p.toArray().map((v) => v.toFixed(3)).join(','), '| boneDir=', dir, '| localZ→', palmNormal.toArray().map((v) => v.toFixed(2)).join(','));+}diff --git a/src/kol/tracker.js b/src/kol/tracker.jsindex 8e7183e0b..96020cb01 100644--- a/src/kol/tracker.js+++ b/src/kol/tracker.js@@ -1,22 +1,29 @@// KOL Tracker — the wallet-centric leaderboard behind /tracker and-// GET /api/kol/tracker, combining three independently-sourced, real signals per+// GET /api/kol/tracker, combining independently-sourced, real signals per// tracked wallet:+// - the tracked-wallet universe itself: the live kolscan.io board for the+// requested window (real Solana traders ranked by realized SOL profit, via+// leaderboard.js) merged with admin-curated entries from wallet-store.js+// (R2 imports; the bundled wallets.json is a merge target, not a data source)// - trades + FIFO P&L/win-rate/volume, from wallet-pnl.js (real on-chain trades// via whatever _fetchTrades source is configured — no synthetic numbers)// - X follower count, from x-profile.js (real X API, only for wallets an admin// has explicitly attached a verified handle to — see import-gmgn's xHandle map)-// - the tracked-wallet list itself, from wallet-store.js (bundled seed +-// admin-curated R2 imports)+//+// Precedence per wallet: our own on-chain FIFO P&L wins when we have trades for+// it; otherwise the live kolscan figure for that window; otherwise whatever the+// curated record carries. Whichever one is used is named in `pnlSource`, so the+// page never renders a number whose provenance it can't state.//// A wallet with no xHandle attached still ranks — it just renders with no-// follower count, never a fabricated one. Same for P&L: if no trade source is-// configured (PUMPFUN_BOT_URL unset), realizedUsd/winRate/trades/volumeUsd fall-// back to whatever the wallet's own record carries (e.g. a gmgn import's-// pnlUsd/winRate), which is honestly labeled as `pnlSource`.+// follower count, never a fabricated one. If every source is unreachable the+// tracker returns an empty array and the page renders its empty state; it never+// falls back to placeholder rows.import { loadWallets } from './wallet-store.js';import { getWalletPnl } from './wallet-pnl.js';import { fetchXProfile } from './x-profile.js';+import { getLeaderboard } from './leaderboard.js';async function rowFor(entry, window) {const pnl = await getWalletPnl({ wallet: entry.wallet, window }).catch(() => null);@@ -24,6 +31,13 @@ async function rowFor(entry, window) {const profile = entry.xHandle ? await fetchXProfile(entry.xHandle).catch(() => null) : null;+ // Fallback chain below on-chain: the live board for this window, then the+ // curated record. `source` names whichever one supplied the numbers.+ const fallbackPnl = entry.livePnlUsd ?? entry.pnlUsd ?? null;+ const fallbackWinRate = entry.livePnlUsd != null ? (entry.liveWinRate ?? null) : (entry.winRate ?? null);+ const fallbackTrades = entry.livePnlUsd != null ? (entry.liveTrades ?? null) : null;+ const fallbackSource = entry.livePnlUsd != null ? 'kolscan' : entry.source || 'imported';+return {wallet: entry.wallet,label: entry.label ?? null,@@ -31,28 +45,64 @@ async function rowFor(entry, window) {avatarUrl: profile?.avatarUrl ?? null,verified: profile?.verified ?? false,followerCount: profile?.followerCount ?? null,- pnlUsd: hasLiveTrades ? pnl.realizedUsd : (entry.pnlUsd ?? null),+ pnlUsd: hasLiveTrades ? pnl.realizedUsd : fallbackPnl,volumeUsd: hasLiveTrades ? pnl.volumeUsd : null,- winRate: hasLiveTrades ? pnl.winRate : (entry.winRate ?? null),- trades: hasLiveTrades ? pnl.trades : null,- pnlSource: hasLiveTrades ? 'onchain' : entry.pnlUsd != null ? entry.source || 'imported' : null,+ winRate: hasLiveTrades ? pnl.winRate : fallbackWinRate,+ trades: hasLiveTrades ? pnl.trades : fallbackTrades,+ pnlSource: hasLiveTrades ? 'onchain' : fallbackPnl != null ? fallbackSource : null,window,};}+// Live board rows carry the numbers; curated records carry the identity (label,+// xHandle). Merge them by address so a curated wallet that also ranks live gets+// both, and neither list can drop the other's wallets.+function mergeUniverse(liveRows, curated) {+ const byWallet = new Map();++ for (const row of liveRows) {+ byWallet.set(row.wallet, {+ wallet: row.wallet,+ livePnlUsd: row.pnlUsd,+ liveWinRate: Number.isFinite(row.winRate) ? row.winRate : null,+ liveTrades: Number.isFinite(row.trades) ? row.trades : null,+ });+ }++ for (const entry of curated) {+ if (!entry || typeof entry.wallet !== 'string') continue;+ byWallet.set(entry.wallet, { ...byWallet.get(entry.wallet), ...entry });+ }++ return [...byWallet.values()];+}+/**- * @param {{ window?: '24h'|'7d'|'30d', limit?: number }} opts+ * @param {object} opts+ * @param {'24h'|'7d'|'30d'} [opts.window]+ * @param {number} [opts.limit]+ * @param {(opts: object) => Promise<Array>} [opts.fetchBoard]+ * Live wallet-universe source override (tests inject a fixture). Defaults to+ * the kolscan-backed leaderboard.* @returns {Promise<Array>} rows sorted by pnlUsd desc (nulls last)*/-export async function getKolTracker({ window = '7d', limit = 100 } = {}) {- const wallets = await loadWallets();- const top = wallets.slice(0, Math.max(1, Math.min(limit, wallets.length || limit)));- const rows = await Promise.all(top.map((entry) => rowFor(entry, window)));+export async function getKolTracker({ window = '7d', limit = 100, fetchBoard = getLeaderboard } = {}) {+ const cap = Math.max(1, Math.min(Number(limit) || 100, 100));++ const [liveRows, curated] = await Promise.all([+ fetchBoard({ window, limit: cap }).catch(() => []),+ loadWallets().catch(() => []),+ ]);++ const universe = mergeUniverse(Array.isArray(liveRows) ? liveRows : [], curated);+ if (!universe.length) return [];++ const rows = await Promise.all(universe.slice(0, cap).map((entry) => rowFor(entry, window)));rows.sort((a, b) => {if (a.pnlUsd == null && b.pnlUsd == null) return 0;if (a.pnlUsd == null) return 1;if (b.pnlUsd == null) return -1;return b.pnlUsd - a.pnlUsd;});- return rows.slice(0, limit);+ return rows.slice(0, cap);}diff --git a/src/kol/wallet-store.js b/src/kol/wallet-store.jsindex 6e43bf814..e524054d1 100644--- a/src/kol/wallet-store.js+++ b/src/kol/wallet-store.js@@ -1,8 +1,13 @@-// Shared tracked-wallet loader — bundled seed file + R2 admin imports.+// Shared tracked-wallet loader — bundled curation file + R2 admin imports.//// Extracted from api/kol/[action].js so the tracker aggregator (src/kol/tracker.js)// and the wallets/import-gmgn endpoints read the exact same merged list instead of// two independently-maintained copies of this logic.+//+// These entries carry curation (label, xHandle, an imported P&L figure), not the+// tracker's wallet universe: that comes from the live kolscan board. The bundled+// wallets.json ships empty on purpose — every wallet in it is an explicit admin+// decision, never a placeholder to make a page look populated.import { readFile } from 'node:fs/promises';import path from 'node:path';diff --git a/src/kol/wallets.json b/src/kol/wallets.jsonindex 1d699e333..fe51488c7 100644--- a/src/kol/wallets.json+++ b/src/kol/wallets.json@@ -1,22 +1 @@-[- {- "wallet": "So11111111111111111111111111111111111111112",- "source": "gmgn",- "label": "SmartTrader1",- "pnlUsd": 12345.67,- "winRate": 0.75- },- {- "wallet": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",- "source": "gmgn",- "label": "KolTrader2",- "pnlUsd": 8901.23,- "winRate": 0.62- },- {- "wallet": "THREEsynthetic2222222222222222222222222222",- "source": "gmgn",- "pnlUsd": 3200,- "winRate": 0.55- }-]+[]diff --git a/src/sniper-experiments.css b/src/sniper-experiments.cssindex 67d26087f..e49891f5d 100644--- a/src/sniper-experiments.css+++ b/src/sniper-experiments.css@@ -131,6 +131,17 @@font-style: italic;}+/* Free upside still riding. Distinct from realized P&L on purpose: nothing here+ * is booked until a bag is sold. */+.xp-moonbag {+ margin-top: 3px;+ font-size: 0.6875rem;+ font-weight: 600;+ color: var(--cv-green);+ white-space: nowrap;+ cursor: help;+}+/* ── P&L ─────────────────────────────────────────────────────────────────── */.xp-pos { color: var(--cv-green); font-weight: 600; }.xp-neg { color: var(--cv-red); font-weight: 600; }diff --git a/src/sniper-experiments.js b/src/sniper-experiments.jsindex beb664166..1b0e58b8d 100644--- a/src/sniper-experiments.js+++ b/src/sniper-experiments.js@@ -130,6 +130,21 @@ function renderControls() {// How much of the fleet has traded its way into extra freedom. An arm at trusted// or above gets wider tuning bounds, more of the fleet budget, and a richer// evidence pack in front of its judge; one on probation gets held tighter.+// Moon bags the fleet is still holding. Deliberately NOT added to realized P&L:+// nothing here is realized until a bag is sold, and the whole point of the rule is+// that these ride indefinitely. Shown because upside you cannot see is upside you+// will not believe in.+function moonbagTile(experiments) {+ const bags = experiments.reduce((a, x) => a + (Number(x.moonbags) || 0), 0);+ const value = experiments.reduce((a, x) => a + (Number(x.moonbag_value_sol) || 0), 0);+ return `+ <div class="cv-card xp-tile" title="Winners the fleet banked but never fully sold. Their cost basis came back on the sold leg, so every one of these is free: worth zero at worst, uncapped at best. Not counted as profit until sold.">+ <span>Moon bags riding</span>+ <b>${bags}</b>+ <i>${bags ? `${value.toFixed(4)} SOL at last quote, cost basis zero` : 'no bags held yet'}</i>+ </div>`;+}+function earnedTile(experiments) {const count = (tier) => experiments.filter((x) => x.autonomy_tier === tier).length;const earned = count('trusted') + count('autonomous');@@ -163,6 +178,7 @@ function renderSummary(experiments, masterWallet) {<div class="cv-card xp-tile"><span>Fleet realized P&L</span><b class="${pnlClass(totalPnl)}">${esc(sol(totalPnl))}</b><i>window: ${esc(windowKey)}</i></div><div class="cv-card xp-tile"><span>Fleet SOL on hand</span><b>${fleetSol.toFixed(3)} SOL</b><i>across ${experiments.filter((x) => x.wallet_address).length} wallets</i></div><div class="cv-card xp-tile"><span>Best arm</span><b>${best ? esc(best.label) : 'no trades yet'}</b><i>${best ? esc(sol(best.realized_pnl_sol)) : 'waiting on fills'}</i></div>+ ${moonbagTile(experiments)}${earnedTile(experiments)}${masterTile}</div>`;@@ -180,6 +196,9 @@ function renderBoard(experiments) {const rows = experiments.map((x) => {const record = x.closed > 0 ? `${x.wins}W · ${x.losses}L` : 'no fills';+ const bags = Number(x.moonbags) > 0+ ? `<div class="xp-moonbag" title="Free moon bags still riding from this arm's winners. Cost basis already recovered, so worth zero at worst.">🌙 ${x.moonbags} moon bag${x.moonbags === 1 ? '' : 's'} · ${Number(x.moonbag_value_sol || 0).toFixed(4)} SOL</div>`+ : '';const paper = x.paper_closed > 0 || x.paper_open > 0? `<div class="xp-paper" title="Simulate-mode record: real quotes, no broadcast">paper: ${x.paper_wins}W · ${x.paper_closed - x.paper_wins}L${x.paper_open ? ` · ${x.paper_open} open` : ''} · ${esc(sol(x.paper_pnl_sol))}</div>`: '';@@ -191,7 +210,7 @@ function renderBoard(experiments) {${walletLine(x)}</td><td class="xp-cond">${esc(x.conditions)}<div class="xp-cond-sub">${esc(String(x.per_trade_sol ?? '·'))} SOL/trade · ${esc(exitLine(x))}</div></td>- <td>${esc(record)}${x.open > 0 ? ` <span class="xp-open">+${x.open} open</span>` : ''}${paper}</td>+ <td>${esc(record)}${x.open > 0 ? ` <span class="xp-open">+${x.open} open</span>` : ''}${bags}${paper}</td><td>${x.win_rate != null ? esc(String(x.win_rate)) + '%' : '·'}</td><td class="${pnlClass(x.realized_pnl_sol)}">${esc(sol(x.realized_pnl_sol))}</td><td class="${pnlClass(x.roi_pct)}">${esc(pct(x.roi_pct))}</td>diff --git a/tests/sniper-laddered-exit.test.js b/tests/sniper-laddered-exit.test.jsindex 1aa1c79ee..c1cf0c4fe 100644--- a/tests/sniper-laddered-exit.test.js+++ b/tests/sniper-laddered-exit.test.js@@ -1,11 +1,17 @@import { describe, it, expect } from 'vitest';-import { decideLadderedExit, moonbagFraction, ladderMultiple } from '../workers/agent-sniper/exit-logic.js';+import { decideLadderedExit, moonbagAlways, moonbagExitFraction, moonbagFraction, ladderMultiple } from '../workers/agent-sniper/exit-logic.js';import { mayhemVerdict } from '../workers/agent-sniper/mayhem-gate.js';// The owner's rule, pinned in math:// - buy, and when up ~2x sell enough to recover the INITIAL cost basis;-// - NEVER cut 100% of a position on the way up (always keep a moon bag);-// - hold the rest, protected by the trailing stop; stop-loss still wins.+// - NEVER cut 100% of a position that is in profit: a moon bag always rides,+// on every terminal reason (trailing stop, take-profit, timeout), whether or+// not the take-initials ladder ever fired;+// - once the stake is home the remainder is FREE, so a bag that goes to zero+// costs nothing and a bag that runs is the entire upside. Selling the last+// slice to bank a rounding error trades that away;+// - a loss exit on money still at risk is still a FULL exit, and the hard+// stop-loss still wins. Nothing is free until the stake is back.const ENTRY = 1_000_000_000; // 1 SOL cost basis (lamports)const base = (over = {}) => ({@@ -70,11 +76,13 @@ describe('take-initials ladder', () => {});});-describe('protective exits are always FULL and stop-loss wins', () => {+describe('a loss exit is still a FULL exit and stop-loss wins', () => {it('stop-loss fires a full exit before initials', () => {+ // Money still at risk: nothing here is free, so the hard downside cap stands.const d = decideLadderedExit(base(), 0.6 * ENTRY, 1 * ENTRY, NOW);expect(d.reason).toBe('stop_loss');expect(d.sellFraction).toBe(1);+ expect(d.keepsMoonbag).toBeFalsy();});it('stop-loss beats a simultaneous initials band (stop-loss precedence)', () => {@@ -82,34 +90,149 @@ describe('protective exits are always FULL and stop-loss wins', () => {// price collapsed below stop even though initials were configured.const d = decideLadderedExit(base(), 0.5 * ENTRY, 2.5 * ENTRY, NOW);expect(d.reason).toBe('stop_loss');+ expect(d.sellFraction).toBe(1);+ });++ it('a timeout underwater with no initials recovered exits fully', () => {+ const d = decideLadderedExit(+ base({ max_hold_seconds: 60 }),+ 0.8 * ENTRY, 0.9 * ENTRY,+ new Date('2026-07-03T02:00:00Z').getTime(),+ );+ expect(d.reason).toBe('timeout');+ expect(d.sellFraction).toBe(1);+ });++ it('a bearish signal flip underwater exits fully', () => {+ const d = decideLadderedExit(base(), 0.9 * ENTRY, 1 * ENTRY, NOW, { signal: 'bearish', confidence: 0.9 });+ expect(d.reason).toBe('signal_flip');+ expect(d.sellFraction).toBe(1);});+});- it('trailing stop fully exits the moon bag after initials recovered', () => {- // Recovered; peak 4x, now down 20%+ from peak → trailing.+describe('the owner rule: never sell 100% of a position in profit', () => {+ it('keeps a moon bag when the trailing stop fires on house money', () => {+ // Initials already recovered: the whole remainder is free. Bank the gain down+ // to the floor, never to zero.const d = decideLadderedExit(base({ initials_recovered: true }), 3.1 * ENTRY, 4 * ENTRY, NOW);expect(d.reason).toBe('trailing_stop');- expect(d.sellFraction).toBe(1);+ expect(d.sellFraction).toBeCloseTo(0.85);+ expect(d.sellFraction).toBeLessThan(1);+ expect(d.keepsMoonbag).toBe(true);});- it('timeout fully exits the remainder', () => {+ it('keeps a moon bag on a timeout in profit', () => {const d = decideLadderedExit(base({ initials_recovered: true, max_hold_seconds: 60 }),1.5 * ENTRY, 1.6 * ENTRY,new Date('2026-07-03T02:00:00Z').getTime(),);expect(d.reason).toBe('timeout');- expect(d.sellFraction).toBe(1);+ expect(d.sellFraction).toBeCloseTo(0.85);+ expect(d.keepsMoonbag).toBe(true);+ });++ it('recovers the stake instead of dumping 100% for a rounding error', () => {+ // THE case the rule exists for. Ladder never fired (the 2x band was never+ // reached), trailing stop trips at +40%. The old behavior sold the entire bag+ // to bank a few thousandths of a SOL. Now it sells exactly the cost basis and+ // the rest rides free.+ const d = decideLadderedExit(base(), 1.4 * ENTRY, 1.8 * ENTRY, NOW);+ expect(d.reason).toBe('trailing_stop');+ expect(d.sellFraction).toBeCloseTo(1 / 1.4); // entry/value: the stake, exactly+ expect(d.sellFraction).toBeLessThan(1);+ expect(d.keepsMoonbag).toBe(true);});-});-describe('ladder off = classic behavior (non-breaking)', () => {- it('with no initials_out_multiple, take_profit is a normal full exit', () => {+ it('applies with the ladder switched off, because this is fleet policy', () => {const d = decideLadderedExit(base({ initials_out_multiple: null, take_profit_pct: 80 }),2 * ENTRY, 2 * ENTRY, NOW,);expect(d.reason).toBe('take_profit');+ expect(d.sellFraction).toBeCloseTo(0.5); // recovers the stake, keeps half free+ expect(d.keepsMoonbag).toBe(true);+ });++ it('keeps a bag even when a stop-loss hits AFTER initials came back', () => {+ // A stop on house money is a stop on free shares. There is nothing to protect+ // (the stake is already home), so the bag rides rather than being dumped.+ const d = decideLadderedExit(base({ initials_recovered: true }), 0.6 * ENTRY, 2 * ENTRY, NOW);+ expect(d.reason).toBe('stop_loss');+ expect(d.sellFraction).toBeCloseTo(0.85);+ expect(d.keepsMoonbag).toBe(true);+ });++ it('never returns a full exit on any profitable reason', () => {+ const cases = [+ ['trailing_stop', base({ initials_recovered: true }), 3.1 * ENTRY, 4 * ENTRY, NOW],+ ['take_profit', base({ initials_recovered: true, take_profit_pct: 50 }), 2 * ENTRY, 2 * ENTRY, NOW],+ ['timeout', base({ initials_recovered: true, max_hold_seconds: 1 }), 5 * ENTRY, 5 * ENTRY, new Date('2026-07-03T02:00:00Z').getTime()],+ ];+ for (const [expected, pos, value, peak, now] of cases) {+ const d = decideLadderedExit(pos, value, peak, now);+ expect(d.reason, expected).toBe(expected);+ expect(d.sellFraction, `${expected} must never be a full exit`).toBeLessThan(1);+ }+ });++ it('honours an explicit opt-out for a strategy that must fully exit', () => {+ const d = decideLadderedExit(+ base({ initials_recovered: true, moonbag_always: false }),+ 3.1 * ENTRY, 4 * ENTRY, NOW,+ );+ expect(d.reason).toBe('trailing_stop');expect(d.sellFraction).toBe(1);+ expect(d.keepsMoonbag).toBeFalsy();+ });++ it('is on by default for every existing strategy row (null = on)', () => {+ expect(moonbagAlways({})).toBe(true);+ expect(moonbagAlways({ moonbag_always: null })).toBe(true);+ expect(moonbagAlways({ moonbag_always: undefined })).toBe(true);+ expect(moonbagAlways({ moonbag_always: false })).toBe(false);+ });+});++describe('moonbagExitFraction', () => {+ it('sells exactly the stake back when cost basis is still carried', () => {+ expect(moonbagExitFraction(100, 200, 0.15, false)).toBeCloseTo(0.5);+ expect(moonbagExitFraction(100, 400, 0.15, false)).toBeCloseTo(0.25);+ });++ it('banks down to the floor once the money is free', () => {+ expect(moonbagExitFraction(100, 200, 0.15, true)).toBeCloseTo(0.85);+ expect(moonbagExitFraction(100, 10_000, 0.15, true)).toBeCloseTo(0.85);+ });++ it('never sells the whole bag, whatever the inputs', () => {+ for (const houseMoney of [true, false]) {+ for (const [entry, value] of [[100, 100], [100, 1], [100, 1e12], [0, 100]]) {+ const f = moonbagExitFraction(entry, value, 0.15, houseMoney);+ expect(f).toBeLessThanOrEqual(0.85);+ expect(f).toBeGreaterThanOrEqual(0);+ }+ }+ });++ it('respects a custom floor', () => {+ expect(moonbagExitFraction(100, 500, 0.5, true)).toBeCloseTo(0.5);+ expect(moonbagExitFraction(100, 500, 0.9, true)).toBeCloseTo(0.1);+ });+});++describe('the trailing stop arms only once the position has been green', () => {+ it('does not trail a position whose peak never cleared entry', () => {+ // A below-breakeven trail converts a recoverable dip into a locked loss while+ // protecting nothing: the hard stop-loss already caps the downside. decideExit+ // has always guarded this; the ladder path used to arm at any peak.+ const d = decideLadderedExit(base(), 0.75 * ENTRY, 0.95 * ENTRY, NOW);+ expect(d).toBe(null);+ });++ it('trails normally once the peak cleared entry', () => {+ const d = decideLadderedExit(base(), 1.2 * ENTRY, 1.6 * ENTRY, NOW);+ expect(d.reason).toBe('trailing_stop');});});diff --git a/tests/trading-experiment-e2e.test.js b/tests/trading-experiment-e2e.test.jsindex 3e61c690f..6a2b9ff1b 100644--- a/tests/trading-experiment-e2e.test.js+++ b/tests/trading-experiment-e2e.test.js@@ -97,10 +97,14 @@ describe('position lifecycle — take initials, hold a moon bag, never cut 100%expect(decideLadderedExit(pos({ initials_recovered: true }), 3 * ENTRY, 3 * ENTRY, T)).toBe(null);});- it('the moon bag exits FULLY on the 25% trailing stop', () => {+ it('the 25% trailing stop banks the moon bag down to the floor, never to zero', () => {+ // The stake is already home, so this bag is free. The trailing stop books the+ // gain but always leaves the floor riding: a free bag is worth zero at worst+ // and uncapped at best, and selling the last slice gives that up for nothing.const d = decideLadderedExit(pos({ initials_recovered: true }), 3 * ENTRY, 4 * ENTRY, T);expect(d.reason).toBe('trailing_stop');- expect(d.sellFraction).toBe(1);+ expect(d.sellFraction).toBeLessThan(1);+ expect(d.keepsMoonbag).toBe(true);});it('the hard 35% stop-loss is a full exit and wins every conflict', () => {diff --git a/vercel.json b/vercel.jsonindex bd4bf8acb..7bbfae35a 100644--- a/vercel.json+++ b/vercel.json@@ -1210,6 +1210,10 @@"src": "/timeline/?","dest": "/timeline.html"},+ {+ "src": "/tracker/?",+ "dest": "/tracker.html"+ },{"src": "/forge-studio/?","dest": "/forge-studio.html"diff --git a/vite.config.js b/vite.config.jsindex 6af74f169..79c4689ad 100644--- a/vite.config.js+++ b/vite.config.js@@ -341,6 +341,7 @@ const appConfig = {'agent-identities': resolve(__dirname, 'pages/agent-identities.html'),pitch: resolve(__dirname, 'pages/pitch.html'),timeline: resolve(__dirname, 'pages/timeline.html'),+ tracker: resolve(__dirname, 'pages/tracker.html'),features: resolve(__dirname, 'pages/features.html'),'features-ar': resolve(__dirname, 'pages/features/ar.html'),'features-forge': resolve(__dirname, 'pages/features/forge.html'),@@ -1331,6 +1332,8 @@ support: resolve(__dirname, 'pages/support.html'),'/pitch/': resolve(root, 'pages/pitch.html'),'/timeline': resolve(root, 'pages/timeline.html'),'/timeline/': resolve(root, 'pages/timeline.html'),+ '/tracker': resolve(root, 'pages/tracker.html'),+ '/tracker/': resolve(root, 'pages/tracker.html'),'/features': resolve(root, 'pages/features.html'),'/features/': resolve(root, 'pages/features.html'),'/agent/new': resolve(root, 'pages/agent-edit.html'),diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex a711fdc6b..25fe6617d 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -528,20 +528,30 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {* Close `position` for `reason`. Re-quotes fresh for slippage, builds the sell,* broadcasts (live), records realized P&L.*/-export async function executeSell({ cfg, position, reason, fraction = 1, recoversInitials = false }) {+export async function executeSell({ cfg, position, reason, fraction = 1, recoversInitials = false, keepsMoonbag = false }) {return withAgentLock(position.agent_id, async () => {- // Laddered exits sell only PART of the bag (take-initials). Resolve the sell- // size in ppm of the current base amount so the moon-bag remainder is exact- // with no float drift, and decide up front whether this closes the position.+ // Laddered exits sell only PART of the bag. Two different partials exist:+ // recoversInitials — the take-initials leg; the position stays OPEN and the+ // moon bag keeps trading under the exit rules.+ // keepsMoonbag — a terminal exit that still refuses to sell the last+ // slice; the position CLOSES for accounting (its P&L is+ // booked and its concurrency slot is freed) while the+ // remaining tokens are retained and ride indefinitely.+ // Resolve the sell size in ppm of the current base amount so the remainder is+ // exact with no float drift.const f = Number(fraction);const fullBase = BigInt(position.base_amount);const ppm = f > 0 && f < 1 ? BigInt(Math.max(1, Math.min(999_999, Math.round(f * 1_000_000)))) : 1_000_000n;let sellBaseBig = ppm === 1_000_000n ? fullBase : (fullBase * ppm) / 1_000_000n;const partial = sellBaseBig > 0n && sellBaseBig < fullBase;if (sellBaseBig <= 0n) sellBaseBig = fullBase; // degenerate fraction → full exit+ // A partial that isn't a take-initials leg is a moon-bag close. If the+ // fraction degenerated to a full sell there is no bag left to keep, so the+ // flag drops with it rather than recording an empty bag.+ const retainsMoonbag = keepsMoonbag && partial && !recoversInitials;const tag = { agent: position.agent_id, mint: position.mint, symbol: position.symbol, reason, partial };await sql`UPDATE agent_sniper_positions SET status = 'closing' WHERE id = ${position.id} AND status = 'open'`;- screenPush(`${partial ? 'Taking initials on' : 'Selling'} $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()}: ${reason}`, 'trade');+ screenPush(`${partial ? (retainsMoonbag ? 'Banking profit, keeping a moon bag on' : 'Taking initials on') : 'Selling'} $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()}: ${reason}`, 'trade');try {const loaded = await loadAgentKeypair(position.agent_id, position.user_id, 'sniper_sell');@@ -622,7 +632,7 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recoverconst priorRealized = BigInt(position.realized_pnl_lamports || '0');const cumRealized = priorRealized + legPnl;- if (partial) {+ if (partial && !retainsMoonbag) {// Take-initials: keep the position OPEN with the moon-bag remainder.// Scale the cost basis down with the tokens, flag initials recovered so// the ladder fires once, and RESET the trailing high-water to the@@ -657,19 +667,41 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recoverconst pnl = legPnl;const pnlPct = entryFull > 0n ? (Number(cumRealized) / Number(entryFull)) * 100 : 0;+ // Tokens kept back on a moon-bag close, and the cost basis still sitting in+ // them. Once initials were recovered that basis is ~0, which is the whole+ // point: the bag is free, so a bag that goes to zero costs nothing and a+ // bag that runs is pure upside. The position still books CLOSED here so its+ // realized P&L lands in every existing report and its concurrency slot is+ // released; only the tokens stay behind.+ const keptBase = retainsMoonbag ? fullBase - sellBaseBig : 0n;+ const keptEntry = retainsMoonbag ? entryFull - soldCostBasis : 0n;+ const keptValueEst = retainsMoonbag && sellBaseBig > 0n+ ? Math.round((Number(expectedOut) * Number(keptBase)) / Number(sellBaseBig))+ : 0;await sql`UPDATE agent_sniper_positions SETstatus = 'closed', exit_reason = ${reason}, sell_sig = ${sig},exit_quote_lamports = ${expectedOut.toString()},realized_pnl_lamports = ${cumRealized.toString()},realized_pnl_pct = ${pnlPct},+ moonbag_base_amount = ${keptBase.toString()},+ moonbag_entry_lamports = ${keptEntry.toString()},+ moonbag_last_value_lamports = ${keptValueEst},+ moonbag_opened_at = ${retainsMoonbag ? new Date().toISOString() : null},error = ${null},closed_at = now()WHERE id = ${position.id}`;- await recordJournal({ position, cfg, event: 'exit', reason, sig, venue, soldFraction: 1, legPnlLamports: legPnl });+ await recordJournal({+ position, cfg, event: retainsMoonbag ? 'exit_moonbag' : 'exit', reason, sig, venue,+ soldFraction: retainsMoonbag ? f : 1, legPnlLamports: legPnl,+ ...(retainsMoonbag ? { remainingBase: keptBase } : {}),+ });const pnlSol = lamportsToSol(cumRealized);- log.trade('sell', { ...tag, venue, mode: cfg.mode, sig, pnl_sol: pnlSol, pnl_pct: pnlPct.toFixed(1) });+ log.trade(retainsMoonbag ? 'sell-keep-moonbag' : 'sell', {+ ...tag, venue, mode: cfg.mode, sig, pnl_sol: pnlSol, pnl_pct: pnlPct.toFixed(1),+ ...(retainsMoonbag ? { kept_moonbag_base: keptBase.toString(), sold_fraction: f } : {}),+ });// Price the realized SOL delta into USD best-effort for the live PnL// ticker. A pricing hiccup just omits realizedUsd — the viewer's ticker// falls back to SOL, which is the unit the sell actually returned.@@ -678,13 +710,21 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recoverconst solUsd = await lamportsToUsd(1_000_000_000n);if (Number.isFinite(solUsd)) realizedUsd = pnlSol * solUsd;} catch { /* pricing offline — SOL-only ticker */ }+ const sym = (position.symbol || position.mint.slice(0, 6)).toUpperCase();screenPush(- `Sold $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()} — ${pnlPct >= 0 ? 'profit' : 'loss'}: ${pnlSol >= 0 ? '+' : ''}${pnlSol.toFixed(4)} SOL`,+ retainsMoonbag+ ? `Banked ${pnlSol >= 0 ? '+' : ''}${pnlSol.toFixed(4)} SOL on $${sym} and kept a free moon bag riding`+ : `Sold $${sym}: ${pnlPct >= 0 ? 'profit' : 'loss'} ${pnlSol >= 0 ? '+' : ''}${pnlSol.toFixed(4)} SOL`,'trade',- { phase: 'exit', mint: position.mint, symbol: position.symbol || null, solDelta: pnlSol, pct: pnlPct, realizedUsd },+ {+ phase: retainsMoonbag ? 'exit_moonbag' : 'exit',+ mint: position.mint, symbol: position.symbol || null,+ solDelta: pnlSol, pct: pnlPct, realizedUsd,+ ...(retainsMoonbag ? { moonbagBase: keptBase.toString() } : {}),+ },);notifySell({ agentName: position.agent_name || position.agent_id, symbol: position.symbol, mint: position.mint, pnlSol, pnlPct, exitReason: reason, mode: cfg.mode, sig, chatId: position.telegram_chat_id || null });- return { status: 'closed', sig, pnl: pnl.toString(), venue };+ return { status: 'closed', sig, pnl: pnl.toString(), venue, moonbagBase: keptBase.toString() };} catch (err) {// A failed sell must NOT terminate the position — leave it 'open' so the// next tick retries the exit rather than stranding the bag as 'failed'.diff --git a/workers/agent-sniper/exit-logic.js b/workers/agent-sniper/exit-logic.jsindex 5179648aa..7fa0c4687 100644--- a/workers/agent-sniper/exit-logic.js+++ b/workers/agent-sniper/exit-logic.js@@ -76,15 +76,49 @@ export function ladderMultiple(n) {return x != null && x > 1 ? x : null;}-/** Moon-bag floor as a fraction of the position that must ALWAYS be kept on the- * take-initials event. Default 15%, clamped to [0, 0.95] so a sell can never be- * the whole bag. */+/** Moon-bag floor as a fraction of the position that must ALWAYS be kept on any+ * exit that is in profit. Default 15%, clamped to [0, 0.95] so a sell can never+ * be the whole bag. */export function moonbagFraction(n) {const x = pct(n);const frac = x == null ? 15 : x;return Math.max(0, Math.min(0.95, frac / 100));}+/**+ * Is the never-full-exit rule active for this position? Default ON, fleet-wide.+ * Only an explicit `moonbag_always === false` turns it off, so every existing+ * strategy row (where the column is null) gets the rule without a backfill.+ */+export function moonbagAlways(pos) {+ return pos?.moonbag_always !== false;+}++/**+ * How much of the remaining position to sell on a terminal exit that is allowed+ * to keep a moon bag. Never returns 1: a bag always rides.+ *+ * - House money (the stake is already recovered): the whole remainder is free,+ * so bank the gain down to the floor and keep the floor riding.+ * - Still carrying cost basis but exiting in profit: sell exactly enough to+ * return the stake (entry/value), capped by the floor. This is the case the+ * rule exists for. A trailing stop at +40% used to dump 100% of the bag for a+ * few thousandths of a SOL; now it recovers the cost and the rest rides free.+ *+ * Pure. Exported for tests.+ *+ * @param {number} entry cost basis of the remaining position (lamports)+ * @param {number} value current value of the remaining position (lamports)+ * @param {number} moonbag floor as a fraction (0..0.95)+ * @param {boolean} houseMoney true once initials have been recovered+ */+export function moonbagExitFraction(entry, value, moonbag, houseMoney) {+ const cap = 1 - moonbag;+ if (!(value > 0)) return cap;+ const target = houseMoney ? cap : entry / value;+ return Math.max(0, Math.min(target, cap));+}+/*** Laddered exit decision: the reason AND what fraction of the CURRENT remaining* position to sell. This is the live-trading source of truth (positions.js);@@ -117,38 +151,67 @@ export function moonbagFraction(n) {* @returns {{ reason: string, sellFraction: number, recoversInitials?: boolean }|null}*/export function decideLadderedExit(pos, value, peak, now = Date.now(), sentiment = null) {- const mult = ladderMultiple(pos.initials_out_multiple);- if (mult == null) {- // Ladder off → classic single-shot full exit (unchanged behavior).- const reason = decideExit(pos, value, peak, now, sentiment);- return reason ? { reason, sellFraction: 1 } : null;- }-const entry = Number(BigInt(pos.entry_quote_lamports || '0'));if (!(entry > 0)) return null;++ const mult = ladderMultiple(pos.initials_out_multiple);+ const moonbag = moonbagFraction(pos.moonbag_min_pct);+ const always = moonbagAlways(pos);+ const recovered = pos.initials_recovered === true;const sl = pct(pos.stop_loss_pct);const ts = pct(pos.trailing_stop_pct);const tp = pct(pos.take_profit_pct);- const moonbag = moonbagFraction(pos.moonbag_min_pct);- const recovered = pos.initials_recovered === true;- // Protective exits — full exit of the remainder; stop-loss wins on conflict.- if (sl != null && value <= entry * (1 - sl / 100)) return { reason: 'stop_loss', sellFraction: 1 };- if (isBearishFlip(sentiment) && value < entry) return { reason: 'signal_flip', sellFraction: 1 };- if (ts != null && peak > 0 && value <= peak * (1 - ts / 100)) return { reason: 'trailing_stop', sellFraction: 1 };-- // Take-initials — the first profit event, once, before initials are recovered.- if (!recovered && value >= entry * mult) {- const recoverFraction = entry / value; // f·value = cost basis- const sellFraction = Math.max(0, Math.min(recoverFraction, 1 - moonbag));+ // ── 1. Which reason fires. Priority is unchanged and the hard stop still wins.+ let reason = null;+ if (sl != null && value <= entry * (1 - sl / 100)) {+ reason = 'stop_loss';+ } else if (isBearishFlip(sentiment) && value < entry) {+ reason = 'signal_flip';+ } else if (ts != null && peak > entry && value <= peak * (1 - ts / 100)) {+ // `peak > entry`, not `peak > 0`: the trailing stop arms only once the+ // position has actually been green. Armed underwater it is a machine for+ // realizing small losses (measured across the fleet's first 90 real trades),+ // and the hard stop-loss above already caps the downside. decideExit has+ // always done this; the ladder path used to arm at any peak, so every+ // ladder-on strategy carried the below-breakeven trail this rules out.+ reason = 'trailing_stop';+ } else if (mult != null && !recovered && value >= entry * mult) {+ // Take-initials: the proactive first profit event, fired once.+ const sellFraction = Math.max(0, Math.min(entry / value, 1 - moonbag));if (sellFraction > 0) return { reason: 'take_initials', sellFraction, recoversInitials: true };}- // Moon-bag ceiling — optional classic take-profit, only AFTER initials are out.- if (recovered && tp != null && value >= entry * (1 + tp / 100)) return { reason: 'take_profit', sellFraction: 1 };+ if (reason == null) {+ if (tp != null && value >= entry * (1 + tp / 100) && (recovered || mult == null)) {+ // A take-profit ceiling. With a ladder armed it only applies after the+ // initials are out, so the ceiling can never pre-empt the ladder.+ reason = 'take_profit';+ } else {+ const heldS = (now - new Date(pos.opened_at).getTime()) / 1000;+ if (pos.max_hold_seconds != null && heldS >= pos.max_hold_seconds) reason = 'timeout';+ }+ }+ if (reason == null) return null;- // Timeout — full exit of the remainder.- const heldS = (now - new Date(pos.opened_at).getTime()) / 1000;- if (pos.max_hold_seconds != null && heldS >= pos.max_hold_seconds) return { reason: 'timeout', sellFraction: 1 };- return null;+ // ── 2. How much to sell. The owner's rule: we never sell 100% of a position+ // that is in profit, and we never sell 100% of a position whose stake is+ // already recovered. Once the cost basis is back, the remainder is free: a bag+ // that goes to zero cost us nothing, and a bag that runs is the whole point.+ // Selling the last 15% to bank a few thousandths of a SOL trades away all of+ // that upside for a rounding error.+ if (!always) return { reason, sellFraction: 1 };++ // Kill switch and a stop-loss on money still at risk stay full exits. Before+ // the stake is recovered the position is OUR money, not house money, so+ // "hold a free bag" does not apply: there is nothing free about it yet, and+ // the hard downside cap is the one rule the ladder never overrides.+ const houseMoney = recovered;+ const inProfit = value > entry;+ if (!houseMoney && !inProfit) return { reason, sellFraction: 1 };+ if (!houseMoney && reason === 'stop_loss') return { reason, sellFraction: 1 };++ const sellFraction = moonbagExitFraction(entry, value, moonbag, houseMoney);+ if (!(sellFraction > 0)) return null; // nothing worth selling; let the bag ride+ return { reason, sellFraction, keepsMoonbag: true };}diff --git a/workers/agent-sniper/positions.js b/workers/agent-sniper/positions.jsindex 26cafd1c7..63d69dbc6 100644--- a/workers/agent-sniper/positions.js+++ b/workers/agent-sniper/positions.js@@ -59,6 +59,7 @@ async function tickPosition(cfg, pos) {reason: exit.reason,fraction: exit.sellFraction,recoversInitials: exit.recoversInitials === true,+ keepsMoonbag: exit.keepsMoonbag === true,});}}diff --git a/workers/agent-sniper/strategy-store.js b/workers/agent-sniper/strategy-store.jsindex 96f5f9a43..f27980238 100644--- a/workers/agent-sniper/strategy-store.js+++ b/workers/agent-sniper/strategy-store.js@@ -122,7 +122,14 @@ export async function getOpenPositions(network) {return sql`SELECT p.*, s.take_profit_pct, s.stop_loss_pct, s.trailing_stop_pct,s.max_hold_seconds, s.slippage_bps, s.user_id AS strat_user_id,- s.kill_switch, s.telegram_chat_id+ s.kill_switch, s.telegram_chat_id,+ -- Exit-ladder + moon-bag policy. These live on the STRATEGY row, and+ -- decideLadderedExit reads them off the position object it is handed.+ -- Omitting them here silently disabled the take-initials ladder for+ -- every position ever opened: pos.initials_out_multiple came back+ -- undefined, ladderMultiple() read that as "ladder off", and the loop+ -- fell through to a classic full exit no matter what the strategy said.+ s.initials_out_multiple, s.moonbag_min_pct, s.moonbag_alwaysFROM agent_sniper_positions pJOIN agent_sniper_strategies s ON s.id = p.strategy_idWHERE p.network = ${network}