signaltrail / tree / src/judge.js · raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
// Bull / Bear / Judge over the SAME recorded evidence. Pure function: replaying a receipt's evidence reproduces its decision.
// (Advocate + reviewer pattern adapted from the swarm's golden-kog-risk-debate, which credits TauricResearch/TradingAgents, Apache-2.0; made deterministic here.)
const r2 = (x) => Math.round(x * 100) / 100;
export function judge(ev, risk) {
  const { narrative: n, screen, price, portfolio, excluded_posts = [] } = ev;
  const bull = [], bear = [], vetoes = [];
  if (n.converged) bull.push(n.why); else vetoes.push('no_convergence: ' + n.why);
  if (n.voices.bullish.length) bull.push(`bullish voices: ${n.voices.bullish.join(', ')} (narrative: ${n.narrative})`);
  if (n.voices.bearish.length) bear.push(`bearish voices: ${n.voices.bearish.join(', ')}`);
  if (n.avg_conviction >= 0.35) bull.push(`average conviction ${n.avg_conviction}`);
  if (n.avg_urgency >= risk.fomo_urgency) bear.push(`urgency ${n.avg_urgency} ≥ ${risk.fomo_urgency}: hype pattern, size halved`);
  if (n.narrative === 'pump-hype') bear.push('narrative is pump-hype language (100x / gem / guaranteed)');
  const mine = excluded_posts.filter((x) => (x.mentions || []).includes(n.symbol));
  if (mine.length) bear.push(`${mine.length} post(s) about ${n.symbol} excluded as manipulation (InjectScan): ${mine.map((x) => x.post_id + ' by ' + x.author).join(', ')}`);
  // safety screen (fail-closed). Only converged candidates are screened; others are already vetoed.
  if (!n.converged) { /* screens not run: nothing to trade */ }
  else if (!screen || screen.status !== 'ok') vetoes.push(`screen_unavailable: TokenVerdict ${screen?.error || 'missing'} (fail-closed: no trade without a safety check)`);
  else {
    const s = screen.result;
    const txt = `TokenVerdict ${s.verdict} (score ${s.score}, liquidity $${Math.round(s.liquidity_usd || 0).toLocaleString('en-US')}, sellable ${s.sellable})`;
    if (s.verdict === 'SAFE') bull.push(txt); else bear.push(txt);
    if (!risk.allowed_verdicts.includes(s.verdict)) vetoes.push(`token_unsafe: ${txt}; policy allows ${risk.allowed_verdicts.join('/')}`);
    if (s.sellable === false) vetoes.push('not_sellable: simulated sell failed (honeypot signal)');
    if ((s.liquidity_usd || 0) < risk.min_liquidity_usd) vetoes.push(`low_liquidity: $${Math.round(s.liquidity_usd || 0)} < $${risk.min_liquidity_usd}`);
  }
  if (n.converged && (!price || price.status !== 'ok' || !(price.price_usd > 0))) vetoes.push('no_price: no reliable paper fill price (fail-closed)');
  if (portfolio.open_symbols.includes(n.symbol)) vetoes.push(`already_open: a practice position in ${n.symbol} is already open`);
  if (portfolio.open_count >= risk.max_open_positions) vetoes.push(`max_open_positions: ${portfolio.open_count}/${risk.max_open_positions}`);
  // sizing (only matters if no veto)
  let size = Math.min(risk.max_position_usd, r2(portfolio.equity_usd * risk.max_position_pct / 100));
  size = r2(size * (0.5 + 0.5 * Math.min(1, n.avg_conviction / 0.7)));
  if (n.avg_urgency >= risk.fomo_urgency) size = r2(size / 2);
  size = Math.min(size, portfolio.cash_usd);
  if (!vetoes.length && size < risk.min_position_usd) vetoes.push(`size_too_small: $${size}`);
  const open = vetoes.length === 0;
  const p = price?.price_usd;
  return {
    action: open ? 'OPEN_PRACTICE_LONG' : 'SKIP',
    symbol: n.symbol,
    bull_case: bull, bear_case: bear, vetoes,
    verdict: open ? `OPEN practice long ${n.symbol}: $${size} at $${p} (paper)` : `SKIP ${n.symbol}: ${vetoes[0].split(':')[0]}`,
    position: open ? { side: 'long', size_usd: size, entry_price_usd: p, qty: Number((size / p).toPrecision(8)), stop_price_usd: Number((p * (1 - risk.stop_loss_pct / 100)).toPrecision(6)), take_profit_price_usd: Number((p * (1 + risk.take_profit_pct / 100)).toPrecision(6)), max_hold_hours: risk.max_hold_hours } : null,
  };
}
// exit rule for an open practice position, given a fresh price
export function exitCheck(pos, priceUsd, nowIso) {
  const age = (Date.parse(nowIso) - Date.parse(pos.opened_at)) / 3600e3;
  if (priceUsd <= pos.stop_price_usd) return { exit: true, reason: `stop: ${priceUsd} ≤ ${pos.stop_price_usd}` };
  if (priceUsd >= pos.take_profit_price_usd) return { exit: true, reason: `take_profit: ${priceUsd} ≥ ${pos.take_profit_price_usd}` };
  if (age >= pos.max_hold_hours) return { exit: true, reason: `max_hold: ${age.toFixed(1)}h ≥ ${pos.max_hold_hours}h` };
  return { exit: false, reason: `hold: price ${priceUsd}, stop ${pos.stop_price_usd}, target ${pos.take_profit_price_usd}, age ${age.toFixed(1)}h` };
}

agentgate-source: code mirror on Cloudflare Pages. All repos