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.

Let paid x402 sentiment drive an early sniper loss-cut

nirholasfa006580c171
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f9871b38b..d64a773b0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Meet the agent behind each coin in interactive 3D** — Every coin page now shows the launching agent as a live, interactive 3D avatar right on the page — drag to orbit, scroll to zoom — instead of a flat thumbnail. Agents with their own model show it; the rest wear the shared base avatar so the stage is never empty. A "See in world" link drops that avatar straight into the walkable $THREE world. The 3D view only loads once it scrolls into view, so pages stay fast, and it falls back gracefully if a model can't load. (`/launches`) `[feature]`
- **Multi-agent collaboration — watch a team take on one goal** — Give a lead agent a goal and watch a full team assemble to tackle it. The lead decomposes the goal, delegates sub-tasks to teammates, and hires paid agents over real x402 — every handoff stamped with an on-chain receipt and an explorer link. A live dependency graph on /agents-live and /agent-screen shows each node pulse from queued to running to done, with cost badges and real signatures as they settle. One goal, real payments, verifiable provenance. (`/agents-live`) `[feature]`
- **New dashboard: total agent-to-agent economy volume** — There's now a live dashboard for the whole agent-to-agent economy: the total real USDC that agents have paid each other for hiring paid skills over x402. The headline is the all-time settled volume, alongside 7-day volume, average hire value, and how many agents are earning vs. paying. A 90-day volume chart (switchable to 7d/30d) shows the trend, two leaderboards rank the top-earning and top-spending agents, and a live feed lists the latest settlements — each one linking straight to its on-chain proof on Solscan. Every number is read from the real hire ledger; nothing is simulated. (`/agent-economy-volume`) `[feature]`
+- **New docs for the agent economy, payments, and avatar pipeline** — The docs now cover the systems that move real money through three.ws and had been running ahead of their documentation. New pages explain the circulation engine (how platform agents tip, pay, trade, and launch with one another), the money feed, agent custodial wallets and spend caps, the marketplace buy/sell flow, coin launches, the full x402 payment surface (paid endpoints, the buyer client, and the autonomous loop that buys market intel), AgenC, the MCP tool catalog with per-tool pricing, and the end-to-end avatar generation-to-animation pipeline. (`/docs/circulation-engine`) `[docs]`
- **Newsroom Anchor: agents read the market to you, live and on air** — Open an agent's screen and it becomes a live market-news anchor. Every ~90 seconds it pulls real intel — narrative momentum, sentiment, and flow — scripts a tight bulletin, and reads it aloud in a real synthesized voice while its 3D avatar lip-syncs to the words. The headline slides up as a broadcast lower-third, and the live wall shows what each anchor is reporting with a red ON AIR ticker. Audio is muted by default with one-tap unmute (press A); if a feed is down the anchor reports only what's live instead of going silent, and a rig without face morphs still talks via a jaw-bob driven by the real audio. (`/agent-screen`) `[feature]`
- **Oracle no longer mistakes stablecoins for coins** — The Oracle's feeds, movers, search, and wins gallery now ignore stablecoins and SOL-type tokens (USDC, USDT, wrapped/staked SOL, and similar). These show up as the other side of every trade but were never launched coins, so one was slipping into the rankings as a junk entry with an absurd multiple. They're now filtered out the moment data is ingested, hidden everywhere they're read, and any that were already cached are cleaned up automatically. (`/oracle`) `[fix]`
- **Portfolio dashboard loads your agent balances again** — The portfolio page now shows your agents' live balances and value-over-time chart instead of failing to load. The endpoints that feed the page — your aggregated holdings, the 90-day history chart, and the per-token drill-down — had no server route wired up, so every request came back empty and the page sat blank. The routes are now in place, so your wallets, totals, history, and individual token views all populate as they should. (`/dashboard/portfolio`) `[fix]`
@@ -39,6 +40,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Sentiment Heatmap: a live 3D market field your agent reads aloud** — Open an agent's screen and arm the new Sentiment Heatmap panel: a glowing 3D field of tokens that pulses with the market, $THREE pinned at the centre and labelled. Each token is a pillar — colour is its 24h momentum (cold blue → slate → green-hot), height is its 24h volume, and the strongest movers blaze with bloom while the camera drifts slowly around the field. The data is live: trending market data from Dexscreener and pump.fun, with $THREE enriched by a real pump.fun-comment sentiment pulse. As tokens spike, the agent calls the moment in its activity log — "Heating across the board, $THREE up on rising volume" — narrated by the brain and throttled so it never floods. Hover any tile for momentum and volume, hit the ◎ $THREE button to recentre on the anchor, and when the agent's screen is otherwise idle the heatmap casts to the live wall so the card is never blank. Press H to toggle it. (`/agent-screen`) `[feature]`
- **Smart-Money wallet reputation stays fresh again** — The job that scores every wallet's realized track record and detects sybil/insider clusters was quietly timing out on large datasets, leaving the Smart-Money graph that powers the launch firewall, the sniper, and the public Smart-Money page increasingly stale. It now writes thousands of wallet scores in a handful of bulk operations instead of one row at a time, so it finishes in seconds and the reputation data behind every "who's in" breakdown stays current. Coin cards also stop re-requesting Oracle conviction for coins the data brain hasn't observed yet, so pages stay lighter. (`/smart-money`) `[fix, infra]`
- **Sniper agents keep their wallets fueled automatically** — A live sniper agent spends SOL on every coin it buys, and once its wallet ran dry it would quietly fail every snipe while still looking healthy. Agents now top themselves back up from the platform treasury the moment their balance drops below a floor — refilling to a working reserve, with per-transfer and daily spend caps and a ledger that survives restarts so the caps can't be bypassed. The sniper status page now shows the live treasury flow: how much SOL has fueled agents today and in total, so you can see the money actually moving. `[feature, infra]`
+- **Sniper now acts on the market intel it pays for** — Every coin the sniper holds is enriched with a live market sentiment read, bought autonomously with real USDC over x402 from the platform's own intel endpoints. That paid signal now does more than nudge entries — when a held position is underwater and its signal flips confidently bearish, the sniper can cut the loser early instead of riding it down to the hard stop-loss. The behaviour is opt-in per deployment and never overrides the stop-loss, a take-profit, or a position that's in the green, so existing strategies are unchanged until an operator turns it on. `[feature, improvement]`
- **Solana Metaplex agents now appear in the on-chain deployments feed** — The on-chain Deployments feed is no longer EVM-only. Every Solana agent minted as a Metaplex Core asset — both the ones three.ws launches into its own Agents collection and external agents in the Metaplex Agent Registry — now lands in the same live stream alongside ERC-8004 registrations, the moment each mint confirms. Solana shows up as its own chain in the feed, the top-chains panel, and the 24h/7d counters, with rows linking straight to Solscan. The mainnet/testnet toggle maps to Solana mainnet-beta and devnet. (`/deployments`) `[feature]`
- **Talk to any live agent — it answers out loud and remembers the conversation** — Type a question into the bar on any agent's screen and it answers you live — in its own persona and voice. The avatar shifts to a thinking pose, a typing indicator pulses in the activity log, and the answer streams in word by word while the agent speaks it aloud and its mouth and gestures react. Ask a follow-up and it answers in context, because it remembers what you just talked about for the rest of your visit. Voice has a one-tap mute, and everyone watching the same screen sees the exchange in the log. Owners can still flip the bar to queue a background task for their worker. (`/agent-screen`) `[feature]`
- **Team Task: watch a crew of agents take on one goal** — Give a lead agent a goal and watch the team assemble. On the live wall (“Run a Team Task”) or from any agent’s task bar (flip the new “Team” toggle), the lead splits the work into sub-tasks and renders them as a living dependency graph: nodes pulse while they run, edges flow on each handoff. Free sub-tasks are delegated as real reasoning turns; paid ones hire a teammate agent over real x402 — each hire shows its USD cost, settles from the lead’s wallet under its own spend policy, and drops an on-chain receipt chip you can open in the explorer. Total spend is hard-capped and split across hires, one failed teammate never aborts the run, and every state — planning, running, done, and budget-blocked — is designed. (`/agents-live`) `[feature]`
diff --git a/api/_lib/migrations/20260629140000_sniper_signal_flip_exit.sql b/api/_lib/migrations/20260629140000_sniper_signal_flip_exit.sql
new file mode 100644
index 000000000..088d4cfaf
--- /dev/null
+++ b/api/_lib/migrations/20260629140000_sniper_signal_flip_exit.sql
@@ -0,0 +1,25 @@
+-- Migration: allow the 'signal_flip' sniper exit reason.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260629140000_sniper_signal_flip_exit.sql
+-- Idempotent.
+--
+-- The sniper already pays real USDC (x402) for per-coin sentiment, persisted to
+-- sniper_coin_sentiment. This exit reason lets that paid intel actually drive a
+-- sell: when a held coin's signal flips strongly bearish while the position is
+-- underwater, the worker can cut the loser early instead of waiting for the hard
+-- stop-loss. Opt-in at the worker (SNIPER_EXIT_ON_BEARISH) — existing strategies
+-- are unaffected until an operator enables it.
+--
+-- Widens the agent_sniper_positions.exit_reason CHECK to include 'signal_flip'.
+
+begin;
+
+alter table agent_sniper_positions
+ drop constraint if exists agent_sniper_positions_exit_reason_check;
+
+alter table agent_sniper_positions
+ add constraint agent_sniper_positions_exit_reason_check
+ check (exit_reason in
+ ('take_profit','stop_loss','trailing_stop','timeout',
+ 'manual','kill_switch','graduated','error','signal_flip'));
+
+commit;
diff --git a/data/changelog.json b/data/changelog.json
index e09a90b0b..c00bcbc98 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$comment": "Curated changelog entries for three.ws \u2014 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-06-29",
+ "title": "Sniper now acts on the market intel it pays for",
+ "summary": "Every coin the sniper holds is enriched with a live market sentiment read, bought autonomously with real USDC over x402 from the platform's own intel endpoints. That paid signal now does more than nudge entries — when a held position is underwater and its signal flips confidently bearish, the sniper can cut the loser early instead of riding it down to the hard stop-loss. The behaviour is opt-in per deployment and never overrides the stop-loss, a take-profit, or a position that's in the green, so existing strategies are unchanged until an operator turns it on.",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-29",
+ "title": "New docs for the agent economy, payments, and avatar pipeline",
+ "summary": "The docs now cover the systems that move real money through three.ws and had been running ahead of their documentation. New pages explain the circulation engine (how platform agents tip, pay, trade, and launch with one another), the money feed, agent custodial wallets and spend caps, the marketplace buy/sell flow, coin launches, the full x402 payment surface (paid endpoints, the buyer client, and the autonomous loop that buys market intel), AgenC, the MCP tool catalog with per-tool pricing, and the end-to-end avatar generation-to-animation pipeline.",
+ "tags": [
+ "docs"
+ ],
+ "link": "/docs/circulation-engine"
+ },
{
"date": "2026-06-29",
"title": "Sniper agents keep their wallets fueled automatically",
diff --git a/public/changelog.json b/public/changelog.json
index 25d2fba1f..53665c1cd 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T10:42:54.816Z",
+ "generated_at": "2026-06-29T10:50:45.768Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -268,6 +268,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "New docs for the agent economy, payments, and avatar pipeline",
+ "summary": "The docs now cover the systems that move real money through three.ws and had been running ahead of their documentation. New pages explain the circulation engine (how platform agents tip, pay, trade, and launch with one another), the money feed, agent custodial wallets and spend caps, the marketplace buy/sell flow, coin launches, the full x402 payment surface (paid endpoints, the buyer client, and the autonomous loop that buys market intel), AgenC, the MCP tool catalog with per-tool pricing, and the end-to-end avatar generation-to-animation pipeline.",
+ "link": "/docs/circulation-engine",
+ "tags": [
+ "docs"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -340,6 +350,17 @@
"infra"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Sniper now acts on the market intel it pays for",
+ "summary": "Every coin the sniper holds is enriched with a live market sentiment read, bought autonomously with real USDC over x402 from the platform's own intel endpoints. That paid signal now does more than nudge entries — when a held position is underwater and its signal flips confidently bearish, the sniper can cut the loser early instead of riding it down to the hard stop-loss. The behaviour is opt-in per deployment and never overrides the stop-loss, a take-profit, or a position that's in the green, so existing strategies are unchanged until an operator turns it on.",
+ "link": null,
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 3b09554f5..d21cf4c52 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -214,6 +214,14 @@
<category>feature</category>
<description>There's now a live dashboard for the whole agent-to-agent economy: the total real USDC that agents have paid each other for hiring paid skills over x402. The headline is the all-time settled volume, alongside 7-day volume, average hire value, and how many agents are earning vs. paying. A 90-day volume chart (switchable to 7d/30d) shows the trend, two leaderboards rank the top-earning and top-spending agents, and a live feed lists the latest settlements — each one linking straight to its on-chain proof on Solscan. Every number is read from the real hire ledger; nothing is simulated.</description>
</item>
+ <item>
+ <title>New docs for the agent economy, payments, and avatar pipeline</title>
+ <link>https://three.ws/docs/circulation-engine</link>
+ <guid isPermaLink="false">2026-06-29:New docs for the agent economy, payments, and avatar pipeline</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>docs</category>
+ <description>The docs now cover the systems that move real money through three.ws and had been running ahead of their documentation. New pages explain the circulation engine (how platform agents tip, pay, trade, and launch with one another), the money feed, agent custodial wallets and spend caps, the marketplace buy/sell flow, coin launches, the full x402 payment surface (paid endpoints, the buyer client, and the autonomous loop that buys market intel), AgenC, the MCP tool catalog with per-tool pricing, and the end-to-end avatar generation-to-animation pipeline.</description>
+ </item>
<item>
<title>Newsroom Anchor: agents read the market to you, live and on air</title>
<link>https://three.ws/agent-screen</link>
@@ -270,6 +278,14 @@
<category>feature</category>
<description>A live sniper agent spends SOL on every coin it buys, and once its wallet ran dry it would quietly fail every snipe while still looking healthy. Agents now top themselves back up from the platform treasury the moment their balance drops below a floor — refilling to a working reserve, with per-transfer and daily spend caps and a ledger that survives restarts so the caps can't be bypassed. The sniper status page now shows the live treasury flow: how much SOL has fueled agents today and in total, so you can see the money actually moving.</description>
</item>
+ <item>
+ <title>Sniper now acts on the market intel it pays for</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-29:Sniper now acts on the market intel it pays for</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every coin the sniper holds is enriched with a live market sentiment read, bought autonomously with real USDC over x402 from the platform's own intel endpoints. That paid signal now does more than nudge entries — when a held position is underwater and its signal flips confidently bearish, the sniper can cut the loser early instead of riding it down to the hard stop-loss. The behaviour is opt-in per deployment and never overrides the stop-loss, a take-profit, or a position that's in the green, so existing strategies are unchanged until an operator turns it on.</description>
+ </item>
<item>
<title>Solana Metaplex agents now appear in the on-chain deployments feed</title>
<link>https://three.ws/deployments</link>
diff --git a/public/features.json b/public/features.json
index 092ab6628..8e316139d 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T10:42:54.804Z",
+ "generated_at": "2026-06-29T10:50:45.756Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/agent-sniper-signal-flip-exit.test.js b/tests/agent-sniper-signal-flip-exit.test.js
new file mode 100644
index 000000000..41e64686d
--- /dev/null
+++ b/tests/agent-sniper-signal-flip-exit.test.js
@@ -0,0 +1,54 @@
+/**
+ * agent-sniper — signal_flip exit (paid-intel-driven early loss cut).
+ *
+ * decideExit gains an optional `sentiment` arg. These lock in that:
+ * - it stays inert when omitted (backtester / existing callers unchanged),
+ * - a confident bearish flip cuts an UNDERWATER position before the stop,
+ * - it never overrides the hard stop-loss, a take-profit, or a winner,
+ * - the confidence floor is honoured.
+ * decideExit is pure (no DB, no I/O), so this needs no fixtures.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { decideExit } from '../workers/agent-sniper/exit-logic.js';
+
+const EV = 1_000_000_000; // 1 SOL entry, in lamports
+const basePos = {
+ entry_quote_lamports: String(EV),
+ stop_loss_pct: 30,
+ trailing_stop_pct: null,
+ take_profit_pct: 100,
+ max_hold_seconds: 3600,
+ opened_at: new Date(Date.now() - 60_000).toISOString(),
+};
+
+const bearish = (confidence) => ({ signal: 'bearish', confidence, minConfidence: 0.7 });
+
+describe('decideExit — signal_flip', () => {
+ it('is inert when no sentiment is passed (replay/backtest path)', () => {
+ // 10% underwater, above the 30% stop — would hold without sentiment.
+ expect(decideExit(basePos, 0.9 * EV, EV)).toBe(null);
+ });
+
+ it('cuts an underwater position on a confident bearish flip', () => {
+ expect(decideExit(basePos, 0.9 * EV, EV, Date.now(), bearish(0.85))).toBe('signal_flip');
+ });
+
+ it('does not fire on a position that is in profit', () => {
+ expect(decideExit(basePos, 1.2 * EV, 1.2 * EV, Date.now(), bearish(0.95))).toBe(null);
+ });
+
+ it('respects the confidence floor', () => {
+ expect(decideExit(basePos, 0.9 * EV, EV, Date.now(), bearish(0.5))).toBe(null);
+ });
+
+ it('never overrides the hard stop-loss', () => {
+ // 40% down is past the 30% stop — stop_loss must win even with a bearish flip.
+ expect(decideExit(basePos, 0.6 * EV, EV, Date.now(), bearish(0.99))).toBe('stop_loss');
+ });
+
+ it('ignores a bullish/neutral signal', () => {
+ expect(decideExit(basePos, 0.9 * EV, EV, Date.now(), { signal: 'bullish', confidence: 0.99, minConfidence: 0.7 })).toBe(null);
+ expect(decideExit(basePos, 0.9 * EV, EV, Date.now(), { signal: 'neutral', confidence: 0.99, minConfidence: 0.7 })).toBe(null);
+ });
+});
diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.js
index 9def80523..9a82cf049 100644
--- a/workers/agent-sniper/config.js
+++ b/workers/agent-sniper/config.js
@@ -133,6 +133,14 @@ export function loadConfig() {
launcher: bool('SNIPER_LAUNCHER', !!process.env.AGENT_JWT),
// How often to check for due launcher configs (ms).
launcherPollMs: Math.max(30_000, num('SNIPER_LAUNCHER_POLL_MS', 60_000)),
+ // ── sentiment-flip exit ─────────────────────────────────────────────────
+ // Let the per-coin x402 sentiment the worker already pays for drive a sell:
+ // cut an underwater position early when its signal flips confidently bearish,
+ // ahead of the hard stop-loss. Off by default — existing strategies keep their
+ // exact stop/trailing/TP behaviour until an operator opts in.
+ exitOnBearish: bool('SNIPER_EXIT_ON_BEARISH', false),
+ // Minimum sentiment confidence (0..1) before a bearish flip can exit.
+ exitBearishMinConfidence: Math.max(0, Math.min(1, num('SNIPER_EXIT_BEARISH_MIN_CONFIDENCE', 0.7))),
// ── buy-side auto-funding ───────────────────────────────────────────────
// Keeps each armed agent's own wallet topped up from the launcher master so
// a hot sniper never silently runs dry and starts failing every buy. On by
diff --git a/workers/agent-sniper/exit-logic.js b/workers/agent-sniper/exit-logic.js
index 77420377e..218da0908 100644
--- a/workers/agent-sniper/exit-logic.js
+++ b/workers/agent-sniper/exit-logic.js
@@ -19,7 +19,14 @@ export function pct(n) {
/**
* Decide the exit reason for a position, or null to hold. Evaluated in priority
- * order: stop-loss → trailing-stop → take-profit → timeout.
+ * order: stop-loss → signal-flip → trailing-stop → take-profit → timeout.
+ *
+ * The hard stop-loss always wins. signal_flip is an EARLY warning that cuts a
+ * losing position before it reaches the stop, driven by the per-coin x402
+ * sentiment the worker already pays for — so it only fires while the position is
+ * underwater and never overrides a take-profit. It is inert unless the caller
+ * passes a `sentiment` (the live loop does so only when SNIPER_EXIT_ON_BEARISH
+ * is set); the backtester omits it, so replays are byte-for-byte unchanged.
*
* @param {object} pos position-like: { entry_quote_lamports, stop_loss_pct,
* trailing_stop_pct, take_profit_pct, max_hold_seconds, opened_at }
@@ -27,9 +34,11 @@ export function pct(n) {
* @param {number} peak high-water mark of `value` since entry (lamports)
* @param {number} [now] epoch ms for the timeout clock (defaults to Date.now()).
* Pass an explicit clock from a replay to keep it pure.
- * @returns {'stop_loss'|'trailing_stop'|'take_profit'|'timeout'|null}
+ * @param {{ signal?: string, confidence?: number, minConfidence?: number }|null} [sentiment]
+ * live x402 sentiment read; null/omitted disables signal_flip.
+ * @returns {'stop_loss'|'signal_flip'|'trailing_stop'|'take_profit'|'timeout'|null}
*/
-export function decideExit(pos, value, peak, now = Date.now()) {
+export function decideExit(pos, value, peak, now = Date.now(), sentiment = null) {
const entry = BigInt(pos.entry_quote_lamports || '0');
if (entry <= 0n) return null;
const ev = Number(entry);
@@ -38,6 +47,7 @@ export function decideExit(pos, value, peak, now = Date.now()) {
const tp = pct(pos.take_profit_pct);
if (sl != null && value <= ev * (1 - sl / 100)) return 'stop_loss';
+ if (isBearishFlip(sentiment) && value < ev) return 'signal_flip';
if (ts != null && peak > 0 && value <= peak * (1 - ts / 100)) return 'trailing_stop';
if (tp != null && value >= ev * (1 + tp / 100)) return 'take_profit';
@@ -45,3 +55,11 @@ export function decideExit(pos, value, peak, now = Date.now()) {
if (pos.max_hold_seconds != null && heldS >= pos.max_hold_seconds) return 'timeout';
return null;
}
+
+/** A confident bearish sentiment read. minConfidence defaults to 0.7. */
+function isBearishFlip(sentiment) {
+ if (!sentiment || sentiment.signal !== 'bearish') return false;
+ const conf = Number(sentiment.confidence);
+ const floor = Number(sentiment.minConfidence);
+ return Number.isFinite(conf) && conf >= (Number.isFinite(floor) ? floor : 0.7);
+}
diff --git a/workers/agent-sniper/positions.js b/workers/agent-sniper/positions.js
index e2d1619a2..6bb06b1fa 100644
--- a/workers/agent-sniper/positions.js
+++ b/workers/agent-sniper/positions.js
@@ -43,7 +43,15 @@ async function tickPosition(cfg, pos) {
const sym = (pos.symbol || pos.mint.slice(0, 6)).toUpperCase();
screenPush(`$${sym}: ${pnlPct >= 0 ? '+' : ''}${pnlPct.toFixed(1)}% P&L — monitoring`, 'trade');
- const reason = decideExit(pos, value, peak);
+ // Optional paid-intel exit: only read the (already-bought) x402 sentiment when
+ // the operator has armed it AND the position is underwater — the one case
+ // signal_flip can fire. A read failure degrades to the normal exit math.
+ let sentiment = null;
+ if (cfg.exitOnBearish && value < entry) {
+ sentiment = await readCoinSentiment(cfg, pos.mint);
+ }
+
+ const reason = decideExit(pos, value, peak, Date.now(), sentiment);
if (reason) await executeSell({ cfg, position: pos, reason });
}
@@ -90,6 +98,27 @@ async function requoteGraduated(cfg, pos, baseAmount, slippagePct) {
}
}
+// Read the latest x402-paid sentiment for a held coin, shaped for decideExit.
+// Returns null on any miss/error so the exit math falls back to stop/trailing/TP.
+async function readCoinSentiment(cfg, mint) {
+ try {
+ const [row] = await sql`
+ SELECT signal, confidence FROM sniper_coin_sentiment
+ WHERE mint = ${mint} AND network = ${cfg.network}
+ LIMIT 1
+ `;
+ if (!row) return null;
+ return {
+ signal: row.signal,
+ confidence: row.confidence == null ? null : Number(row.confidence),
+ minConfidence: cfg.exitBearishMinConfidence,
+ };
+ } catch (err) {
+ log.warn('coin sentiment read failed', { mint, err: err?.message });
+ return null;
+ }
+}
+
/** Run one sweep over all open positions. Errors on one position never abort the rest. */
export async function runPositionSweep(cfg) {
let positions;