Skip to content

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.

fix(agent-sniper fleet): laddered exit — never cut 100% up, take initials at 2x, hold a moon bag

nrpo05da4c87951e
diff --git a/packages/agent-sniper/src/executor.js b/packages/agent-sniper/src/executor.js
index 45fe59c37..513e1add0 100644
--- a/packages/agent-sniper/src/executor.js
+++ b/packages/agent-sniper/src/executor.js
@@ -201,13 +201,21 @@ export async function executeBuy({ cfg, strat, candidate, throttle, ports }) {
* @param {string} p.reason
* @param {Ports} p.ports
*/
-export async function executeSell({ cfg, position, reason, ports }) {
+export async function executeSell({ cfg, position, reason, ports, fraction = 1, recoversInitials = false }) {
const { store, wallet, solana, executor, hooks, log } = ports;
return withAgentLock(position.agent_id, async () => {
- const tag = { agent: position.agent_id, mint: position.mint, symbol: position.symbol, reason };
+ // 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,
+ // and decide up front whether this closes the position.
+ const fullBase = BigInt(position.base_amount);
+ const ppm = fraction > 0 && fraction < 1 ? BigInt(Math.max(1, Math.min(999_999, Math.round(fraction * 1_000_000)))) : 1_000_000n;
+ let sellBase = ppm === 1_000_000n ? fullBase : (fullBase * ppm) / 1_000_000n;
+ const partial = sellBase > 0n && sellBase < fullBase;
+ if (sellBase <= 0n) sellBase = fullBase; // degenerate fraction → full exit
+ const tag = { agent: position.agent_id, mint: position.mint, symbol: position.symbol, reason, partial };
const screen = (text, kind, extra) => safe(() => hooks.onScreen?.({ text, kind, ...extra }));
await store.updatePosition(position.id, { status: 'closing' });
- screen(`Selling $${symOf(position)}: ${reason}`, 'trade');
+ screen(`${partial ? 'Taking initials on' : 'Selling'} $${symOf(position)}: ${reason}`, 'trade');
try {
const loaded = await wallet.loadKeypair(position.agent_id, { userId: position.user_id, reason: 'sniper_sell' });
@@ -217,7 +225,7 @@ export async function executeSell({ cfg, position, reason, ports }) {
}
const { keypair } = loaded;
const mintPk = new PublicKey(position.mint);
- const baseAmount = BigInt(position.base_amount);
+ const baseAmount = sellBase;
const slippagePct = (position.slippage_bps ?? 500) / 100;
const quote = await solana.quoteForSell({ mint: mintPk, baseAmount, slippagePct });
@@ -234,16 +242,48 @@ export async function executeSell({ cfg, position, reason, ports }) {
sig = result.signature;
}
- const entry = BigInt(position.entry_quote_lamports || '0');
- const pnl = expectedOut - entry;
- const pnlPct = entry > 0n ? (Number(pnl) / Number(entry)) * 100 : 0;
+ const entryFull = BigInt(position.entry_quote_lamports || '0');
+ // Cost basis of the tokens sold on THIS leg (scaled by the sold ppm).
+ const soldCostBasis = partial ? (entryFull * ppm) / 1_000_000n : entryFull;
+ const legPnl = expectedOut - soldCostBasis;
+ const legPnlPct = soldCostBasis > 0n ? (Number(legPnl) / Number(soldCostBasis)) * 100 : 0;
+ const cumRealized = BigInt(position.realized_pnl_lamports || '0') + legPnl;
+
+ if (partial) {
+ // 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
+ // remaining bag's value (the pre-sale peak would instantly trip trailing).
+ const remainingBase = fullBase - sellBase;
+ const remainingEntry = entryFull - soldCostBasis;
+ const remainingValueEst = Math.round((Number(expectedOut) * Number(remainingBase)) / Number(sellBase));
+ await store.updatePosition(position.id, {
+ status: 'open',
+ base_amount: remainingBase.toString(),
+ entry_quote_lamports: remainingEntry.toString(),
+ initials_recovered: recoversInitials ? true : position.initials_recovered === true,
+ peak_value_lamports: remainingValueEst,
+ last_value_lamports: remainingValueEst,
+ realized_pnl_lamports: cumRealized.toString(),
+ error: null,
+ });
+ const legSol = lamportsToSol(legPnl);
+ log.trade('take-initials', { ...tag, mode: cfg.mode, sig, sold_fraction: fraction, leg_pnl_sol: legSol });
+ screen(`Took initials on $${symOf(position)} — +${legSol.toFixed(4)} SOL back, moon bag riding`, 'trade',
+ { phase: 'take_initials', mint: position.mint, symbol: position.symbol || null, solDelta: legSol, soldFraction: fraction });
+ safe(() => hooks.onSell?.({ position, pnlSol: legSol, pnlPct: legPnlPct, exitReason: reason, mode: cfg.mode, sig, network: cfg.network, partial: true }));
+ return { status: 'partial', sig, sold_fraction: fraction, leg_pnl: legPnl.toString() };
+ }
+
+ const pnl = legPnl;
+ const pnlPct = entryFull > 0n ? (Number(cumRealized) / Number(entryFull)) * 100 : 0;
await store.updatePosition(position.id, {
status: 'closed', exit_reason: reason, sell_sig: sig,
exit_quote_lamports: expectedOut.toString(),
- realized_pnl_lamports: pnl.toString(), realized_pnl_pct: pnlPct,
+ realized_pnl_lamports: cumRealized.toString(), realized_pnl_pct: pnlPct,
error: null, closed_at_ms: Date.now(),
});
- const pnlSol = lamportsToSol(pnl);
+ const pnlSol = lamportsToSol(cumRealized);
log.trade('sell', { ...tag, mode: cfg.mode, sig, pnl_sol: pnlSol, pnl_pct: pnlPct.toFixed(1) });
screen(`Sold $${symOf(position)} — ${pnlPct >= 0 ? 'profit' : 'loss'}: ${pnlSol >= 0 ? '+' : ''}${pnlSol.toFixed(4)} SOL`, 'trade',
{ phase: 'exit', mint: position.mint, symbol: position.symbol || null, solDelta: pnlSol, pct: pnlPct });
diff --git a/packages/agent-sniper/src/exit-logic.js b/packages/agent-sniper/src/exit-logic.js
index 42bbbca23..c9545ed64 100644
--- a/packages/agent-sniper/src/exit-logic.js
+++ b/packages/agent-sniper/src/exit-logic.js
@@ -59,3 +59,77 @@ export function decideExit(pos, value, peak, nowMs, sentiment = null) {
return null;
}
+
+/** The take-initials multiple (× entry) or null when the ladder is off (must be
+ * > 1 — you can't recover initials below cost). */
+export function ladderMultiple(v) {
+ const x = num(v);
+ return x != null && x > 1 ? x : null;
+}
+
+/** Moon-bag floor as a fraction of the position that must ALWAYS remain on the
+ * take-initials event. Default 15%, clamped to [0, 0.95] so a sell can never be
+ * the whole bag. */
+export function moonbagFraction(v) {
+ const x = num(v);
+ const frac = x == null ? 15 : x;
+ return Math.max(0, Math.min(0.95, frac / 100));
+}
+
+/**
+ * Laddered exit: the reason AND what fraction of the CURRENT remaining position
+ * to sell. Encodes the owner's rule: never cut 100% on the way up — at
+ * `initials_out_multiple`× entry (e.g. 2×) sell just enough to recover the cost
+ * basis (fraction = entry/value, capped at 1 − moonbag floor) and hold a moon bag
+ * that rides on the trailing stop. Protective exits (stop-loss → signal-flip →
+ * trailing-stop → timeout) are always FULL exits of the remainder, and stop-loss
+ * wins every conflict.
+ *
+ * OPT-IN: with no `initials_out_multiple` set it is byte-for-byte the classic
+ * full-exit `decideExit`, so existing strategies are unchanged.
+ *
+ * @returns {{ reason: string, sellFraction: number, recoversInitials?: boolean }|null}
+ */
+export function decideLadderedExit(pos, value, peak, nowMs, sentiment = null) {
+ const mult = ladderMultiple(pos.initials_out_multiple);
+ if (mult == null) {
+ const reason = decideExit(pos, value, peak, nowMs, sentiment);
+ return reason ? { reason, sellFraction: 1 } : null;
+ }
+
+ const entry = num(pos.entry_quote_lamports, 0) || 0;
+ if (entry <= 0) return null;
+ const pnlPct = ((value - entry) / entry) * 100;
+ const moonbag = moonbagFraction(pos.moonbag_min_pct);
+ const recovered = pos.initials_recovered === true;
+
+ // Protective exits — full exit of the remainder; stop-loss wins.
+ const stop = num(pos.stop_loss_pct);
+ if (stop != null && pnlPct <= -Math.abs(stop)) return { reason: 'stop_loss', sellFraction: 1 };
+ if (sentiment && value < entry && sentiment.signal === 'bearish') {
+ const conf = num(sentiment.confidence);
+ if (conf != null && conf >= sentiment.minConfidence) return { reason: 'signal_flip', sellFraction: 1 };
+ }
+ const trail = num(pos.trailing_stop_pct);
+ if (trail != null && peak > 0 && peak > entry && ((peak - value) / peak) * 100 >= Math.abs(trail)) {
+ return { reason: 'trailing_stop', sellFraction: 1 };
+ }
+
+ // Take-initials — first profit event, once, before initials are recovered.
+ if (!recovered && value >= entry * mult) {
+ 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.
+ const tp = num(pos.take_profit_pct);
+ if (recovered && tp != null && pnlPct >= Math.abs(tp)) return { reason: 'take_profit', sellFraction: 1 };
+
+ // Timeout — full exit of the remainder.
+ const maxHold = num(pos.max_hold_seconds);
+ const openedAt = num(pos.opened_at_ms);
+ if (maxHold != null && openedAt != null && nowMs - openedAt >= maxHold * 1000) {
+ return { reason: 'timeout', sellFraction: 1 };
+ }
+ return null;
+}
diff --git a/packages/agent-sniper/src/positions.js b/packages/agent-sniper/src/positions.js
index 275fb4832..d03199e9c 100644
--- a/packages/agent-sniper/src/positions.js
+++ b/packages/agent-sniper/src/positions.js
@@ -6,7 +6,7 @@
// it needs no per-mint trade feed.
import { PublicKey } from '@solana/web3.js';
-import { decideExit } from './exit-logic.js';
+import { decideLadderedExit } from './exit-logic.js';
import { executeSell } from './executor.js';
async function tickPosition(cfg, pos, ports) {
@@ -48,8 +48,13 @@ async function tickPosition(cfg, pos, ports) {
} catch { /* sentiment offline — fall back to stop/trailing/TP */ }
}
- const reason = decideExit(pos, value, peak, Date.now(), sentiment);
- if (reason) await executeSell({ cfg, position: pos, reason, ports });
+ const exit = decideLadderedExit(pos, value, peak, Date.now(), sentiment);
+ if (exit) {
+ await executeSell({
+ cfg, position: pos, reason: exit.reason, ports,
+ fraction: exit.sellFraction, recoversInitials: exit.recoversInitials === true,
+ });
+ }
}
/** Run one sweep over all open positions. An error on one never aborts the rest. */
diff --git a/packages/agent-sniper/test/laddered-exit.test.js b/packages/agent-sniper/test/laddered-exit.test.js
new file mode 100644
index 000000000..10c1cc16c
--- /dev/null
+++ b/packages/agent-sniper/test/laddered-exit.test.js
@@ -0,0 +1,68 @@
+import { describe, it, expect } from 'vitest';
+import { decideLadderedExit, moonbagFraction, ladderMultiple } from '../src/exit-logic.js';
+
+// The owner's rules, pinned for the fleet engine: buy nothing outside 10k–100k
+// (scorer, tested elsewhere) and NEVER cut 100% on the way up — take initials at
+// 2×, hold a moon bag, protect it with the trailing stop; stop-loss always wins.
+
+const ENTRY = 1_000_000_000;
+const pos = (over = {}) => ({
+ entry_quote_lamports: String(ENTRY),
+ stop_loss_pct: 30,
+ trailing_stop_pct: 20,
+ take_profit_pct: null,
+ max_hold_seconds: null,
+ opened_at_ms: 1_000_000_000_000,
+ initials_out_multiple: 2,
+ moonbag_min_pct: 15,
+ initials_recovered: false,
+ ...over,
+});
+const NOW = 1_000_000_000_000 + 60_000;
+
+describe('fleet ladder helpers', () => {
+ it('ladderMultiple requires > 1', () => {
+ expect(ladderMultiple(2)).toBe(2);
+ expect(ladderMultiple(1)).toBe(null);
+ expect(ladderMultiple(null)).toBe(null);
+ });
+ it('moonbagFraction defaults 15%, clamps [0,0.95]', () => {
+ expect(moonbagFraction(null)).toBeCloseTo(0.15);
+ expect(moonbagFraction(200)).toBe(0.95);
+ });
+});
+
+describe('fleet decideLadderedExit', () => {
+ it('holds under 2× (no premature take)', () => {
+ expect(decideLadderedExit(pos(), 1.7 * ENTRY, 1.7 * ENTRY, NOW)).toBe(null);
+ });
+ it('at 2× sells half (recovers initials), keeps a moon bag, never 100%', () => {
+ const d = decideLadderedExit(pos(), 2 * ENTRY, 2 * ENTRY, NOW);
+ expect(d.reason).toBe('take_initials');
+ expect(d.sellFraction).toBeCloseTo(0.5);
+ expect(d.sellFraction).toBeLessThan(1);
+ expect(d.recoversInitials).toBe(true);
+ });
+ it('at 5× keeps 80% moon bag', () => {
+ expect(decideLadderedExit(pos(), 5 * ENTRY, 5 * ENTRY, NOW).sellFraction).toBeCloseTo(0.2);
+ });
+ it('never breaches the moonbag floor', () => {
+ const d = decideLadderedExit(pos({ initials_out_multiple: 1.05, moonbag_min_pct: 90 }), 1.05 * ENTRY, 1.05 * ENTRY, NOW);
+ expect(d.sellFraction).toBeCloseTo(0.1);
+ });
+ it('stop-loss is a full exit and wins', () => {
+ const d = decideLadderedExit(pos(), 0.6 * ENTRY, 2.5 * ENTRY, NOW);
+ expect(d.reason).toBe('stop_loss');
+ expect(d.sellFraction).toBe(1);
+ });
+ it('moon bag exits fully on the trailing stop after initials', () => {
+ const d = decideLadderedExit(pos({ initials_recovered: true }), 3 * ENTRY, 4 * ENTRY, NOW);
+ expect(d.reason).toBe('trailing_stop');
+ expect(d.sellFraction).toBe(1);
+ });
+ it('ladder off (no multiple) = classic full exit', () => {
+ const d = decideLadderedExit(pos({ initials_out_multiple: null, take_profit_pct: 60 }), 2 * ENTRY, 2 * ENTRY, NOW);
+ expect(d.reason).toBe('take_profit');
+ expect(d.sellFraction).toBe(1);
+ });
+});