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(sniper): let the moon bag ride after take-initials instead of selling it on the next sweep

nirholas6d15fa7ab17e
diff --git a/api/_lib/migrations/20261001090000_sniper_position_stake.sql b/api/_lib/migrations/20261001090000_sniper_position_stake.sql
new file mode 100644
index 000000000..0cbe78472
--- /dev/null
+++ b/api/_lib/migrations/20261001090000_sniper_position_stake.sql
@@ -0,0 +1,49 @@
+-- Migration: record each sniper position's original stake, and correct the
+-- realized % on laddered trades that was computed against the wrong basis.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261001090000_sniper_position_stake.sql
+-- Idempotent.
+--
+-- After a take-initials leg, executeSell scales entry_quote_lamports down to the
+-- cost basis of the moon bag that remains, which the exit rules need. The final
+-- close then divided cumulative realized P&L by that REDUCED basis, so every
+-- laddered trade booked roughly double its true return (a +73% trade stored as
+-- +215%). realized_pnl_pct feeds the optimizer, the leaderboard, trader stats and
+-- the Oracle calibration, so the inflation propagated everywhere.
+--
+-- stake_lamports is the SOL actually committed at entry. The worker writes it on
+-- every fill from now on and divides by it at close. Historical rows are
+-- backfilled from what is provable:
+-- * never laddered: the stake is entry_quote_lamports, which was never scaled;
+-- * laddered with a take_initials journal entry: the basis was scaled by
+-- (1 - sold_fraction), so the stake is entry_quote_lamports / (1 - sold_fraction);
+-- * laddered with no journal entry (7 rows at the time of writing): left NULL,
+-- because the original stake cannot be recovered without guessing.
+
+alter table agent_sniper_positions
+ add column if not exists stake_lamports numeric(40, 0);
+
+update agent_sniper_positions
+set stake_lamports = entry_quote_lamports
+where stake_lamports is null
+ and entry_quote_lamports is not null
+ and initials_recovered is not true;
+
+update agent_sniper_positions p
+set stake_lamports = round(p.entry_quote_lamports / (1 - j.sold_fraction))
+from (
+ select distinct on (position_id) position_id, sold_fraction
+ from trading_journal
+ where event = 'take_initials' and sold_fraction > 0 and sold_fraction < 1
+ order by position_id, ts
+) j
+where p.id = j.position_id
+ and p.stake_lamports is null
+ and p.initials_recovered = true
+ and p.entry_quote_lamports is not null;
+
+update agent_sniper_positions
+set realized_pnl_pct = realized_pnl_lamports / stake_lamports * 100
+where initials_recovered = true
+ and status = 'closed'
+ and stake_lamports > 0
+ and realized_pnl_lamports is not null;
diff --git a/tests/sniper-laddered-exit.test.js b/tests/sniper-laddered-exit.test.js
index c1cf0c4fe..5c30f796e 100644
--- a/tests/sniper-laddered-exit.test.js
+++ b/tests/sniper-laddered-exit.test.js
@@ -121,14 +121,35 @@ describe('the owner rule: never sell 100% of a position in profit', () => {
expect(d.keepsMoonbag).toBe(true);
});
- it('keeps a moon bag on a timeout in profit', () => {
+ it('keeps a moon bag on a timeout in profit (stake still at risk)', () => {
const d = decideLadderedExit(
- base({ initials_recovered: true, max_hold_seconds: 60 }),
+ base({ 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).toBeCloseTo(0.85);
+ // Sells exactly the stake back (entry/value), the rest rides free.
+ expect(d.sellFraction).toBeCloseTo(1 / 1.5);
+ expect(d.keepsMoonbag).toBe(true);
+ });
+
+ it('never times out a recovered bag: house money has no clock', () => {
+ const d = decideLadderedExit(
+ base({ initials_recovered: true, max_hold_seconds: 60 }),
+ 1.5 * ENTRY, 1.6 * ENTRY,
+ new Date('2026-07-03T09:00:00Z').getTime(),
+ );
+ expect(d).toBe(null);
+ });
+
+ it('does not fire take-profit at the ladder price right after initials', () => {
+ // The regression: entry is the bag's scaled basis after initials, so value/entry
+ // is ~2x the moment the ladder fires. TP 60 used to be "met" immediately.
+ const pos = base({ initials_recovered: true, take_profit_pct: 60 });
+ expect(decideLadderedExit(pos, 2.05 * ENTRY, 2.05 * ENTRY, NOW)).toBe(null);
+ expect(decideLadderedExit(pos, 3.1 * ENTRY, 3.1 * ENTRY, NOW)).toBe(null);
+ const d = decideLadderedExit(pos, 3.25 * ENTRY, 3.25 * ENTRY, NOW);
+ expect(d.reason).toBe('take_profit');
expect(d.keepsMoonbag).toBe(true);
});
@@ -166,8 +187,8 @@ describe('the owner rule: never sell 100% of a position in profit', () => {
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()],
+ ['take_profit', base({ initials_recovered: true, take_profit_pct: 50 }), 3.1 * ENTRY, 3.1 * ENTRY, NOW],
+ ['timeout', base({ max_hold_seconds: 1 }), 1.5 * ENTRY, 1.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);
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index c65ca0fef..91f925d51 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -583,6 +583,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
status = 'open', buy_sig = ${sig},
error = ${ammEntry ? 'graduated:amm_entry' : null},
entry_quote_lamports = ${entryCost.toString()},
+ stake_lamports = ${entryCost.toString()},
base_amount = ${baseAmount.toString()},
entry_price_lamports_per_token = ${pricePerToken},
entry_price_impact_pct = ${Number(quote.priceImpactPct)},
@@ -801,7 +802,11 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recover
}
const pnl = legPnl;
- const pnlPct = entryFull > 0n ? (Number(cumRealized) / Number(entryFull)) * 100 : 0;
+ // Divide by the ORIGINAL stake. After a take-initials leg entryFull is only
+ // the moon bag's scaled-down basis, and dividing by it roughly doubled the
+ // booked % of every laddered trade (fed straight into the optimizer).
+ const stake = position.stake_lamports != null ? BigInt(position.stake_lamports) : entryFull;
+ const pnlPct = stake > 0n ? (Number(cumRealized) / Number(stake)) * 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
diff --git a/workers/agent-sniper/exit-logic.js b/workers/agent-sniper/exit-logic.js
index b9e255152..b795cba02 100644
--- a/workers/agent-sniper/exit-logic.js
+++ b/workers/agent-sniper/exit-logic.js
@@ -225,11 +225,22 @@ export function decideLadderedExit(pos, value, peak, now = Date.now(), sentiment
}
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.
+ // 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, and it is
+ // measured from the price the ladder fired at, not from the original entry.
+ // After the initials leg `entry` is the moon bag's scaled-down basis, so
+ // value/entry is the price multiple (~2x at that moment): measuring the
+ // ceiling from entry meant any take_profit_pct <= 100 was already met and
+ // the very next sweep sold the bag the ladder had just set free. Measured
+ // from the ladder price, TP 60 means "the next +60% above 2x", i.e. 3.2x.
+ const tpBase = recovered && mult != null ? entry * mult : entry;
+ if (tp != null && value >= tpBase * (1 + tp / 100) && (recovered || mult == null)) {
reason = 'take_profit';
- } else {
+ } else if (!recovered) {
+ // The clock only runs on money still at risk. A recovered bag is house
+ // money: runners peak a median 12-37 minutes after the entry band and the
+ // largest 4-41 hours later, so a 30-60 minute max hold sold exactly the
+ // tail the ladder exists to keep (one bag was timed out at 24.7x).
const heldS = (now - new Date(pos.opened_at).getTime()) / 1000;
if (pos.max_hold_seconds != null && heldS >= pos.max_hold_seconds) reason = 'timeout';
}
diff --git a/workers/agent-sniper/strategy-store.js b/workers/agent-sniper/strategy-store.js
index 10f76784a..80bebd54c 100644
--- a/workers/agent-sniper/strategy-store.js
+++ b/workers/agent-sniper/strategy-store.js
@@ -69,10 +69,14 @@ export function cachedStrategies() {
/** Count an agent's positions that still hold (or are mid-open) on this network. */
export async function countOpenPositions(agentId, network) {
+ // A recovered moon bag is house money riding on its own exit rules; it holds
+ // no stake at risk, so it must not hold a concurrency slot. Counting it meant a
+ // bag kept open for a long run blocked the arm from taking any new entry.
const [r] = await sql`
SELECT count(*)::int AS n FROM agent_sniper_positions
WHERE agent_id = ${agentId} AND network = ${network}
AND status IN ('opening','open','closing')
+ AND initials_recovered IS NOT TRUE
`;
return r?.n ?? 0;
}
@@ -80,7 +84,9 @@ export async function countOpenPositions(agentId, network) {
/** Lamports committed by an agent today (UTC) — the daily-budget denominator. */
export async function getDailySpend(agentId, network) {
const [r] = await sql`
- SELECT coalesce(sum(entry_quote_lamports), 0)::text AS spent
+ -- The stake committed, not the post-ladder basis: take-initials scales
+ -- entry_quote_lamports down, which made a laddered trade under-count spend.
+ SELECT coalesce(sum(coalesce(stake_lamports, entry_quote_lamports)), 0)::text AS spent
FROM agent_sniper_positions
WHERE agent_id = ${agentId} AND network = ${network}
AND opened_at >= date_trunc('day', now())