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.

Oracle backtest API, enriched edge tab, share/watch in drawer, win exit alerts

nirholasa961b6e577ed
diff --git a/api/_lib/oracle/alerts.js b/api/_lib/oracle/alerts.js
index 0dbf716e1..c8216de26 100644
--- a/api/_lib/oracle/alerts.js
+++ b/api/_lib/oracle/alerts.js
@@ -91,6 +91,47 @@ async function markAlerted(mint, network) {
} catch { /* non-fatal */ }
}
+/**
+ * Fire a Telegram alert when an agent's open position resolves as a win.
+ * Called by the settle-loop after grading.
+ *
+ * @param {Array<{agent_name:string, agent_id:string, symbol:string, mint:string, tier:string, conviction:number, mode:string, size_sol:number, realized_pnl_sol:number, peak_multiple:number, network:string}>} exits
+ * @returns {Promise<number>} number of alerts sent
+ */
+export async function alertProfitableExit(exits) {
+ const token = process.env.TELEGRAM_BOT_TOKEN;
+ const chatId = process.env.TELEGRAM_ORACLE_CHAT_ID;
+ if (!token || !chatId || !exits?.length) return 0;
+
+ let sent = 0;
+ for (const e of exits) {
+ // Only alert live-mode wins with positive PnL or a meaningful ATH.
+ if (e.mode !== 'live' && e.mode !== 'simulate') continue;
+ if ((e.realized_pnl_sol ?? 0) <= 0 && (e.peak_multiple ?? 0) < 2) continue;
+
+ const pnlStr = e.realized_pnl_sol != null
+ ? `+${Number(e.realized_pnl_sol).toFixed(4)} SOL`
+ : `${(e.peak_multiple ?? 0).toFixed(2)}× peak`;
+ const peakStr = e.peak_multiple != null ? `${Number(e.peak_multiple).toFixed(2)}×` : '?';
+ const sizeStr = e.size_sol != null ? `${Number(e.size_sol).toFixed(3)} SOL` : '?';
+ const emoji = e.mode === 'simulate' ? '🤖 [sim]' : '🤖';
+ const tierE = tierEmoji(e.tier);
+ const agentName = escHtml(e.agent_name || e.agent_id || 'Agent');
+ const sym = escHtml(e.symbol || '?');
+ const modeLabel = e.mode === 'simulate' ? ' <i>(simulated)</i>' : '';
+
+ const text = [
+ `${emoji} <b>${agentName}</b> made <b>${escHtml(pnlStr)}</b> on <b>$${sym}</b>${modeLabel}`,
+ `Peak: <b>${peakStr}</b> · Size: ${escHtml(sizeStr)} · Entry: ${tierE} ${escHtml(e.tier)} conviction (${e.conviction ?? '?'})`,
+ `<a href="https://pump.fun/coin/${encodeURIComponent(e.mint)}">pump.fun</a> · <a href="https://three.ws/oracle?mint=${encodeURIComponent(e.mint)}">Oracle</a> · <a href="https://three.ws/agents/${encodeURIComponent(e.agent_id)}">Track record</a>`,
+ ].join('\n');
+
+ await send(text);
+ sent++;
+ }
+ return sent;
+}
+
/**
* Fire alerts for newly-scored coins that cross the tier threshold for the
* first time. Called by the oracle-score cron after each score pass.
diff --git a/api/oracle/backtest.js b/api/oracle/backtest.js
new file mode 100644
index 000000000..17d1e923b
--- /dev/null
+++ b/api/oracle/backtest.js
@@ -0,0 +1,153 @@
+/**
+ * Oracle — conviction accuracy backtest.
+ *
+ * GET /api/oracle/backtest?period=7d&tier=prime&network=mainnet
+ *
+ * Joins oracle_conviction (what the engine scored) against pump_coin_outcomes
+ * (ground truth: graduated, rugged, ATH multiple) and returns hit-rate stats
+ * per tier. This is the honest answer to "does the oracle engine actually work?"
+ *
+ * Only coins with a resolved outcome are counted — open positions are excluded
+ * from the win-rate calculation so the denominator is accurate.
+ *
+ * Params:
+ * period — 1d | 7d | 30d | 90d | all (default: 30d)
+ * tier — prime | strong | lean | watch | avoid | all (default: all)
+ * network — mainnet | devnet (default: mainnet)
+ *
+ * Cached for 5 minutes — the DB table is large and this query is expensive.
+ */
+
+import { cors, json, method, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+const PERIODS = { '1d': 1, '7d': 7, '30d': 30, '90d': 90, 'all': null };
+const TIERS = new Set(['prime', 'strong', 'lean', 'watch', 'avoid', 'all']);
+const TIER_ORDER = { prime: 5, strong: 4, lean: 3, watch: 2, avoid: 1 };
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+const CACHE_TTL_MS = 5 * 60_000;
+const _cache = new Map(); // key → { data, at }
+
+function cacheKey(period, tier, network) { return `${period}:${tier}:${network}`; }
+
+async function query(days, tier, network) {
+ const key = cacheKey(days, tier, network);
+ const hit = _cache.get(key);
+ if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.data;
+
+ // ── per-tier breakdown ────────────────────────────────────────────────────
+ const tierFilter = tier !== 'all' ? sql`and c.tier = ${tier}` : sql``;
+ const periodFilter = days != null ? sql`and c.scored_at >= now() - (${days} || ' days')::interval` : sql``;
+
+ const rows = await sql`
+ select
+ c.tier,
+ count(*)::int as total,
+ count(*) filter (where o.graduated or o.ath_multiple >= 2)::int as wins,
+ count(*) filter (where o.rugged or (o.ath_multiple is not null and o.ath_multiple < 1.2 and not o.graduated))::int as losses,
+ count(*) filter (where o.ath_multiple is not null)::int as with_ath,
+ round(avg(o.ath_multiple)::numeric, 2) as avg_ath,
+ round(percentile_cont(0.5) within group (order by o.ath_multiple)::numeric, 2) as median_ath,
+ count(*) filter (where o.ath_multiple >= 3)::int as three_x,
+ count(*) filter (where o.ath_multiple >= 5)::int as five_x,
+ count(*) filter (where o.ath_multiple >= 10)::int as ten_x,
+ count(*) filter (where o.graduated)::int as graduated,
+ count(*) filter (where o.rugged)::int as rugged
+ from oracle_conviction c
+ join pump_coin_outcomes o on o.mint = c.mint and o.network = c.network
+ where c.network = ${network}
+ and (o.graduated or o.rugged or o.ath_multiple is not null)
+ ${tierFilter}
+ ${periodFilter}
+ group by c.tier
+ order by min(case c.tier when 'prime' then 5 when 'strong' then 4 when 'lean' then 3 when 'watch' then 2 when 'avoid' then 1 else 0 end) desc
+ `;
+
+ // ── aggregate across tiers ────────────────────────────────────────────────
+ let agg = { total: 0, wins: 0, losses: 0, three_x: 0, five_x: 0, ten_x: 0, graduated: 0, rugged: 0 };
+ for (const r of rows) {
+ agg.total += r.total;
+ agg.wins += r.wins;
+ agg.losses += r.losses;
+ agg.three_x += r.three_x;
+ agg.five_x += r.five_x;
+ agg.ten_x += r.ten_x;
+ agg.graduated += r.graduated;
+ agg.rugged += r.rugged;
+ }
+ const resolved = agg.wins + agg.losses;
+ agg.win_rate = resolved ? Math.round((agg.wins / resolved) * 100) : null;
+
+ // ── top performers in the period ─────────────────────────────────────────
+ const topFilter = days != null ? sql`and c.scored_at >= now() - (${days} || ' days')::interval` : sql``;
+ const topTierFilter = tier !== 'all' ? sql`and c.tier = ${tier}` : sql``;
+ const top = await sql`
+ select c.mint, c.symbol, c.name, c.score, c.tier, o.ath_multiple, o.graduated, o.rugged
+ from oracle_conviction c
+ join pump_coin_outcomes o on o.mint = c.mint and o.network = c.network
+ where c.network = ${network}
+ and o.ath_multiple is not null
+ ${topTierFilter}
+ ${topFilter}
+ order by o.ath_multiple desc nulls last
+ limit 10
+ `;
+
+ const data = {
+ period: days != null ? `${days}d` : 'all',
+ tier,
+ network,
+ by_tier: rows.map((r) => ({
+ tier: r.tier,
+ total: r.total,
+ wins: r.wins,
+ losses: r.losses,
+ win_rate: (r.wins + r.losses) > 0 ? Math.round((r.wins / (r.wins + r.losses)) * 100) : null,
+ avg_ath: r.avg_ath ? Number(r.avg_ath) : null,
+ median_ath: r.median_ath ? Number(r.median_ath) : null,
+ three_x: r.three_x,
+ five_x: r.five_x,
+ ten_x: r.ten_x,
+ graduated: r.graduated,
+ rugged: r.rugged,
+ })),
+ aggregate: agg,
+ top_performers: top.map((r) => ({
+ mint: r.mint,
+ symbol: r.symbol,
+ name: r.name,
+ score: r.score,
+ tier: r.tier,
+ ath_multiple: r.ath_multiple ? Number(r.ath_multiple) : null,
+ graduated: r.graduated,
+ rugged: r.rugged,
+ })),
+ };
+
+ _cache.set(key, { data, at: Date.now() });
+ return data;
+}
+
+export default async function handleOracleBacktest(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const periodKey = PERIODS.hasOwnProperty(params.get('period')) ? params.get('period') : '30d';
+ const days = PERIODS[periodKey];
+ const tier = TIERS.has(params.get('tier')) ? params.get('tier') : 'all';
+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';
+
+ try {
+ const data = await query(days, tier, network);
+ return json(res, 200, data, { 'cache-control': 'public, max-age=300, s-maxage=300' });
+ } catch (err) {
+ console.error('[oracle/backtest]', err);
+ return json(res, 503, { error: 'backtest_unavailable', message: 'Could not run backtest query.' });
+ }
+}
diff --git a/pages/oracle.html b/pages/oracle.html
index 1e5ea3da6..a9d4c2e2c 100644
--- a/pages/oracle.html
+++ b/pages/oracle.html
@@ -155,6 +155,15 @@
.gradbar { height: 7px; border-radius: 4px; background: rgba(255,255,255,0.07); overflow: hidden; }
.gradbar i { display: block; height: 100%; background: linear-gradient(90deg, var(--up), var(--cyan)); }
.intro { color: var(--muted); font-size: 13.5px; max-width: 720px; margin: 0 0 16px; }
+ .edge-agg { display: grid; grid-template-columns: repeat(auto-fill, minmax(90px, 1fr)); gap: 1px; background: var(--line); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; margin-bottom: 0; }
+ .edge-kpi { background: var(--panel); padding: 12px 14px; }
+ .edge-kpi span { font: 600 10px/1 var(--mono); text-transform: uppercase; letter-spacing: .06em; color: var(--faint); display: block; margin-bottom: 6px; }
+ .edge-kpi b { font: 700 18px/1 var(--mono); color: var(--ink); }
+ .edge-kpi b.up { color: var(--up); } .edge-kpi b.dn { color: var(--down); }
+ .edge-top { display: flex; flex-direction: column; gap: 6px; }
+ .edge-top-row { display: flex; align-items: center; gap: 10px; text-decoration: none; color: var(--ink); font-size: 13px; padding: 8px 12px; border-radius: 8px; background: var(--panel); border: 1px solid var(--line); transition: border-color .14s; }
+ .edge-top-row:hover { border-color: var(--stroke-strong, var(--cyan)); }
+ .edge-ath { margin-left: auto; font: 700 13px/1 var(--mono); color: var(--up); }
/* agent panel */
.apanel { display: grid; grid-template-columns: 1fr 1.8fr; gap: 16px; align-items: start; }
@@ -207,6 +216,13 @@
.nw-sub { font: 600 10.5px/1 var(--mono); color: var(--faint); }
.nw-buy { font: 700 13px/1 var(--mono); text-align: right; }
.solscan { font: 600 12px/1 var(--mono); color: var(--cyan); }
+ .dr-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 14px 0 2px; }
+ .dr-act { font: 600 12px/1 var(--mono); color: var(--cyan); text-decoration: none; background: none; border: none; cursor: pointer; padding: 0; transition: opacity .15s; }
+ .dr-act:hover { opacity: .7; }
+ .dr-act:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 2px; }
+ .dr-watch { color: var(--faint); }
+ .dr-watch[aria-pressed="true"] { color: var(--accent); }
+ .dr-share { color: var(--amber, #f5a623); }
/* states + buttons */
.state { padding: 56px 22px; text-align: center; color: var(--muted); }
diff --git a/pages/pump-live.html b/pages/pump-live.html
index ff4c10157..7f2e9b2f8 100644
--- a/pages/pump-live.html
+++ b/pages/pump-live.html
@@ -170,7 +170,11 @@
.token-symbol { color: #888; font-size: 12px; }
.token-mcap { margin-top: 4px; font-size: 14px; color: var(--green); }
.token-meta { margin-top: 2px; font-size: 11px; color: #777; }
- .token-links { margin-top: 8px; font-size: 11px; display: flex; gap: 10px; }
+ .token-links { margin-top: 8px; font-size: 11px; display: flex; gap: 10px; align-items: center; }
+ .token-watch { background: none; border: 1px solid var(--medium-grey); border-radius: 6px; color: #666;
+ font-size: 14px; line-height: 1; padding: 2px 7px; cursor: pointer; transition: color .15s, border-color .15s; }
+ .token-watch.watched { color: #7c83ff; border-color: #7c83ff; }
+ .token-watch:hover { color: #fff; border-color: #aaa; }
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
@@ -328,6 +332,20 @@
// Refreshed every 60s; never blocks rendering. No hardcoded price.
// ════════════════════════════════════════════════════════════════════
+ const WATCH_KEY = 'ld_watchlist';
+ function isWatched(mint) {
+ try { return JSON.parse(localStorage.getItem(WATCH_KEY) || '[]').includes(mint); } catch { return false; }
+ }
+ function toggleWatch(mint) {
+ try {
+ const list = JSON.parse(localStorage.getItem(WATCH_KEY) || '[]');
+ const idx = list.indexOf(mint);
+ if (idx >= 0) list.splice(idx, 1); else list.unshift(mint);
+ localStorage.setItem(WATCH_KEY, JSON.stringify(list.slice(0, 200)));
+ return idx < 0;
+ } catch { return false; }
+ }
+
let solPrice = 0;
async function refreshSolPrice() {
@@ -573,7 +591,24 @@
solscanLink.target = '_blank';
solscanLink.rel = 'noopener noreferrer';
solscanLink.textContent = 'Solscan';
- links.append(pumpLink, solscanLink);
+ const watchBtn = document.createElement('button');
+ watchBtn.className = `token-watch${isWatched(token.mint) ? ' watched' : ''}`;
+ watchBtn.type = 'button';
+ watchBtn.textContent = isWatched(token.mint) ? '★' : '☆';
+ watchBtn.title = isWatched(token.mint) ? 'Remove from watchlist' : 'Add to watchlist';
+ watchBtn.setAttribute('aria-label', watchBtn.title);
+ watchBtn.setAttribute('aria-pressed', String(isWatched(token.mint)));
+ watchBtn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const nowWatched = toggleWatch(token.mint);
+ watchBtn.textContent = nowWatched ? '★' : '☆';
+ watchBtn.classList.toggle('watched', nowWatched);
+ const lbl = nowWatched ? 'Remove from watchlist' : 'Add to watchlist';
+ watchBtn.title = lbl;
+ watchBtn.setAttribute('aria-label', lbl);
+ watchBtn.setAttribute('aria-pressed', String(nowWatched));
+ });
+ links.append(pumpLink, solscanLink, watchBtn);
info.append(nameEl, symEl, mcapEl, links);
card.append(img, info);
diff --git a/pages/smart-money.html b/pages/smart-money.html
index f0da147bf..872a1e118 100644
--- a/pages/smart-money.html
+++ b/pages/smart-money.html
@@ -68,6 +68,16 @@
/* coin grid */
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(330px, 1fr)); gap: 14px; }
+ .sm-coin-wrap { position: relative; }
+ .sm-watch { position: absolute; top: 10px; right: 10px; z-index: 2; width: 28px; height: 28px;
+ display: grid; place-items: center; border-radius: 8px; border: 1px solid var(--line);
+ background: rgba(0,0,0,0.3); color: rgba(255,255,255,0.45); font-size: 14px; cursor: pointer;
+ transition: color .15s, border-color .15s; opacity: 0; }
+ .sm-coin-wrap:hover .sm-watch, .sm-watch.sm-watched, .sm-watch:focus-visible { opacity: 1; }
+ .sm-watch.sm-watched { color: #7c83ff; border-color: #7c83ff; background: rgba(124,131,255,.12); }
+ .sm-watch:hover { color: var(--ink); }
+ .sm-watch:focus-visible { outline: 2px solid #7c83ff; outline-offset: 1px; }
+ @media (hover: none) { .sm-watch { opacity: 1; } }
.coin { text-align: left; width: 100%; background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
border: 1px solid var(--line); border-radius: var(--r); padding: 15px; box-shadow: var(--shadow);
display: flex; flex-direction: column; gap: 13px; transition: transform .14s, border-color .18s; }
@@ -213,6 +223,20 @@
const labelText = { smart_money: 'smart money', sniper: 'sniper', dumper: 'dumper', rugger: 'rugger', fresh: 'fresh', neutral: 'neutral', unproven: 'new' };
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
+ const WATCH_KEY = 'ld_watchlist';
+ function isWatched(mint) {
+ try { return JSON.parse(localStorage.getItem(WATCH_KEY) || '[]').includes(mint); } catch { return false; }
+ }
+ function toggleSmWatch(mint) {
+ try {
+ const list = JSON.parse(localStorage.getItem(WATCH_KEY) || '[]');
+ const idx = list.indexOf(mint);
+ if (idx >= 0) list.splice(idx, 1); else list.unshift(mint);
+ localStorage.setItem(WATCH_KEY, JSON.stringify(list.slice(0, 200)));
+ return idx < 0;
+ } catch { return false; }
+ }
+
let timer = null;
async function getJSON(url) {
@@ -228,7 +252,11 @@
: `<div class="coin-img">${esc((c.symbol || '?').slice(0, 2))}</div>`;
const notable = (c.notable || []).slice(0, 4).map((n) =>
`<span class="nlabel lb-${n.label || 'neutral'}">${short(n.wallet)}</span>`).join('');
- return `<button class="coin" data-mint="${esc(c.mint)}">
+
+ const btn = document.createElement('button');
+ btn.className = 'coin';
+ btn.dataset.mint = c.mint;
+ btn.innerHTML = `
<div class="coin-top">
${img}
<div class="coin-id"><div class="coin-sym">${esc(c.symbol || '—')}</div><div class="coin-name">${esc(c.name || c.mint.slice(0, 10))}</div></div>
@@ -240,8 +268,32 @@
${c.category ? `<span class="chip cat">${esc(c.category)}</span>` : ''}
${c.graduated ? '<span class="chip" style="color:var(--up)">graduated</span>' : ''}
</div>
- ${notable ? `<div class="notable-row">${notable}</div>` : ''}
- </button>`;
+ ${notable ? `<div class="notable-row">${notable}</div>` : ''}`;
+ btn.addEventListener('click', () => openCoin(c.mint));
+
+ const watched = isWatched(c.mint);
+ const wb = document.createElement('button');
+ wb.className = `sm-watch${watched ? ' sm-watched' : ''}`;
+ wb.type = 'button';
+ wb.textContent = watched ? '★' : '☆';
+ wb.setAttribute('aria-label', watched ? 'Remove from watchlist' : 'Add to watchlist');
+ wb.setAttribute('aria-pressed', String(watched));
+ wb.title = watched ? 'Remove from watchlist' : 'Add to watchlist';
+ wb.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const nowWatched = toggleSmWatch(c.mint);
+ wb.textContent = nowWatched ? '★' : '☆';
+ wb.classList.toggle('sm-watched', nowWatched);
+ wb.setAttribute('aria-pressed', String(nowWatched));
+ const lbl = nowWatched ? 'Remove from watchlist' : 'Add to watchlist';
+ wb.setAttribute('aria-label', lbl);
+ wb.title = lbl;
+ });
+
+ const wrap = document.createElement('div');
+ wrap.className = 'sm-coin-wrap';
+ wrap.append(btn, wb);
+ return wrap;
}
function renderFeed(coins) {
@@ -252,8 +304,8 @@
The radar only lights up when wallets with a real track record start buying a new launch. As coins are judged (≈6h after launch) and reputations build, this fills in. Check back shortly.</div>`;
return;
}
- grid.innerHTML = coins.map(coinCard).join('');
- grid.querySelectorAll('.coin').forEach((el) => el.addEventListener('click', () => openCoin(el.dataset.mint)));
+ grid.innerHTML = '';
+ coins.forEach((c) => grid.appendChild(coinCard(c)));
}
function walletRow(w, i) {
diff --git a/src/oracle.js b/src/oracle.js
index a35f40e43..493db9d58 100644
--- a/src/oracle.js
+++ b/src/oracle.js
@@ -45,6 +45,14 @@ function ago(ts) {
}
function solscan(addr) { return `https://solscan.io/account/${addr}`; }
function pumpUrl(mint) { return `https://pump.fun/coin/${mint}`; }
+function tweetConviction(c) {
+ const tier = c.tier || 'watch';
+ const score = c.score ?? '—';
+ const symbol = c.symbol || '—';
+ const oracleUrl = `https://three.ws/oracle?mint=${encodeURIComponent(c.mint)}`;
+ const text = `$${symbol} — ${score}/100 ${tier} conviction on @trythreews Oracle\n\nWho · How · What · Move all fused into one score.\n${oracleUrl}`;
+ return `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}`;
+}
const CATEGORIES = ['meme', 'tech', 'ai', 'culture', 'community', 'political', 'news', 'animal', 'celebrity', 'utility', 'unknown'];
const ARCH_TITLE = {
@@ -353,38 +361,85 @@ function walletRow(w, i) {
// ── edge (backtest) ──────────────────────────────────────────────────────────
let _backtest = null;
-function cacheBacktest(bt) { _backtest = bt; if ($('#edgeWrap').dataset.loaded) renderEdge(); }
+function cacheBacktest(bt) {
+ // Normalize old { tier, scored, resolved, grad_rate, avg_ath_multiple } rows
+ // into the richer format from /api/oracle/backtest if the feed returns both.
+ if (!_backtest && Array.isArray(bt)) _backtest = { by_tier: bt, aggregate: null, top_performers: [] };
+ if ($('#edgeWrap').dataset.loaded) renderEdge();
+}
async function loadEdge() {
const wrap = $('#edgeWrap');
wrap.dataset.loaded = '1';
- if (!_backtest) {
- const { data } = await api(`/api/oracle/feed?network=${NETWORK}&limit=1`);
- _backtest = data?.backtest || [];
+ wrap.innerHTML = '<div class="state">Loading performance data…</div>';
+ const { ok, data } = await api(`/api/oracle/backtest?period=30d&network=${NETWORK}`);
+ if (ok && data) {
+ _backtest = data;
+ } else if (!_backtest) {
+ // Fallback: try to get the old format from the feed
+ const { data: feed } = await api(`/api/oracle/feed?network=${NETWORK}&limit=1`);
+ if (feed?.backtest) _backtest = { by_tier: feed.backtest, aggregate: null, top_performers: [] };
}
renderEdge();
}
function renderEdge() {
const wrap = $('#edgeWrap');
- const rows = (_backtest || []).filter((r) => r.scored > 0);
+ const bt = _backtest;
+ const tiers = bt?.by_tier || [];
+ const rows = tiers.filter((r) => (r.total || r.scored || 0) > 0);
+
if (!rows.length) {
- wrap.innerHTML = `<div class="state"><b>The edge is still proving itself</b>Win-rate by tier appears once Oracle has scored coins that have since resolved to an outcome (graduated or not). This is intentionally honest — no backfilled numbers.</div>`;
+ wrap.innerHTML = `<div class="state"><b>The edge is still proving itself.</b> Win-rate by tier appears once Oracle has scored coins that have since resolved to an outcome. This is intentionally honest — no backfilled numbers.</div>`;
return;
}
+
+ const agg = bt?.aggregate;
+ const aggLine = agg && agg.total > 0 ? `
+ <div class="edge-agg">
+ <div class="edge-kpi"><span>Total scored</span><b>${agg.total}</b></div>
+ <div class="edge-kpi"><span>Win rate</span><b class="${(agg.win_rate||0) >= 50 ? 'up' : 'dn'}">${agg.win_rate != null ? agg.win_rate + '%' : '—'}</b></div>
+ <div class="edge-kpi"><span>Wins</span><b class="up">${agg.wins}</b></div>
+ <div class="edge-kpi"><span>Losses</span><b class="dn">${agg.losses}</b></div>
+ <div class="edge-kpi"><span>Graduated</span><b>${agg.graduated}</b></div>
+ <div class="edge-kpi"><span>Rugged</span><b>${agg.rugged}</b></div>
+ <div class="edge-kpi"><span>≥ 5×</span><b>${agg.five_x}</b></div>
+ <div class="edge-kpi"><span>≥ 10×</span><b>${agg.ten_x}</b></div>
+ </div>` : '';
+
+ const top = bt?.top_performers?.slice(0, 5) || [];
+ const topHtml = top.length ? `
+ <div class="dr-sec" style="margin-top:20px">Top performers (30d by ATH)</div>
+ <div class="edge-top">
+ ${top.map((t) => `<a class="edge-top-row" href="https://pump.fun/coin/${esc(t.mint)}" target="_blank" rel="noopener">
+ <span class="tierpill ${tierPill(t.tier)}">${esc(t.tier)}</span>
+ <b>${esc(t.symbol || t.mint.slice(0, 6))}</b>
+ <span class="edge-ath">${t.ath_multiple ? Number(t.ath_multiple).toFixed(1) + '×' : t.graduated ? '✓ grad' : '—'}</span>
+ </a>`).join('')}
+ </div>` : '';
+
wrap.innerHTML = `
- <div class="ehead"><span>Tier</span><span>Graduation rate</span><span class="colhide">Resolved</span><span>Avg ATH×</span><span>Scored</span></div>
- ${rows.map(edgeRow).join('')}`;
+ ${aggLine}
+ <div class="ehead" style="margin-top:${agg ? '20px' : '0'}"><span>Tier</span><span>Win rate</span><span class="colhide">Wins / Losses</span><span>Avg ATH×</span><span>≥ 5×</span></div>
+ ${rows.map(edgeRow).join('')}
+ ${topHtml}
+ <p style="font-size:11px;color:var(--faint);margin-top:18px">Win = graduated OR ATH ≥ 2×. Loss = rugged OR ATH &lt; 1.2×. Open positions excluded. 30-day window.</p>`;
}
function edgeRow(r) {
- const grad = r.grad_rate ?? 0;
+ // Support both old format (grad_rate, scored) and new format (win_rate, total, wins, losses)
+ const winRate = r.win_rate ?? r.grad_rate ?? null;
+ const total = r.total || r.scored || 0;
+ const wins = r.wins ?? 0;
+ const losses = r.losses ?? 0;
+ const ath = r.avg_ath ? Number(r.avg_ath).toFixed(1) : (r.avg_ath_multiple ? Number(r.avg_ath_multiple).toFixed(1) : null);
+ const fiveX = r.five_x ?? 0;
return `<div class="erow">
<span><span class="tierpill ${tierPill(r.tier)}">${esc(r.tier)}</span></span>
- <span><div class="gradbar"><i style="width:${grad}%"></i></div><span class="lstat" style="text-align:left"><b>${r.grad_rate == null ? '—' : grad + '%'}</b></span></span>
- <span class="lstat colhide">${r.resolved}</span>
- <span class="lstat"><b>${r.avg_ath_multiple ? r.avg_ath_multiple.toFixed(1) + '×' : '—'}</b></span>
- <span class="lstat">${r.scored}</span>
+ <span><div class="gradbar"><i style="width:${winRate ?? 0}%"></i></div><span class="lstat" style="text-align:left"><b>${winRate != null ? winRate + '%' : '—'}</b></span></span>
+ <span class="lstat colhide">${wins} / ${losses}</span>
+ <span class="lstat"><b>${ath ? ath + '×' : '—'}</b></span>
+ <span class="lstat">${fiveX}</span>
</div>`;
}
@@ -471,9 +526,11 @@ function renderDrawer(d) {
${pillar('mom', 'Move', p.momentum)}
</div>
</div>
- <div style="display:flex;gap:14px;margin:14px 0 2px">
- <a class="solscan" href="${pumpUrl(c.mint)}" target="_blank" rel="noopener">pump.fun ↗</a>
- <a class="solscan" href="${solscan(c.mint)}" target="_blank" rel="noopener">solscan ↗</a>
+ <div class="dr-actions">
+ <a class="dr-act" href="${pumpUrl(c.mint)}" target="_blank" rel="noopener">pump.fun ↗</a>
+ <a class="dr-act" href="${solscan(c.mint)}" target="_blank" rel="noopener">solscan ↗</a>
+ <button class="dr-act dr-watch" id="drWatch" data-mint="${esc(c.mint)}" type="button" aria-pressed="${watchedMints().has(c.mint)}">${watchedMints().has(c.mint) ? '★ Watching' : '☆ Watch'}</button>
+ <a class="dr-act dr-share" href="${tweetConviction(c)}" target="_blank" rel="noopener" title="Share conviction on X">Share ↗</a>
${c.structure_cap != null && c.structure_cap < 60 ? `<span class="note warn">structural cap ${c.structure_cap}</span>` : ''}
</div>
${narr ? `<div class="dr-sec">Narrative</div><div style="font-size:13.5px;color:var(--ink)">${esc(narr.narrative || '')}</div>
@@ -501,6 +558,25 @@ function renderDrawer(d) {
if (tapeEl) tapeEl.innerHTML = '<div class="state" style="padding:16px 0">Trade feed unavailable.</div>';
});
}
+
+ // Watch toggle
+ const watchBtn = $('#drWatch');
+ if (watchBtn) {
+ watchBtn.addEventListener('click', () => {
+ toggleOracleWatch(c.mint);
+ const now = watchedMints().has(c.mint);
+ watchBtn.textContent = now ? '★ Watching' : '☆ Watch';
+ watchBtn.setAttribute('aria-pressed', String(now));
+ // Reflect on the coin card in the feed grid if visible.
+ const cardEl = document.querySelector(`#feedGrid .coin[data-mint="${CSS.escape(c.mint)}"]`);
+ const cardWatchBtn = cardEl?.querySelector('.oc-watch');
+ if (cardWatchBtn) {
+ cardWatchBtn.textContent = now ? '★' : '☆';
+ cardWatchBtn.classList.toggle('oc-watched', now);
+ cardWatchBtn.setAttribute('aria-pressed', String(now));
+ }
+ });
+ }
}
function whoRow(w) {
diff --git a/vercel.json b/vercel.json
index adc1bf6a1..199b19df6 100644
--- a/vercel.json
+++ b/vercel.json
@@ -175,6 +175,10 @@
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 30
},
+ "api/oracle/backtest.js": {
+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
+ "maxDuration": 30
+ },
"api/copy/executions.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 30
@@ -1809,6 +1813,10 @@
"src": "/api/oracle/social",
"dest": "/api/oracle/social.js"
},
+ {
+ "src": "/api/oracle/backtest",
+ "dest": "/api/oracle/backtest.js"
+ },
{
"src": "/api/copy/executions",
"dest": "/api/copy/executions.js"
diff --git a/workers/oracle/settle-loop.js b/workers/oracle/settle-loop.js
index 2d7b83c99..a4b301869 100644
--- a/workers/oracle/settle-loop.js
+++ b/workers/oracle/settle-loop.js
@@ -8,14 +8,18 @@
import { sql } from '../../api/_lib/db.js';
import { log } from './log.js';
import { gradeAction } from '../../api/_lib/oracle/settle.js';
+import { alertProfitableExit } from '../../api/_lib/oracle/alerts.js';
/** Open actions whose coin now has a resolved outcome. */
async function settleableActions(cfg, limit = 100) {
return sql`
- select a.id, a.size_sol, a.entry_mc_usd,
+ select a.id, a.agent_id, a.size_sol, a.entry_mc_usd,
+ a.symbol, a.conviction, a.tier, a.mode, a.mint,
+ ai.name as agent_name,
o.graduated, o.rugged, o.ath_multiple, o.last_market_cap_usd
from oracle_watch_actions a
join pump_coin_outcomes o on o.mint = a.mint
+ left join agent_identities ai on ai.id = a.agent_id
where a.network = ${cfg.network}
and (a.outcome is null or a.outcome = 'open')
and (o.graduated is true or o.rugged is true or o.ath_multiple is not null or o.last_market_cap_usd is not null)
@@ -28,6 +32,7 @@ export async function runSettlePass(cfg) {
const rows = await settleableActions(cfg);
if (!rows.length) return 0;
let settled = 0;
+ const wins = [];
for (const r of rows) {
const g = gradeAction(
{ size_sol: r.size_sol, entry_mc_usd: r.entry_mc_usd },
@@ -42,10 +47,26 @@ export async function runSettlePass(cfg) {
where id = ${r.id}
`;
settled += 1;
+ if (g.outcome === 'win') {
+ wins.push({
+ agent_id: r.agent_id,
+ agent_name: r.agent_name,
+ mint: r.mint,
+ symbol: r.symbol,
+ tier: r.tier,
+ conviction: r.conviction,
+ mode: r.mode,
+ size_sol: r.size_sol,
+ realized_pnl_sol: g.realized_pnl_sol,
+ peak_multiple: g.peak_multiple,
+ network: cfg.network,
+ });
+ }
} catch (e) {
log.warn(`settle action ${r.id} failed:`, e.message);
}
}
- if (settled) log.info(`settled ${settled} action(s)`);
+ if (settled) log.info(`settled ${settled} action(s)${wins.length ? `, ${wins.length} win(s)` : ''}`);
+ if (wins.length) alertProfitableExit(wins).catch(() => {});
return settled;
}