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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(orders): add trail_ratchet two-phase exits and stable DAILY_LOSS/DRAWDOWN/IMPACT/TIER_LOCK reason codes
nirholas592273a4e715
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 66dbd2f86..509040412 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -435,7 +435,7 @@ surface-map row already covers:| [workers/agent-anchor/](workers/agent-anchor) | Newsroom Anchor worker: turns market intel into anchor-read segments || [workers/agent-forge/](workers/agent-forge) | Headless Live Avatar Forge caster: forges on a free lane and broadcasts the GLB onto an agent's live screen. Operator-run CLI, not a deployed service || [workers/agent-mm/](workers/agent-mm) | Launch Copilot market-maker engine (rules-based) |-| [workers/agent-orders/](workers/agent-orders) | Programmable Orders Engine: limit / stop / trailing / DCA / TWAP / conditional orders swept against live quotes and fired through the audited agent-trade path. Built and tested, not deployed as a Cloud Run service yet, so orders stay `active` until it runs |+| [workers/agent-orders/](workers/agent-orders) | Programmable Orders Engine: limit / stop / trailing / DCA / TWAP / conditional orders swept against live quotes and fired through the audited agent-trade path. Includes the `trail_ratchet` two-phase stop and stable exit reason codes. Cloud Run deploy is one command (`workers/agent-orders/README.md`), owner-gated, so orders stay `active` until it runs || [workers/agent-screen-worker/](workers/agent-screen-worker) | Stagehand-driven real browser worker behind the agent screen cast || [workers/avatar-pipeline-controller/](workers/avatar-pipeline-controller) | FastAPI CPU orchestrator behind Scan-yourself-to-3D (multi-backend lane; not deployed today, `GCP_RECONSTRUCTION_URL` points at `avatar-reconstruction`) || [workers/deploy/](workers/deploy) | Cloud Run deploy runbook for the selfie-to-3D pipeline |diff --git a/api/_lib/exit-ratchet.js b/api/_lib/exit-ratchet.jsnew file mode 100644index 000000000..eecddd0d0--- /dev/null+++ b/api/_lib/exit-ratchet.js@@ -0,0 +1,103 @@+/**+ * Two-phase ratcheting trailing stop and the stable reason codes for exits and+ * refusals (order engine, lane D).+ *+ * Phase 1 is a wide fixed stop below the entry (`initialStopPct`): the position+ * gets room to breathe. Each lock tier `{ profit_pct, lock_pct }` arms once the+ * high-water mark has shown `profit_pct` of profit over the entry, and from then+ * on the stop never falls below `entry * (1 + lock_pct / 100)`. The stop only+ * ever ratchets up: the high-water mark is monotonic, so a tier, once reached,+ * stays reached even when price falls back under the tier's trigger level.+ *+ * Everything here is pure (no I/O) so the sweep worker, the HTTP preview and the+ * tests share one answer.+ */++/** Stable codes carried by every refusal or exit. Never rename a code. */+export const REASON_CODES = Object.freeze({+ DAILY_LOSS: 'Daily loss limit reached',+ DRAWDOWN: 'Fell through the initial stop',+ IMPACT: 'Price impact above the safety limit',+ TIER_LOCK: 'Fell back to a locked-in profit tier',+});++const GUARD_TO_REASON = new Map([+ ['daily_loss_limit', 'DAILY_LOSS'],+ ['price_impact', 'IMPACT'],+ ['price_impact_too_high', 'IMPACT'],+]);++/** The stable code for a guard reason (executor / guard vocabulary), or null. */+export function reasonCodeForGuard(reason) {+ return GUARD_TO_REASON.get(String(reason || '')) || null;+}++export const MAX_RATCHET_TIERS = 8;++const finite = (v) => (v === '' || v == null ? null : Number.isFinite(Number(v)) ? Number(v) : null);++/**+ * Validate a ratchet spec. Tiers must strictly ascend in profit_pct and lock_pct,+ * and every lock must sit below the profit that arms it (a lock at or above its+ * own trigger would sell instantly).+ * @returns {{ ok: true, ratchet: { initial_stop_pct: number, tiers: Array<{profit_pct:number, lock_pct:number}> } } | { ok: false, message: string }}+ */+export function normalizeRatchet(raw) {+ if (!raw || typeof raw !== 'object') return { ok: false, message: 'ratchet { initial_stop_pct, tiers } is required' };+ const initial = finite(raw.initial_stop_pct);+ if (initial == null || initial <= 0 || initial >= 100) {+ return { ok: false, message: 'ratchet.initial_stop_pct must be between 0 and 100' };+ }+ if (!Array.isArray(raw.tiers) || raw.tiers.length < 1) return { ok: false, message: 'ratchet.tiers needs at least one tier' };+ if (raw.tiers.length > MAX_RATCHET_TIERS) return { ok: false, message: `ratchet.tiers may have at most ${MAX_RATCHET_TIERS} tiers` };+ const tiers = [];+ for (const t of raw.tiers) {+ const profit = finite(t?.profit_pct);+ const lock = finite(t?.lock_pct);+ if (profit == null || profit <= 0) return { ok: false, message: 'every tier needs a profit_pct above 0' };+ if (lock == null || lock < -initial) return { ok: false, message: `every tier needs a lock_pct of at least -${initial}` };+ if (lock >= profit) return { ok: false, message: 'a tier lock_pct must be below its profit_pct' };+ const prev = tiers[tiers.length - 1];+ if (prev && (profit <= prev.profit_pct || lock <= prev.lock_pct)) {+ return { ok: false, message: 'tiers must ascend: each profit_pct and lock_pct above the previous tier' };+ }+ tiers.push({ profit_pct: profit, lock_pct: lock });+ }+ return { ok: true, ratchet: { initial_stop_pct: initial, tiers } };+}++/**+ * Where the stop sits and why.+ * @param {{ entry: number, peak: number, ratchet: { initial_stop_pct: number, tiers: Array<{profit_pct:number, lock_pct:number}> } }} p+ * @returns {{ stop: number, phase: 1|2, tier: number|null, code: 'DRAWDOWN'|'TIER_LOCK' }}+ */+export function ratchetStop({ entry, peak, ratchet }) {+ const e = Number(entry);+ const hwm = Math.max(Number(peak) || 0, e);+ const initialStop = e * (1 - ratchet.initial_stop_pct / 100);+ let stop = initialStop;+ let tier = null;+ ratchet.tiers.forEach((t, i) => {+ if (hwm >= e * (1 + t.profit_pct / 100)) {+ const floor = e * (1 + t.lock_pct / 100);+ if (floor > stop) { stop = floor; tier = i; }+ }+ });+ return tier == null+ ? { stop, phase: 1, tier: null, code: 'DRAWDOWN' }+ : { stop, phase: 2, tier, code: 'TIER_LOCK' };+}++/**+ * Decide an exit at the observed `value`. A gap straight through a lock tier+ * still fires (the test is `value <= stop`, not equality), at the first value the+ * sweep sees, which is the best fill the engine can honestly promise.+ * @returns {{ fire: boolean, code: 'DRAWDOWN'|'TIER_LOCK'|null, stop: number, phase: 1|2, tier: number|null }}+ */+export function evaluateRatchet({ entry, peak, value, ratchet }) {+ const e = Number(entry);+ const v = Number(value);+ if (!(e > 0) || !Number.isFinite(v)) return { fire: false, code: null, stop: NaN, phase: 1, tier: null };+ const s = ratchetStop({ entry: e, peak: Math.max(Number(peak) || 0, v), ratchet });+ return v <= s.stop ? { fire: true, ...s } : { fire: false, code: null, stop: s.stop, phase: s.phase, tier: s.tier };+}diff --git a/api/_lib/migrations/20261023210000_orders_trail_ratchet.sql b/api/_lib/migrations/20261023210000_orders_trail_ratchet.sqlnew file mode 100644index 000000000..eb16c3618--- /dev/null+++ b/api/_lib/migrations/20261023210000_orders_trail_ratchet.sql@@ -0,0 +1,8 @@+-- Two-phase ratcheting trailing stop (order type 'trail_ratchet').+-- ratchet holds { initial_stop_pct, tiers: [{ profit_pct, lock_pct }] }. The entry+-- price is orders.reference_price and the high-water mark is orders.peak_price.+ALTER TABLE orders ADD COLUMN IF NOT EXISTS ratchet JSONB;++ALTER TABLE orders DROP CONSTRAINT IF EXISTS orders_type_check;+ALTER TABLE orders ADD CONSTRAINT orders_type_check+ CHECK (type IN ('limit','stop','trailing','trail_ratchet','dca','twap','conditional'));diff --git a/api/_lib/order-book.js b/api/_lib/order-book.jsindex cbb0a4e80..bd32b2c7e 100644--- a/api/_lib/order-book.js+++ b/api/_lib/order-book.js@@ -31,7 +31,7 @@ const CODE_MAP = new Map([['kill_switch', 'kill_switch'], ['trading_paused', 'kill_switch'], ['wallet_anomaly_frozen', 'kill_switch'],['orders_global_kill', 'kill_switch'],// Spend policy: per-trade cap, daily budget, USD ceilings, position limits.- ['per_trade_cap', 'cap_hit'], ['daily_budget', 'cap_hit'], ['daily_exceeded', 'cap_hit'],+ ['per_trade_cap', 'cap_hit'], ['daily_loss_limit', 'cap_hit'], ['daily_budget', 'cap_hit'], ['daily_exceeded', 'cap_hit'],['daily_budget_exceeded', 'cap_hit'], ['per_tx_exceeded', 'cap_hit'], ['max_positions', 'cap_hit'],['spend_limit', 'cap_hit'], ['capability_required', 'cap_hit'], ['policy_unavailable', 'cap_hit'],['policy_blocked', 'cap_hit'],@@ -98,6 +98,10 @@ export function nextFire(o) {if (o.type === 'trailing') {return { at: null, label: o.side === 'sell' ? `After a ${o.trail_pct}% drop from the high` : `After a ${o.trail_pct}% bounce from the low` };}+ if (o.type === 'trail_ratchet') {+ const first = o.ratchet?.tiers?.[0];+ return { at: null, label: `Below ${o.ratchet?.initial_stop_pct}% under entry${first ? `, then locking profit from +${first.profit_pct}%` : ''}` };+ }const dir = (o.type === 'limit') === (o.side === 'buy') ? 'at or below' : 'at or above';return { at: null, label: `When ${o.trigger_metric} is ${dir} ${target}` };}diff --git a/api/_lib/orders.js b/api/_lib/orders.jsindex f3507d9cb..ac395dd09 100644--- a/api/_lib/orders.js+++ b/api/_lib/orders.js@@ -12,6 +12,8 @@* limit — fill at a target price/market-cap (buy on a dip, sell on a rise)* stop — fill when a level is breached (stop-loss sell / breakout buy)* trailing — fill on a % drawdown from the high-water mark (or run-up from the low)+ * trail_ratchet: sell-only two-phase stop: a wide initial stop, then lock tiers that+ * ratchet the floor up as profit grows (api/_lib/exit-ratchet.js)* dca — recurring buys/sells on a fixed interval, N slices* twap — slice ONE large order over time to cut price impact, N slices* conditional — fill when a validated signal condition is true@@ -22,8 +24,9 @@import { randomUUID } from 'node:crypto';import { validateSolanaAddress } from './agent-trade-guards.js';import { sql, sqlValues } from './db.js';+import { normalizeRatchet } from './exit-ratchet.js';-export const ORDER_TYPES = Object.freeze(['limit', 'stop', 'trailing', 'dca', 'twap', 'conditional']);+export const ORDER_TYPES = Object.freeze(['limit', 'stop', 'trailing', 'trail_ratchet', 'dca', 'twap', 'conditional']);export const ORDER_SIDES = Object.freeze(['buy', 'sell']);export const TRIGGER_METRICS = Object.freeze(['price_sol', 'mcap_sol', 'mcap_usd']);// Where an order may fill. 'launchpad' = the pump bonding curve, then the@@ -262,7 +265,7 @@ export function normalizeOrder(raw) {network, venue, price_band,slippage_bps, max_price_impact_pct, expires_at: expires_at || null,trigger_metric,- limit_price: null, stop_price: null, trail_pct: null,+ limit_price: null, stop_price: null, trail_pct: null, ratchet: null, entry_price: null,schedule: null, condition: null,size_sol: null, size_tokens: null, sell_pct: null,};@@ -286,6 +289,16 @@ export function normalizeOrder(raw) {const v = num(raw.trail_pct);if (v == null || v <= 0 || v >= 100) return err('invalid_trail', 'trail_pct must be between 0 and 100');out.trail_pct = v;+ } else if (type === 'trail_ratchet') {+ if (side !== 'sell') return err('invalid_side', 'a ratcheting stop protects a position, so side must be "sell"');+ const r = normalizeRatchet(raw.ratchet);+ if (!r.ok) return err('invalid_ratchet', r.message);+ out.ratchet = r.ratchet;+ if (raw.entry_price != null && raw.entry_price !== '') {+ const e = posNum(raw.entry_price);+ if (!e) return err('invalid_price', 'entry_price must be a positive number in the trigger metric');+ out.entry_price = e;+ }} else if (type === 'dca') {const sch = parseSchedule(raw.schedule, { minInterval: 60, minSlices: 1 });if (!sch.ok) return sch;@@ -482,6 +495,11 @@ export function describeOrder(o) {return o.side === 'sell'? `Trailing stop: sell ${sizeLabel(o)} of ${sym} after a ${o.trail_pct}% drop from its high.`: `Trailing entry: buy ${sizeLabel(o)} of ${sym} after a ${o.trail_pct}% bounce from its low.`;+ case 'trail_ratchet': {+ const r = o.ratchet || { tiers: [] };+ const tiers = r.tiers.map((t) => `at +${t.profit_pct}% lock ${t.lock_pct >= 0 ? '+' : ''}${t.lock_pct}%`).join(', ');+ return `Ratcheting stop: sell ${sizeLabel(o)} of ${sym} if it falls ${r.initial_stop_pct}% below entry; then ${tiers}, and the stop never moves down.`;+ }case 'dca': {const every = humanInterval(o.schedule?.interval_seconds);return `DCA: ${verb.toLowerCase()} ${sizeLabel(o)} of ${sym} every ${every}, ${o.schedule?.slices}× total${bandLabel(o.price_band)}.`;@@ -536,7 +554,7 @@ export function shapeOrder(row) {size_sol: numOrNull(row.size_sol), size_tokens: numOrNull(row.size_tokens), sell_pct: numOrNull(row.sell_pct),trigger_metric: row.trigger_metric,limit_price: numOrNull(row.limit_price), stop_price: numOrNull(row.stop_price),- trail_pct: numOrNull(row.trail_pct), peak_price: numOrNull(row.peak_price),+ trail_pct: numOrNull(row.trail_pct), ratchet: row.ratchet || null, peak_price: numOrNull(row.peak_price),reference_price: numOrNull(row.reference_price),schedule: row.schedule || null, next_fire_at: row.next_fire_at, condition: row.condition || null,slippage_bps: row.slippage_bps, max_price_impact_pct: numOrNull(row.max_price_impact_pct),@@ -629,7 +647,7 @@ const orderInsertColumns = () => sql`agent_id, user_id, network, mint, symbol, type, side, size_sol, size_tokens,sell_pct, trigger_metric, limit_price, stop_price, trail_pct, schedule,next_fire_at, condition, slippage_bps, max_price_impact_pct, expires_at, status,- venue, route, price_band, group_id, group_kind, group_leg`;+ venue, route, price_band, group_id, group_kind, group_leg, ratchet, reference_price`;// One VALUES row for orderInsertColumns(). Schedule-driven orders (dca/twap)// get next_fire_at = now so the first slice fires on the next sweep.@@ -646,6 +664,8 @@ function orderInsertRow(agentId, userId, o, { route = null, group = null } = {})o.venue || 'auto', route,sql`${o.price_band ? JSON.stringify(o.price_band) : null}::jsonb`,group ? sql`${group.id}::uuid` : null, group?.kind ?? null, group?.leg ?? null,+ sql`${o.ratchet ? JSON.stringify(o.ratchet) : null}::jsonb`,+ o.entry_price ?? null,];}diff --git a/api/_mcpagent/orders-tools.js b/api/_mcpagent/orders-tools.jsindex ce5027abf..1f7dea427 100644--- a/api/_mcpagent/orders-tools.js+++ b/api/_mcpagent/orders-tools.js@@ -469,7 +469,7 @@ export const orderToolDefs = [agent_id: agentIdProp,network: { type: 'string', enum: ['mainnet', 'devnet'], description: 'Limit to one cluster. Both when omitted.' },status: { type: 'string', enum: ['open', 'closed', 'all'], default: 'open' },- type: { type: 'string', enum: ['limit', 'stop', 'trailing', 'dca', 'twap', 'conditional'] },+ type: { type: 'string', enum: ['limit', 'stop', 'trailing', 'trail_ratchet', 'dca', 'twap', 'conditional'] },limit: { type: 'integer', minimum: 1, maximum: 200, default: 50 },},required: ['agent_id'],diff --git a/api/agents/orders.js b/api/agents/orders.jsindex 83c67b7e2..511303ead 100644--- a/api/agents/orders.js+++ b/api/agents/orders.js@@ -33,6 +33,7 @@ import { sql } from '../_lib/db.js';import { getSolanaAddressBalances } from '../_lib/agent-wallet.js';import { getSpendLimits, getTradeLimits } from '../_lib/agent-trade-guards.js';import { getPumpTradeClient } from '../_lib/pump.js';+import { evaluateRatchet, REASON_CODES } from '../_lib/exit-ratchet.js';import { assessTradeSafety } from '../_lib/trade-firewall.js';import { PublicKey } from '@solana/web3.js';import {@@ -144,6 +145,7 @@ async function handleSchema(req, res, id) {return json(res, 200, {data: {order_types: ORDER_TYPES,+ reason_codes: REASON_CODES,trigger_metrics: TRIGGER_METRICS,venues: ORDER_VENUES,group_kinds: GROUP_KINDS,@@ -367,7 +369,7 @@ async function liveContext(o, orders) {const need = new Set();for (const leg of orders) {if (leg.type === 'conditional') for (const k of conditionSignals(leg.condition)) need.add(k);- if (leg.type === 'trailing' || leg.type === 'conditional') need.add('mcap_usd');+ if (leg.type === 'trailing' || leg.type === 'trail_ratchet' || leg.type === 'conditional') need.add('mcap_usd');if (leg.price_band?.metric === 'mcap_usd') need.add('mcap_usd');}const venue = { requested: o.venue || 'auto', route: null, source: null };@@ -395,6 +397,9 @@ function previewFrom(o, { market, signals }) {preview.would_fire_now = r.fired; preview.missing = r.missing;} else if (o.type === 'limit' || o.type === 'stop') {preview.would_fire_now = shouldFirePrice(o, cur, cur);+ } else if (o.type === 'trail_ratchet') {+ const entry = o.reference_price ?? cur;+ preview.would_fire_now = evaluateRatchet({ entry, peak: entry, value: cur, ratchet: o.ratchet }).fire;} else if (o.type === 'trailing') {preview.would_fire_now = false; // needs a tracked high/low-water mark first} else if (o.type === 'dca' || o.type === 'twap') {diff --git a/data/changelog.json b/data/changelog.jsonindex 81a129140..acce22feb 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, 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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-23",+ "title": "Ratcheting exit orders with named reason codes",+ "summary": "Orders gain a trail_ratchet type: a wide initial stop that never moves down, then profit tiers that lock in gains (for example at +50% lock +10%, at +100% lock +50%), evaluated against the high-water mark so a gap down through a tier still sells. Every skipped or fired exit now carries a stable reason code (DAILY_LOSS, DRAWDOWN, IMPACT, TIER_LOCK) in the activity feed, the order events and the decision trail. The wallet hub Orders tab has a Ratchet form with an add-tier editor and shows the codes as chips.",+ "tags": [+ "feature"+ ],+ "link": "/dashboard"+ },{"date": "2026-10-23","title": "Splat video export now records every frame of the camera path",diff --git a/src/agent-wallet-hub/tabs/orders.js b/src/agent-wallet-hub/tabs/orders.jsindex cc3885388..c746d352a 100644--- a/src/agent-wallet-hub/tabs/orders.js+++ b/src/agent-wallet-hub/tabs/orders.js@@ -34,6 +34,7 @@ const TYPE_META = {limit: { icon: '🎯', label: 'Limit', blurb: 'Fill at a target price/market-cap.' },stop: { icon: '🛑', label: 'Stop', blurb: 'Stop-loss on a fall, or breakout on a rise.' },trailing: { icon: '📉', label: 'Trailing', blurb: 'Sell after a % drop from the high.' },+ trail_ratchet: { icon: '🔒', label: 'Ratchet', blurb: 'Wide stop first, then lock profit tiers that never loosen.' },ladder: { icon: '🪜', label: 'Ladder', blurb: 'Scale in or out across up to 10 levels.' },oco: { icon: '⚖️', label: 'OCO', blurb: 'Take-profit + stop; first fill cancels the other.' },dca: { icon: '🪙', label: 'DCA', blurb: 'Recurring buys/sells on an interval.' },@@ -129,6 +130,7 @@ const STYLE = `.aord-badge { font-size: var(--text-2xs,.6875rem); padding:1px 7px; border-radius: var(--radius-pill,999px); background: var(--wallet-accent-soft,rgba(139,92,246,.12)); color: var(--wallet-accent,#c4b5fd); font-weight:500; margin-left:6px; vertical-align:1px; }.aord-next { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#aaa); margin-top:6px; }.aord-skip { display:inline-flex; align-items:center; gap:5px; font-size: var(--text-2xs,.6875rem); padding:2px 9px; border-radius: var(--radius-pill,999px); color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 10%, transparent); border:1px solid color-mix(in srgb, var(--warn,#fbbf24) 35%, transparent); margin-top:6px; }+.aord-code { display:inline-block; font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-2xs,.6875rem); letter-spacing:.04em; padding:1px 6px; border-radius:5px; border:1px solid var(--line,rgba(255,255,255,.18)); color: var(--ink-dim,#aaa); vertical-align:middle; }.aord-legs { display:flex; flex-direction:column; gap:7px; margin-bottom:11px; }.aord-leg { display:flex; gap:7px; align-items:center; }.aord-leg .n { font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); width:22px; flex:none; }@@ -184,10 +186,25 @@ async function call(url, { method = 'GET', body = null } = {}) {}}+const REASON_LABEL = {+ DAILY_LOSS: 'Daily loss limit reached',+ DRAWDOWN: 'Fell through the initial stop',+ IMPACT: 'Price impact above the safety limit',+ TIER_LOCK: 'Fell back to a locked-in profit tier',+};++// The stable reason code on an exit or refusal, as a labelled chip.+function reasonChip(code) {+ if (!code || !REASON_LABEL[code]) return '';+ return ` <span class="aord-code" title="${esc(REASON_LABEL[code])}">${esc(code)}</span>`;+}+function freshForm() {return {type: 'limit', side: 'buy', mint: '', trigger_metric: 'mcap_usd',limit_price: '', stop_price: '', trail_pct: '25',+ ratchet_initial: '30', ratchet_entry: '',+ tiers: [{ profit: '50', lock: '10' }, { profit: '100', lock: '50' }],size_sol: '0.1', sell_pct: '100', size_tokens: '',total_sol: '1', total_pct: '100',interval: '3600', slices: '6', slippage_bps: '500', expires_at: '',@@ -342,7 +359,7 @@ registerWalletTab({<div class="aord-field"><label id="f-side-lbl">Side</label><div class="aord-seg" role="group" aria-labelledby="f-side-lbl">- <button type="button" data-side="buy" aria-pressed="${f.side === 'buy'}">Buy</button>+ <button type="button" data-side="buy" aria-pressed="${f.side === 'buy'}" ${f.type === 'trail_ratchet' ? 'disabled title="A ratcheting stop protects a position, so it sells only"' : ''}>Buy</button><button type="button" data-side="sell" aria-pressed="${f.side === 'sell'}">Sell</button></div></div>@@ -371,6 +388,7 @@ registerWalletTab({if (f.type === 'limit') return `<div class="aord-row">${metricSel('f-metric')}<div class="aord-field"><label for="f-limit_price">Target (${shortMetric(f.trigger_metric)})</label><input class="aord-input" id="f-limit_price" type="number" step="any" min="0" value="${esc(f.limit_price)}" placeholder="${f.side === 'buy' ? 'buy at or below' : 'sell at or above'}"/></div></div><div class="aord-row">${sizeField}</div>`;if (f.type === 'stop') return `<div class="aord-row">${metricSel('f-metric')}<div class="aord-field"><label for="f-stop_price">Stop (${shortMetric(f.trigger_metric)})</label><input class="aord-input" id="f-stop_price" type="number" step="any" min="0" value="${esc(f.stop_price)}" placeholder="${f.side === 'sell' ? 'sell if it falls to' : 'buy once it breaks'}"/></div></div><div class="aord-row">${sizeField}</div>`;if (f.type === 'trailing') return `<div class="aord-row">${metricSel('f-metric')}<div class="aord-field"><label for="f-trail_pct">Trail (%)</label><input class="aord-input" id="f-trail_pct" type="number" step="0.1" min="0.1" max="99" value="${esc(f.trail_pct)}"/></div></div><div class="aord-row">${sizeField}</div>`;+ if (f.type === 'trail_ratchet') return ratchetFields(f, metricSel, sizeField);if (f.type === 'dca') return `<div class="aord-row"><div class="aord-field"><label for="f-interval">Every</label>${intervalSelect(f)}</div><div class="aord-field"><label for="f-slices">Slices</label><input class="aord-input" id="f-slices" type="number" min="1" max="1000" value="${esc(f.slices)}"/></div></div><div class="aord-row">${sizeField}</div>${bandFields(f, metricSel)}`;if (f.type === 'ladder') return `<div class="aord-row">${metricSel('f-metric')}</div>${ladderFields(f)}`;if (f.type === 'oco') return ocoFields(f, metricSel, sizeField);@@ -395,6 +413,20 @@ registerWalletTab({<p class="aord-hint">Leave both blank to buy every slice at market. A slice that lands outside the band waits for the next interval.</p>`;}+ function ratchetFields(f, metricSel, sizeField) {+ const rows = f.tiers.map((t, i) => `<div class="aord-leg">+ <span class="n">${i + 1}</span>+ <input class="aord-input" data-ti="${i}" data-tf="profit" type="number" step="any" min="0" value="${esc(t.profit)}" placeholder="at profit (%)" aria-label="Tier ${i + 1} profit percent"/>+ <input class="aord-input" data-ti="${i}" data-tf="lock" type="number" step="any" value="${esc(t.lock)}" placeholder="lock (%)" aria-label="Tier ${i + 1} locked profit percent"/>+ <button type="button" class="x" data-trm="${i}" aria-label="Remove tier ${i + 1}" ${f.tiers.length <= 1 ? 'disabled' : ''}>✕</button>+ </div>`).join('');+ return `<div class="aord-row">${metricSel('f-metric')}<div class="aord-field"><label for="f-ratchet_initial">Initial stop (% below entry)</label><input class="aord-input" id="f-ratchet_initial" type="number" step="0.1" min="0.1" max="99" value="${esc(f.ratchet_initial)}"/></div></div>+ <div class="aord-row"><div class="aord-field"><label for="f-ratchet_entry">Entry (${shortMetric(f.trigger_metric)}, optional)</label><input class="aord-input" id="f-ratchet_entry" type="number" step="any" min="0" value="${esc(f.ratchet_entry)}" placeholder="blank = price when first checked"/></div>${sizeField}</div>+ <div class="aord-field"><label>Lock tiers (profit reached, profit locked)</label><div class="aord-legs">${rows}</div>+ <button type="button" class="aord-btn ghost sm" id="aord-add-tier" ${f.tiers.length >= 8 ? 'disabled' : ''}>+ Add tier</button></div>+ <p class="aord-hint">Sells if price falls ${esc(f.ratchet_initial || '?')}% below entry. Once a tier's profit is reached the stop never drops below its locked profit. Tiers must ascend. Sells only.</p>`;+ }+function ladderFields(f) {const max = state.schema?.max_ladder_legs || 10;const unit = shortMetric(f.trigger_metric);@@ -525,7 +557,7 @@ registerWalletTab({const next = open ? (state.book[o.id]?.next_fire || null) : null;const nextLine = next ? `<div class="aord-next">Next: ${esc(next.at ? `${relTime(next.at)} · ${new Date(next.at).toLocaleString()}` : next.label)}</div>` : '';const skipLine = open && o.last_skip_code- ? `<div class="aord-skip" title="${esc(o.last_skip_detail || '')}">⏸ ${esc(skipLabelFor(o.last_skip_code))}${o.skip_count > 1 ? ` · ${o.skip_count}×` : ''}${o.last_skip_at ? ` · ${esc(relTime(o.last_skip_at))}` : ''}</div>` : '';+ ? `<div class="aord-skip" title="${esc(o.last_skip_detail || '')}">⏸ ${esc(skipLabelFor(o.last_skip_code))}${reasonChip((String(o.last_skip_detail || '').match(/^\[([A-Z_]+)\]/) || [])[1])}${o.skip_count > 1 ? ` · ${o.skip_count}×` : ''}${o.last_skip_at ? ` · ${esc(relTime(o.last_skip_at))}` : ''}</div>` : '';const groupBadge = o.group_kind ? `<span class="aord-badge">${o.group_kind === 'oco' ? 'OCO' : 'Ladder'} · leg ${esc(o.group_leg)}</span>` : '';const ctl = OPEN_STATUSES.includes(o.status) ? `<div class="aord-item-ctl"><button type="button" class="aord-btn ghost sm" data-pause="${esc(o.id)}">${o.status === 'paused' ? 'Resume' : 'Pause'}</button>@@ -582,7 +614,7 @@ registerWalletTab({? `<ul class="aord-ev">${evs.map((e) => {const m = EVENT_META[e.kind] || { icon: '•', label: e.kind };const what = e.kind === 'skip' ? (e.label || skipLabelFor(e.code)) : e.kind === 'cancel' && e.code ? `${m.label} (${cancelReasonLabel(e.code)})` : m.label;- return `<li><span class="ic ${esc(e.kind)}" aria-hidden="true">${m.icon}</span><div class="body">${esc(what)} ${esc(symOf(e.order_id))}${e.detail ? `<small>${esc(String(e.detail).slice(0, 160))}</small>` : ''}</div><span class="t" title="${esc(new Date(e.created_at).toLocaleString())}">${esc(relTime(e.created_at))}</span></li>`;+ return `<li><span class="ic ${esc(e.kind)}" aria-hidden="true">${m.icon}</span><div class="body">${esc(what)} ${esc(symOf(e.order_id))}${reasonChip(e.meta?.reason_code || (String(e.detail || '').match(/^\[([A-Z_]+)\]/) || [])[1])}${e.detail ? `<small>${esc(String(e.detail).slice(0, 160))}</small>` : ''}</div><span class="t" title="${esc(new Date(e.created_at).toLocaleString())}">${esc(relTime(e.created_at))}</span></li>`;}).join('')}</ul>`: `<div class="aord-empty"><div class="ic">🛰️</div>No activity yet. Every placement, fill, failure, skip and cancel lands here, and you get a notification when an order fires or fails.</div>`;return `<div class="aord-card" id="aord-activity"><h3>Activity</h3><p class="sub">Why each order did or didn’t fire, newest first.</p>${inner}</div>`;@@ -590,12 +622,12 @@ registerWalletTab({// ── wiring ────────────────────────────────────────────────────────────────function wire() {- panel.querySelectorAll('[data-type]').forEach((b) => b.addEventListener('click', () => { state.form.type = b.dataset.type; state.preview = null; render(); }));+ panel.querySelectorAll('[data-type]').forEach((b) => b.addEventListener('click', () => { state.form.type = b.dataset.type; if (b.dataset.type === 'trail_ratchet') state.form.side = 'sell'; state.preview = null; render(); }));panel.querySelectorAll('[data-side]').forEach((b) => b.addEventListener('click', () => { state.form.side = b.dataset.side; state.preview = null; render(); }));panel.querySelectorAll('[data-mode]').forEach((b) => b.addEventListener('click', () => { state.form.condition_mode = b.dataset.mode; render(); }));bindInput('f-mint', 'mint'); bindInput('f-slippage', 'slippage_bps'); bindInput('f-expires', 'expires_at');bindInput('f-metric', 'trigger_metric', true); bindInput('f-limit_price', 'limit_price'); bindInput('f-stop_price', 'stop_price');- bindInput('f-trail_pct', 'trail_pct'); bindInput('f-size_sol', 'size_sol'); bindInput('f-sell_pct', 'sell_pct');+ bindInput('f-trail_pct', 'trail_pct'); bindInput('f-ratchet_initial', 'ratchet_initial'); bindInput('f-ratchet_entry', 'ratchet_entry'); bindInput('f-size_sol', 'size_sol'); bindInput('f-sell_pct', 'sell_pct');bindInput('f-total_sol', 'total_sol'); bindInput('f-total_pct', 'total_pct'); bindInput('f-interval', 'interval', true); bindInput('f-slices', 'slices');bindInput('f-venue', 'venue', true); bindInput('f-band_min', 'band_min'); bindInput('f-band_max', 'band_max');bindInput('f-oco_limit', 'oco_limit'); bindInput('f-oco_stop', 'oco_stop');@@ -606,6 +638,16 @@ registerWalletTab({}));// Totals in the ladder hint update on blur so typing keeps focus.panel.querySelectorAll('[data-li]').forEach((el) => el.addEventListener('change', () => { if (el.dataset.lf !== 'price') render(); }));+ panel.querySelectorAll('[data-ti]').forEach((el) => el.addEventListener('input', () => {+ state.form.tiers[Number(el.dataset.ti)][el.dataset.tf] = el.value;+ state.preview = null;+ }));+ panel.querySelector('#aord-add-tier')?.addEventListener('click', () => {+ const last = state.form.tiers[state.form.tiers.length - 1] || { profit: '0', lock: '0' };+ state.form.tiers.push({ profit: String((Number(last.profit) || 0) * 2 || 100), lock: String(Math.round(((Number(last.profit) || 0) + (Number(last.lock) || 0)) / 2)) });+ render();+ });+ panel.querySelectorAll('[data-trm]').forEach((b) => b.addEventListener('click', () => { if (state.form.tiers.length > 1) { state.form.tiers.splice(Number(b.dataset.trm), 1); render(); } }));panel.querySelector('#aord-add-leg')?.addEventListener('click', () => {const last = state.form.legs[state.form.legs.length - 1] || { pct: '25', sol: '0.1' };state.form.legs.push({ price: '', pct: last.pct, sol: last.sol });@@ -656,7 +698,10 @@ registerWalletTab({if (f.type === 'limit') o.limit_price = Number(f.limit_price);else if (f.type === 'stop') o.stop_price = Number(f.stop_price);else if (f.type === 'trailing') o.trail_pct = Number(f.trail_pct);- else if (f.type === 'dca') o.schedule = { interval_seconds: Number(f.interval), slices: Number(f.slices) };+ else if (f.type === 'trail_ratchet') {+ o.ratchet = { initial_stop_pct: Number(f.ratchet_initial), tiers: f.tiers.map((t) => ({ profit_pct: Number(t.profit), lock_pct: Number(t.lock) })) };+ if (f.ratchet_entry !== '') o.entry_price = Number(f.ratchet_entry);+ } else if (f.type === 'dca') o.schedule = { interval_seconds: Number(f.interval), slices: Number(f.slices) };else if (f.type === 'twap') {o.schedule = { interval_seconds: Number(f.interval), slices: Number(f.slices) };if (f.side === 'buy') { o.total_sol = Number(f.total_sol); delete o.size_sol; } else { o.sell_pct = Number(f.total_pct); }diff --git a/tests/agent-orders-sweep.test.js b/tests/agent-orders-sweep.test.jsindex 36d63f72a..76af6e4fc 100644--- a/tests/agent-orders-sweep.test.js+++ b/tests/agent-orders-sweep.test.js@@ -491,6 +491,48 @@ describe('runOrderSweep: conditional and trailing triggers', () => {expect(tradeState.calls).toHaveLength(0);});+ it('ratchet: holds in phase 1, locks a tier at the peak, and fires TIER_LOCK on the fall back', async () => {+ const ratchet = { initial_stop_pct: 30, tiers: [{ profit_pct: 50, lock_pct: 10 }] };+ const base = { type: 'trail_ratchet', side: 'sell', size_sol: null, sell_pct: 100, limit_price: null, ratchet, reference_price: 100_000, peak_price: 100_000 };+ dbState.activeOrders = [order(base)];+ priceAt(80_000); // 20% under entry, inside the wide stop+ await runOrderSweep(cfg);+ expect(tradeState.calls).toHaveLength(0);++ dbState.calls = [];+ dbState.activeOrders = [order({ ...base, peak_price: 160_000 })]; // tier 1 armed earlier+ priceAt(120_000); // above the +10% lock (110000)+ await runOrderSweep(cfg);+ expect(tradeState.calls).toHaveLength(0);+ expect(call('mark_evaluated').values[1]).toBe(160_000);++ dbState.calls = [];+ priceAt(105_000); // through the lock, still above the phase 1 stop+ await runOrderSweep(cfg);+ expect(tradeState.calls).toHaveLength(1);+ expect(tradeState.calls[0].input.isMax).toBe(true);+ const fill = call('insert_fill') || call('advance');+ expect(JSON.stringify(dbState.calls)).toContain('TIER_LOCK');+ expect(fill).toBeTruthy();+ });++ it('ratchet: a gap straight through a lock tier exits with TIER_LOCK, a phase 1 breach with DRAWDOWN', async () => {+ const ratchet = { initial_stop_pct: 30, tiers: [{ profit_pct: 50, lock_pct: 10 }] };+ const base = { type: 'trail_ratchet', side: 'sell', size_sol: null, sell_pct: 100, limit_price: null, ratchet, reference_price: 100_000 };+ dbState.activeOrders = [order({ ...base, peak_price: 200_000 })];+ priceAt(60_000);+ await runOrderSweep(cfg);+ expect(tradeState.calls).toHaveLength(1);+ expect(JSON.stringify(dbState.calls)).toContain('TIER_LOCK');++ dbState.calls = []; tradeState.calls = [];+ dbState.activeOrders = [order({ ...base, peak_price: 100_000 })];+ priceAt(65_000);+ await runOrderSweep(cfg);+ expect(tradeState.calls).toHaveLength(1);+ expect(JSON.stringify(dbState.calls)).toContain('DRAWDOWN');+ });+it('tracks the trailing high-water mark each sweep and fires on the drawdown', async () => {dbState.activeOrders = [order({ type: 'trailing', side: 'sell', size_sol: null, sell_pct: 100, trail_pct: 20, peak_price: 100_000, limit_price: null })];priceAt(90_000); // only 10% off the peakdiff --git a/tests/exit-ratchet.test.js b/tests/exit-ratchet.test.jsnew file mode 100644index 000000000..98243d794--- /dev/null+++ b/tests/exit-ratchet.test.js@@ -0,0 +1,122 @@+import { describe, it, expect } from 'vitest';+import {+ evaluateRatchet, ratchetStop, normalizeRatchet, reasonCodeForGuard, REASON_CODES,+} from '../api/_lib/exit-ratchet.js';+import { normalizeOrder, describeOrder, ORDER_TYPES } from '../api/_lib/orders.js';+import { nextFire } from '../api/_lib/order-book.js';++const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+// Entry 100. Wide 30% stop = 70. +50% arms a lock at +10% (110); +100% arms +50% (150); +200% arms +120% (220).+const ratchet = {+ initial_stop_pct: 30,+ tiers: [+ { profit_pct: 50, lock_pct: 10 },+ { profit_pct: 100, lock_pct: 50 },+ { profit_pct: 200, lock_pct: 120 },+ ],+};++describe('evaluateRatchet table', () => {+ const rows = [+ // name, peak, value, fire, code, stop, tier+ ['phase 1 holds above the wide stop', 100, 80, false, null, 70, null],+ ['phase 1 holds exactly at the stop boundary + 1', 100, 70.01, false, null, 70, null],+ ['phase 1 exits at the wide stop', 100, 70, true, 'DRAWDOWN', 70, null],+ ['phase 1 exits below the wide stop', 100, 40, true, 'DRAWDOWN', 70, null],+ ['peak below tier 1 trigger keeps phase 1', 149, 100, false, null, 70, null],+ ['tier 1 arms at +50% and floor rises to 110', 150, 140, false, null, 110, 0],+ ['tier 1 locks: falls to the lock', 150, 110, true, 'TIER_LOCK', 110, 0],+ ['tier 1 locks: falls under the lock', 160, 100, true, 'TIER_LOCK', 110, 0],+ ['tier 2 arms at +100%', 200, 151, false, null, 150, 1],+ ['tier 2 locks', 200, 150, true, 'TIER_LOCK', 150, 1],+ ['stop never falls back to tier 1 after tier 2 armed', 200, 120, true, 'TIER_LOCK', 150, 1],+ ['tier 3 arms at +200%', 300, 230, false, null, 220, 2],+ ['tier 3 locks', 300, 219, true, 'TIER_LOCK', 220, 2],+ ['gap-down from the peak through two lock tiers fires', 300, 90, true, 'TIER_LOCK', 220, 2],+ ['gap-down straight through tier 1 lock fires with TIER_LOCK', 150, 60, true, 'TIER_LOCK', 110, 0],+ ['value above peak raises the peak, stop follows', 100, 210, false, null, 150, 1],+ ];+ for (const [name, peak, value, fire, code, stop, tier] of rows) {+ it(name, () => {+ const r = evaluateRatchet({ entry: 100, peak, value, ratchet });+ expect(r.fire).toBe(fire);+ expect(r.code).toBe(code);+ expect(r.stop).toBeCloseTo(stop, 8);+ expect(r.tier).toBe(tier);+ });+ }++ it('a stale peak below the entry is clamped up to the entry', () => {+ expect(ratchetStop({ entry: 100, peak: 10, ratchet }).stop).toBeCloseTo(70, 8);+ });++ it('the stop is monotonic in the peak', () => {+ let last = -Infinity;+ for (let peak = 100; peak <= 400; peak += 5) {+ const { stop } = ratchetStop({ entry: 100, peak, ratchet });+ expect(stop).toBeGreaterThanOrEqual(last);+ last = stop;+ }+ });++ it('a negative lock above the initial stop still raises the floor in phase 2', () => {+ const r = { initial_stop_pct: 40, tiers: [{ profit_pct: 20, lock_pct: -10 }] };+ expect(ratchetStop({ entry: 100, peak: 125, ratchet: r })).toMatchObject({ stop: 90, phase: 2, code: 'TIER_LOCK' });+ });++ it('holds on a missing value or entry', () => {+ expect(evaluateRatchet({ entry: 100, peak: 100, value: NaN, ratchet }).fire).toBe(false);+ expect(evaluateRatchet({ entry: 0, peak: 100, value: 50, ratchet }).fire).toBe(false);+ });+});++describe('normalizeRatchet', () => {+ it('accepts a valid spec', () => {+ expect(normalizeRatchet(ratchet).ok).toBe(true);+ });+ it.each([+ ['no object', null],+ ['no tiers', { initial_stop_pct: 30, tiers: [] }],+ ['bad initial stop', { initial_stop_pct: 100, tiers: [{ profit_pct: 10, lock_pct: 1 }] }],+ ['lock at or above its trigger', { initial_stop_pct: 30, tiers: [{ profit_pct: 10, lock_pct: 10 }] }],+ ['non ascending tiers', { initial_stop_pct: 30, tiers: [{ profit_pct: 50, lock_pct: 10 }, { profit_pct: 40, lock_pct: 20 }] }],+ ['lock below the initial stop', { initial_stop_pct: 30, tiers: [{ profit_pct: 50, lock_pct: -35 }] }],+ ['too many tiers', { initial_stop_pct: 30, tiers: Array.from({ length: 9 }, (_, i) => ({ profit_pct: 10 + i, lock_pct: i })) }],+ ])('rejects %s', (_n, raw) => {+ expect(normalizeRatchet(raw).ok).toBe(false);+ });+});++describe('reason codes', () => {+ it('maps guard reasons onto stable codes', () => {+ expect(reasonCodeForGuard('daily_loss_limit')).toBe('DAILY_LOSS');+ expect(reasonCodeForGuard('price_impact')).toBe('IMPACT');+ expect(reasonCodeForGuard('kill_switch')).toBeNull();+ expect(Object.keys(REASON_CODES).sort()).toEqual(['DAILY_LOSS', 'DRAWDOWN', 'IMPACT', 'TIER_LOCK']);+ });+});++describe('trail_ratchet orders', () => {+ const base = { type: 'trail_ratchet', side: 'sell', mint: THREE, sell_pct: 100, ratchet, entry_price: 100 };+ it('is a registered order type', () => {+ expect(ORDER_TYPES).toContain('trail_ratchet');+ });+ it('normalizes, carries the entry, and reads back in words', () => {+ const r = normalizeOrder(base);+ expect(r.ok).toBe(true);+ expect(r.order.entry_price).toBe(100);+ expect(r.order.ratchet.tiers).toHaveLength(3);+ expect(describeOrder({ ...r.order, symbol: 'THREE' })).toMatch(/Ratcheting stop: sell .* if it falls 30% below entry/);+ });+ it('is sell only', () => {+ expect(normalizeOrder({ ...base, side: 'buy', size_sol: 1 }).error).toBe('invalid_side');+ });+ it('rejects a bad ratchet and a bad entry', () => {+ expect(normalizeOrder({ ...base, ratchet: { initial_stop_pct: 30, tiers: [] } }).error).toBe('invalid_ratchet');+ expect(normalizeOrder({ ...base, entry_price: -1 }).error).toBe('invalid_price');+ });+ it('the order book explains when it acts', () => {+ const o = { ...normalizeOrder(base).order, status: 'active', hold_until: null };+ expect(nextFire(o).label).toMatch(/30% under entry/);+ });+});diff --git a/workers/agent-orders/README.md b/workers/agent-orders/README.mdindex ec075beed..a50b30d3a 100644--- a/workers/agent-orders/README.md+++ b/workers/agent-orders/README.md@@ -52,6 +52,7 @@ block such as a firewall rug verdict).| `limit` buy / sell | metric ≤ target (dip) / ≥ target (rise) || `stop` sell / buy | metric ≤ stop (stop-loss) / ≥ stop (breakout) || `trailing` sell / buy | metric ≤ peak·(1−trail%) / ≥ trough·(1+trail%) |+| `trail_ratchet` sell | the two-phase stop below: initial wide stop, then lock tiers that never loosen || `dca` | `next_fire_at ≤ now`, one slice per interval, N slices || `twap` | same scheduling; slices ONE total order to cut impact || `conditional` | a validated `{ all\|any: [{ signal, op, value }] }` is true |@@ -60,6 +61,26 @@ block such as a firewall rug verdict).`price_sol`, `mcap_sol`, `mcap_usd`, `price_change_pct`, `smart_money_score`,`dev_dump`, `graduated` — all real, code-free (see `api/_lib/orders.js`).+### Ratcheting trailing stop (`trail_ratchet`)++A sell-only stop with two phases, pure logic in `api/_lib/exit-ratchet.js`:++1. **Phase 1, the wide stop.** The position gets room to breathe: the order sells if the trigger metric falls `ratchet.initial_stop_pct` below the entry.+2. **Phase 2, lock tiers.** `ratchet.tiers` is `[{ profit_pct, lock_pct }]`, ascending. Once the high-water mark has shown `profit_pct` over the entry, the stop is never below `entry * (1 + lock_pct/100)`. The high-water mark only rises, so a tier stays armed after price falls back under its trigger.++The entry is `entry_price` (in the trigger metric) when the order is placed, otherwise the first live reading the sweep takes. A gap down through a lock tier still exits on the first sweep that sees it, at the live fill, because the test is `value <= stop`. Create it from the Orders tab (Ratchet) or `POST /api/agents/:id/orders` with `{ type: "trail_ratchet", side: "sell", mint, sell_pct, ratchet: { initial_stop_pct: 30, tiers: [{ profit_pct: 50, lock_pct: 10 }] }, entry_price? }`.++### Reason codes++Every ratchet exit and every guard refusal carries a stable code, shown as a chip on the order card and in Activity, written to `agent_order_events` (`meta.reason_code` for exits, a `[CODE]` prefix on the skip detail for refusals), and recorded on the agent's decision trail as kind `order_exit` for exits:++| Code | Meaning |+|------|---------|+| `DRAWDOWN` | price fell through the phase 1 initial stop |+| `TIER_LOCK` | price fell back to a locked-in profit tier |+| `DAILY_LOSS` | a fill was refused because the agent hit its daily loss limit |+| `IMPACT` | a fill was refused because price impact exceeded the safety limit |+### Sizing a percentage sell (DCA and TWAP differ on purpose)Both scheduled types accept `sell_pct`, and they mean different things:@@ -125,7 +146,7 @@ execution path touches Postgres and Solana RPC only.## Tests```bash-npx vitest run tests/orders-engine.test.js tests/agent-orders-sweep.test.js+npx vitest run tests/orders-engine.test.js tests/agent-orders-sweep.test.js tests/exit-ratchet.test.js````tests/orders-engine.test.js` covers the pure rule layer (`api/_lib/orders.js`:diff --git a/workers/agent-orders/sweep.js b/workers/agent-orders/sweep.jsindex 62172a1f8..6e21c3dff 100644--- a/workers/agent-orders/sweep.js+++ b/workers/agent-orders/sweep.js@@ -23,6 +23,8 @@ import { insertNotification } from '../../api/_lib/notify.js';import {shouldFirePrice, evaluateCondition, conditionSignals, describeOrder,} from '../../api/_lib/orders.js';+import { evaluateRatchet, reasonCodeForGuard, REASON_CODES } from '../../api/_lib/exit-ratchet.js';+import { recordDecision } from '../../api/_lib/reasoning-ledger.js';import { skipCodeFor, isVenueFailure, skipLabel } from '../../api/_lib/order-book.js';import { getSignals, metricValue, getHolding } from './market.js';import {@@ -180,12 +182,23 @@ async function evaluate(order, now) {const base = order.peak_price ?? metricVal;peak = order.side === 'sell' ? Math.max(base, metricVal) : Math.min(base, metricVal);}+ // A ratcheting stop's entry is its reference price (set at placement, or the+ // first live observation); the high-water mark never starts below it.+ const entry = order.reference_price ?? (order.type === 'trail_ratchet' ? metricVal : null);+ if (order.type === 'trail_ratchet' && metricVal != null) {+ peak = Math.max(order.peak_price ?? 0, entry ?? 0, metricVal);+ }await markEvaluated(order.id, { lastPrice: metricVal, peak });let fire = null;if (order.type === 'conditional') {const { fired } = evaluateCondition(order.condition, signals);if (fired) fire = { reason: 'condition', triggerPrice: metricVal, sliceIndex: 0, terminal: true, nextFireAt: null, route };+ } else if (order.type === 'trail_ratchet') {+ const r = evaluateRatchet({ entry, peak, value: metricVal, ratchet: order.ratchet });+ if (r.fire) {+ fire = { reason: r.code, exitCode: r.code, stop: r.stop, tier: r.tier, triggerPrice: metricVal, sliceIndex: 0, terminal: true, nextFireAt: null, route };+ }} else if (shouldFirePrice(order, metricVal, peak)) {const reason = order.type === 'trailing'? (order.side === 'sell' ? 'trailing_stop' : 'trailing_entry')@@ -367,6 +380,29 @@ async function announce(order, kind, { code = null, message, link = null, meta =});}+// A ratchet exit leaves one row on the agent's tamper-evident decision trail+// with its stable reason code. Best effort: the trail must never block a fill.+async function recordExitDecision(order, fire, { status, signature }) {+ try {+ await recordDecision({+ agentId: order.agent_id,+ kind: 'order_exit',+ subjectRef: order.id,+ actionRef: `${fire.exitCode}:${fire.sliceIndex}`,+ inputs: {+ reason_code: fire.exitCode, order_type: order.type, mint: order.mint,+ entry: order.reference_price, peak: order.peak_price, price: fire.triggerPrice,+ stop: fire.stop, tier: fire.tier, fill_status: status, signature: signature || null,+ },+ rationale: `${REASON_CODES[fire.exitCode]}: ${describeOrder(order)}`,+ confidence: 1,+ network: order.network,+ });+ } catch (e) {+ log.warn('exit decision not recorded', { order: order.id, error: e?.message });+ }+}+/** Map an executor result onto an order_fills record + advance the order. */async function settle(order, fire, result, mode) {const priorPartial = order.fill_count > 0;@@ -398,9 +434,13 @@ async function settle(order, fire, result, mode) {const skip = skipCodeFor(code);const changed = order.last_skip_code !== skip;if (isVenueFailure(code)) noteVenueResult(route, false);- await noteSkip(order, skip, `${code}: ${result.message || ''}`);+ const reasonCode = reasonCodeForGuard(code);+ await noteSkip(order, skip, `${reasonCode ? `[${reasonCode}] ` : ''}${code}: ${result.message || ''}`);if (changed && NOTIFY_SKIPS.has(skip)) {- await announce(order, 'skip', { code: skip, message: `${skipLabel(skip)}. ${result.message || ''}`.trim() });+ await announce(order, 'skip', {+ code: skip, message: `${skipLabel(skip)}. ${result.message || ''}`.trim(),+ meta: reasonCode ? { reason_code: reasonCode } : null,+ });}log.info('order fire blocked (will retry)', { order: order.id, code });return;@@ -434,7 +474,9 @@ async function settle(order, fire, result, mode) {const slices = order.schedule?.slices;const sliceNote = slices ? ` Slice ${fire.sliceIndex + 1} of ${slices}.` : '';const ocoNote = cancelled.length ? ' The other leg of the pair was cancelled.' : '';+ if (fire.exitCode) await recordExitDecision(order, fire, { status, signature: sig });await announce(order, 'fire', {+ meta: fire.exitCode ? { reason_code: fire.exitCode, stop: fire.stop, tier: fire.tier } : null,code: status,message: `${simulated ? 'Paper fill (simulation, nothing was sent): ' : ''}${describeOrder(order)}${sliceNote}${ocoNote}`,link: sig ? `https://solscan.io/tx/${sig}${order.network === 'devnet' ? '?cluster=devnet' : ''}` : null,