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.

feat: add force-close functionality for open positions in Trading Brain

qbdz5372940704fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0801234a7..bd217541d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,7 +27,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The markets & standings pages now move like the games they are** — Every surface that ranks, scores, or updates live got the same game-feel treatment as the Swarms page, all on real data. On the Trader Leaderboard, the board re-sorts by gliding each trader to their new rank instead of snapping, the headline counters count up between real values, and a connection dot tells you the standings are live or reconnecting. A trader's profile sweeps its score ring on load and counts the score and realized P&L into place. The Signal Marketplace re-ranks its feed cards with the same glide, counts its summary tiles, and shows a live dot. The Money Pulse counts its 24h volume, tips, launches and active-wallet numbers up between polls. Your Watchlist glides its coins into their new order as live data re-sorts them and counts the portfolio totals. Coin Clash gained a live dot, counting army tallies, and a ring gauge on each faction's win rate. Vaults now counts its stat tiles honestly — from the last real value, never faked from zero — and glides the vault board on re-sort. The agent Labor Market counts its $THREE volume and job tallies under a live dot. Coin Radar already spoke this language, and a long-standing render glitch that could blank the feed when a coin's net flow was exactly zero is now fixed. Nothing is invented — every number, rank and beat traces to a real value, and it all goes still under reduced motion. (`/leaderboard`) `[improvement, fix]`
- **The Sniper dashboard now carries the full Money Studio — wallet, Trading Brain, pricing and earnings** — The Sniper Strategies dashboard used to stop at strategy config and live positions. Now every strategy card has a second tab — Money Studio — that opens the exact same control surface as your agent's Money tab in Agent Studio, without leaving the dashboard. Fund the agent's wallet (live SOL and USDC balances, deposit address, withdraw with a one-tap Max, real SPL holdings and on-chain activity), open the full Trading Brain to draw a snipe rule and either scan live launches for one-tap assisted snipes or arm it to run autonomously, backtest a rule over the last 30 days, set per-call prices on the agent's skills, and watch what other agents pay it — all per agent, all real. No more bouncing between Agent Studio and the dashboard to top up a wallet before arming. The original Money tab in Agent Studio is untouched. (`/dashboard/sniper`) `[feature, improvement]`
- **The swarm members panel is now a live standings board** — A swarm is a competition between its members, and the members list now reads like one. Members are ranked by stake — #1, #2, #3 — with the lead member marked by a token accent, and each member's reputation shows as a vote-weight chip: the chip carries the reputation score with the exact share of the swarm's vote that score commands beneath it, so you can see your track record become voting power (computed the same way the consensus engine does). The moment the treasury fires a trade, the members who were on the winning side of that consensus pulse green — pulled straight from the real recorded vote breakdown, so you can see exactly who carried it. When someone contributes or exits, the share bars animate and the standings re-sort smoothly instead of snapping. Respects reduced-motion preferences. (`/swarms`) `[improvement]`
-- **The Trading Brain now tracks open snipes and today's budget burn live** — The sniping panel in Agent Studio's Money tab no longer goes stale the moment it loads. Open positions now mark to live price on their own — each one shows its unrealized P&L (in SOL and percent) and refreshes every few seconds, so a snipe climbing or bleeding updates in front of you instead of waiting for a reload. When your agent is armed, new fills and exits appear on the same live tick. The Guardrails card now shows real spend: how much SOL the agent has traded today against your daily budget, as a number and a progress bar that turns amber past 60% and red past 90% — so you can see the leash tightening before it stops you. Polling pauses when the tab is hidden to spare your rate limit, and resumes the moment you come back. (`/agent-studio`) `[improvement]`
+- **The Trading Brain now tracks open snipes live and lets you sell on one tap** — The sniping panel in Agent Studio's Money tab no longer goes stale the moment it loads. Open positions now mark to live price on their own — each one shows its unrealized P&L (in SOL and percent) and refreshes every few seconds, so a snipe climbing or bleeding updates in front of you instead of waiting for a reload. When your agent is armed, new fills and exits appear on the same live tick. Every open position now has a Sell now button: one tap exits the full holding immediately at a real price, through the exact same guarded path the agent's automatic take-profit and stop-loss use — so a manual exit and an automatic one can never drift, and getting out works even with the kill switch on. The Guardrails card now shows real spend: how much SOL the agent has traded today against your daily budget, as a number and a progress bar that turns amber past 60% and red past 90% — so you can see the leash tightening before it stops you. Polling pauses when the tab is hidden to spare your rate limit, and resumes the moment you come back. (`/agent-studio`) `[improvement]`
- **x402 payment-modal SDK now installs cleanly outside the monorepo** — The @three-ws/x402-payment-modal package shipped a server-side checkout adapter that quietly relied on @solana/web3.js, @solana/spl-token and express being present — they were never listed in the package, so installing it on its own and using the server piece failed with a missing-module error. Those are now declared as optional dependencies, so the browser modal stays as lightweight as ever while the server and React adapters pull in exactly what they need. The build also no longer assumes a monorepo folder layout. This is the first step in moving the x402 toolkit into its own repositories. `[fix, sdk]`
## 2026-06-29
diff --git a/api/agents/agent-strategy-objects.js b/api/agents/agent-strategy-objects.js
index eb8a1dcfa..9dbbfe3f4 100644
--- a/api/agents/agent-strategy-objects.js
+++ b/api/agents/agent-strategy-objects.js
@@ -10,6 +10,7 @@
// POST /api/agents/:id/strategies/toggle pause/resume one equip { equip_id, active } (owner)
// POST /api/agents/:id/strategies/kill toggle the per-owner global kill switch (owner)
// POST /api/agents/:id/strategies/sweep evaluate this agent's equips now (owner "Run now")
+// POST /api/agents/:id/strategies/close force-close ONE open position now { position_id } (owner "Sell now")
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
@@ -287,5 +288,6 @@ export default async function handler(req, res, id, action) {
if (req.method === 'POST' && action === 'toggle') return handleToggle(req, res, id);
if (req.method === 'POST' && action === 'kill') return handleKill(req, res, id);
if (req.method === 'POST' && action === 'sweep') return handleSweep(req, res, id);
+ if (req.method === 'POST' && action === 'close') return handleClose(req, res, id);
return error(res, 404, 'not_found', `unknown strategies route: ${action || req.method}`);
}
diff --git a/api/chat.js b/api/chat.js
index a88abc427..d381490f4 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -704,6 +704,27 @@ export default wrap(async (req, res) => {
// the next provider would also reject.
if ((upstream.status === 429 || upstream.status >= 500) && canFailOver()) {
const text = await upstream.text().catch(() => '');
+ // A 429 carrying a billing/quota signal is a deploy-wide wall, not a
+ // transient throttle — give it the long AUTH cooldown + 'auth' reason so the
+ // ladder stops re-routing to a dead-billing account every ~45s, and skip the
+ // failed provider's remaining sibling routes (same account → same wall).
+ const billingWall = upstream.status === 429 && isBillingQuotaError(text);
+ if (billingWall) {
+ void markProviderCooldown(route.name, AUTH_COOLDOWN_SECONDS, 'auth');
+ let next = routeIdx + 1;
+ while (next < fallbackRoutes.length && fallbackRoutes[next].name === route.name) next++;
+ console.warn(
+ `[chat:${route.name}] 429 (billing/quota — account unfunded) — cooling ${AUTH_COOLDOWN_SECONDS}s, failing over to ${fallbackRoutes[next]?.name}/${fallbackRoutes[next]?.model}: ${text.slice(0, 120)}`,
+ );
+ if (next < fallbackRoutes.length && Date.now() < deadline) {
+ routeIdx = next;
+ route = fallbackRoutes[routeIdx];
+ includeTools = true;
+ retriedTransient = false;
+ continue;
+ }
+ break; // every remaining route is the same dead account — surface terminal below
+ }
console.warn(
`[chat:${route.name}] ${upstream.status} — falling over to ${fallbackRoutes[routeIdx + 1].name}/${fallbackRoutes[routeIdx + 1].model}: ${text.slice(0, 120)}`,
);
@@ -778,8 +799,17 @@ export default wrap(async (req, res) => {
/provider returned error|rate.?limit|over.?loaded|capacity|temporarily unavailable|quota|exceeded your current/i.test(
`${upstreamMessage} ${text}`,
);
- // The final route failed too — cool it down so the next request skips it.
- if (atCapacity) void markProviderCooldown(route.name);
+ // The final route failed too — cool it down so the next request skips it. A
+ // billing/quota wall gets the long AUTH cooldown (won't recover until ops tops
+ // up) so the dead account isn't re-probed as the final tier every request.
+ if (atCapacity) {
+ const billingWall = isBillingQuotaError(`${upstreamMessage} ${text}`);
+ void markProviderCooldown(
+ route.name,
+ billingWall ? AUTH_COOLDOWN_SECONDS : undefined,
+ billingWall ? 'auth' : 'health',
+ );
+ }
if (atCapacity) res.setHeader('Retry-After', '20');
return error(
res,
@@ -1391,6 +1421,22 @@ function providersTried(attempted) {
return out;
}
+// A 429 (or exhausted-chain body) that is really a deploy-wide BILLING/QUOTA wall,
+// not a transient per-minute throttle. OpenAI returns HTTP 429 with
+// `type: "insufficient_quota"` ("You exceeded your current quota…") AND a separate
+// "Your account is not active, please check your billing details" for a dead/unfunded
+// account — both 429s the generic branch would cool for only DEFAULT_COOLDOWN_SECONDS
+// (45s), so the ladder re-routes to the dead provider as its final tier every ~45s and
+// re-hits the same wall (the "OVER QUOTA"/"route(s) exhausted" flood seen in prod).
+// These won't recover until ops tops up billing, so they deserve the long AUTH cooldown
+// and the 'auth' reason (so even an explicit provider request skips the dead account),
+// exactly like a 401/402/403. Replicate/Groq "insufficient credit" reads the same way.
+function isBillingQuotaError(text) {
+ return /insufficient[_\s]?quota|insufficient[_\s]?credit|exceeded your current quota|account is not active|check your billing|billing details|quota.*exceeded|exceeded.*quota|not active.*billing/i.test(
+ text || '',
+ );
+}
+
function fmt(n) {
return typeof n === 'number' ? n.toLocaleString('en-US') : '?';
}
diff --git a/data/changelog.json b/data/changelog.json
index ae2dff0c6..61dd3e240 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -77,8 +77,8 @@
},
{
"date": "2026-06-30",
- "title": "The Trading Brain now tracks open snipes and today's budget burn live",
- "summary": "The sniping panel in Agent Studio's Money tab no longer goes stale the moment it loads. Open positions now mark to live price on their own — each one shows its unrealized P&L (in SOL and percent) and refreshes every few seconds, so a snipe climbing or bleeding updates in front of you instead of waiting for a reload. When your agent is armed, new fills and exits appear on the same live tick. The Guardrails card now shows real spend: how much SOL the agent has traded today against your daily budget, as a number and a progress bar that turns amber past 60% and red past 90% — so you can see the leash tightening before it stops you. Polling pauses when the tab is hidden to spare your rate limit, and resumes the moment you come back.",
+ "title": "The Trading Brain now tracks open snipes live and lets you sell on one tap",
+ "summary": "The sniping panel in Agent Studio's Money tab no longer goes stale the moment it loads. Open positions now mark to live price on their own — each one shows its unrealized P&L (in SOL and percent) and refreshes every few seconds, so a snipe climbing or bleeding updates in front of you instead of waiting for a reload. When your agent is armed, new fills and exits appear on the same live tick. Every open position now has a Sell now button: one tap exits the full holding immediately at a real price, through the exact same guarded path the agent's automatic take-profit and stop-loss use — so a manual exit and an automatic one can never drift, and getting out works even with the kill switch on. The Guardrails card now shows real spend: how much SOL the agent has traded today against your daily budget, as a number and a progress bar that turns amber past 60% and red past 90% — so you can see the leash tightening before it stops you. Polling pauses when the tab is hidden to spare your rate limit, and resumes the moment you come back.",
"tags": [
"improvement"
],
diff --git a/public/changelog.json b/public/changelog.json
index 930036ed7..779ab5972 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-30T19:55:46.719Z",
+ "generated_at": "2026-06-30T21:06:29.296Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -225,8 +225,8 @@
{
"date": "2026-06-30",
"type": "update",
- "title": "The Trading Brain now tracks open snipes and today's budget burn live",
- "summary": "The sniping panel in Agent Studio's Money tab no longer goes stale the moment it loads. Open positions now mark to live price on their own — each one shows its unrealized P&L (in SOL and percent) and refreshes every few seconds, so a snipe climbing or bleeding updates in front of you instead of waiting for a reload. When your agent is armed, new fills and exits appear on the same live tick. The Guardrails card now shows real spend: how much SOL the agent has traded today against your daily budget, as a number and a progress bar that turns amber past 60% and red past 90% — so you can see the leash tightening before it stops you. Polling pauses when the tab is hidden to spare your rate limit, and resumes the moment you come back.",
+ "title": "The Trading Brain now tracks open snipes live and lets you sell on one tap",
+ "summary": "The sniping panel in Agent Studio's Money tab no longer goes stale the moment it loads. Open positions now mark to live price on their own — each one shows its unrealized P&L (in SOL and percent) and refreshes every few seconds, so a snipe climbing or bleeding updates in front of you instead of waiting for a reload. When your agent is armed, new fills and exits appear on the same live tick. Every open position now has a Sell now button: one tap exits the full holding immediately at a real price, through the exact same guarded path the agent's automatic take-profit and stop-loss use — so a manual exit and an automatic one can never drift, and getting out works even with the kill switch on. The Guardrails card now shows real spend: how much SOL the agent has traded today against your daily budget, as a number and a progress bar that turns amber past 60% and red past 90% — so you can see the leash tightening before it stops you. Polling pauses when the tab is hidden to spare your rate limit, and resumes the moment you come back.",
"link": "/agent-studio",
"tags": [
"improvement"
diff --git a/public/changelog.xml b/public/changelog.xml
index 58905049e..45f616bb3 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -175,12 +175,12 @@
<description>A swarm is a competition between its members, and the members list now reads like one. Members are ranked by stake — #1, #2, #3 — with the lead member marked by a token accent, and each member's reputation shows as a vote-weight chip: the chip carries the reputation score with the exact share of the swarm's vote that score commands beneath it, so you can see your track record become voting power (computed the same way the consensus engine does). The moment the treasury fires a trade, the members who were on the winning side of that consensus pulse green — pulled straight from the real recorded vote breakdown, so you can see exactly who carried it. When someone contributes or exits, the share bars animate and the standings re-sort smoothly instead of snapping. Respects reduced-motion preferences.</description>
</item>
<item>
- <title>The Trading Brain now tracks open snipes and today's budget burn live</title>
+ <title>The Trading Brain now tracks open snipes live and lets you sell on one tap</title>
<link>https://three.ws/agent-studio</link>
- <guid isPermaLink="false">2026-06-30:The Trading Brain now tracks open snipes and today's budget burn live</guid>
+ <guid isPermaLink="false">2026-06-30:The Trading Brain now tracks open snipes live and lets you sell on one tap</guid>
<pubDate>Tue, 30 Jun 2026 12:00:00 GMT</pubDate>
<category>improvement</category>
- <description>The sniping panel in Agent Studio's Money tab no longer goes stale the moment it loads. Open positions now mark to live price on their own — each one shows its unrealized P&amp;L (in SOL and percent) and refreshes every few seconds, so a snipe climbing or bleeding updates in front of you instead of waiting for a reload. When your agent is armed, new fills and exits appear on the same live tick. The Guardrails card now shows real spend: how much SOL the agent has traded today against your daily budget, as a number and a progress bar that turns amber past 60% and red past 90% — so you can see the leash tightening before it stops you. Polling pauses when the tab is hidden to spare your rate limit, and resumes the moment you come back.</description>
+ <description>The sniping panel in Agent Studio's Money tab no longer goes stale the moment it loads. Open positions now mark to live price on their own — each one shows its unrealized P&amp;L (in SOL and percent) and refreshes every few seconds, so a snipe climbing or bleeding updates in front of you instead of waiting for a reload. When your agent is armed, new fills and exits appear on the same live tick. Every open position now has a Sell now button: one tap exits the full holding immediately at a real price, through the exact same guarded path the agent's automatic take-profit and stop-loss use — so a manual exit and an automatic one can never drift, and getting out works even with the kill switch on. The Guardrails card now shows real spend: how much SOL the agent has traded today against your daily budget, as a number and a progress bar that turns amber past 60% and red past 90% — so you can see the leash tightening before it stops you. Polling pauses when the tab is hidden to spare your rate limit, and resumes the moment you come back.</description>
</item>
<item>
<title>x402 payment-modal SDK now installs cleanly outside the monorepo</title>
diff --git a/public/error-reporter.js b/public/error-reporter.js
index 7f08df067..a35b4075d 100644
--- a/public/error-reporter.js
+++ b/public/error-reporter.js
@@ -218,15 +218,57 @@
try {
const json = JSON.stringify(value);
// A real Error (or any object whose useful fields are non-enumerable)
- // serializes to "{}" — a content-free report that tells us nothing. Fall
- // back to the value's own string form so we capture at least the class.
- if (json == null || json === '{}' || json === 'null') return String(value);
+ // serializes to "{}" — a content-free report. Before giving up to
+ // `String(value)` (which yields the diagnostically useless "[object
+ // Object]"), dig the value's OWN property names — these include the
+ // non-enumerable fields JSON.stringify skips, which is exactly where
+ // cross-realm Errors, DOMExceptions, and framework error wrappers hide
+ // `code`/`status`/`message`. That turns an opaque `[object Object]` into a
+ // real signal like `{code:4001,reason:"user rejected"}`.
+ if (json == null || json === '{}' || json === 'null') {
+ const dug = describeOpaqueObject(value);
+ return dug || String(value);
+ }
return json;
} catch {
return String(value);
}
}
+ // Build a `{key:value, …}` summary from an object's own property names,
+ // including the non-enumerable ones JSON.stringify ignores. Only primitive
+ // values are inlined (a getter that throws, or a nested object/function, is
+ // noted by type, never invoked deeply) so this stays exception-proof and
+ // bounded. Returns '' when the object genuinely carries nothing useful, so the
+ // caller can fall back to its own last resort.
+ function describeOpaqueObject(value) {
+ if (!value || typeof value !== 'object') return '';
+ let names;
+ try {
+ names = Object.getOwnPropertyNames(value);
+ } catch {
+ return '';
+ }
+ const parts = [];
+ for (const key of names) {
+ if (key === 'stack' || parts.length >= 12) continue; // stack captured separately
+ let v;
+ try {
+ v = value[key]; // may be a throwing getter — guarded
+ } catch {
+ continue;
+ }
+ const t = typeof v;
+ if (v == null) parts.push(`${key}:${String(v)}`);
+ else if (t === 'string') parts.push(`${key}:${v.length > 120 ? v.slice(0, 120) + '…' : v}`);
+ else if (t === 'number' || t === 'boolean' || t === 'bigint') parts.push(`${key}:${String(v)}`);
+ else if (t === 'object') parts.push(`${key}:[object]`);
+ else if (t === 'function') parts.push(`${key}:[function]`);
+ }
+ if (!parts.length) return '';
+ return `{${parts.join(', ')}}`;
+ }
+
// Extract a useful { name, message, stack } from a rejection reason of ANY
// shape. A promise can reject with a real Error, an Error thrown across a
// module/realm boundary (whose `instanceof Error` is false but which still
@@ -243,15 +285,22 @@
}
if (reason && typeof reason === 'object') {
// Duck-typed / cross-realm errors and common wrapper shapes.
- const message =
- (typeof reason.message === 'string' && reason.message) ||
- (typeof reason.reason === 'string' && reason.reason) ||
- (reason.error && typeof reason.error.message === 'string' && reason.error.message) ||
- safeStringify(reason);
const name =
(typeof reason.name === 'string' && reason.name) ||
(reason.constructor && reason.constructor.name) ||
undefined;
+ let message =
+ (typeof reason.message === 'string' && reason.message) ||
+ (typeof reason.reason === 'string' && reason.reason) ||
+ (reason.error && typeof reason.error.message === 'string' && reason.error.message) ||
+ safeStringify(reason);
+ // `safeStringify` already digs non-enumerable props, but a genuinely empty
+ // object still collapses to the useless "[object Object]". Replace it with a
+ // marker that at least names the class and flags the empty shape — far more
+ // actionable in [client-error] than a bare "[object Object]".
+ if (message === '[object Object]') {
+ message = `(${name || 'Object'} thrown with no diagnostic fields)`;
+ }
const stack = typeof reason.stack === 'string' ? reason.stack : undefined;
return { name, message, stack };
}
diff --git a/public/features.json b/public/features.json
index 75795e963..bc032eb2a 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-30T19:55:46.701Z",
+ "generated_at": "2026-06-30T21:06:29.251Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/studio-panels.css b/public/studio-panels.css
index d5d342055..4554a761f 100644
--- a/public/studio-panels.css
+++ b/public/studio-panels.css
@@ -732,7 +732,7 @@
/* — Positions — */
.tb-pos, .tb-audit-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
.tb-pos-row {
- display: grid; grid-template-columns: 1.4fr 0.9fr 0.9fr 1.2fr; gap: 10px; align-items: center;
+ display: grid; grid-template-columns: 1.4fr 0.9fr 0.9fr 1.2fr auto; gap: 10px; align-items: center;
padding: 10px 12px; border-radius: var(--radius-md, 10px);
background: var(--surface-1, rgba(255, 255, 255, 0.03)); border: 1px solid var(--stroke);
font-size: var(--text-md, 0.8125rem);
@@ -747,6 +747,10 @@
.tb-pos-pnl { text-align: right; font-variant-numeric: tabular-nums; color: var(--ink, #e8e8e8); }
.tb-pos-pnl.pos { color: var(--success, #4ade80); }
.tb-pos-pnl.neg { color: var(--danger, #f87171); }
+.tb-pos-close { margin-top: 0; padding: 5px 10px; font-size: var(--text-2xs, 0.6875rem); justify-self: end; white-space: nowrap; }
+.tb-pos-close:hover:not(:disabled) { border-color: var(--danger, #f87171); color: var(--danger, #f87171); }
+.tb-pos-close:disabled { opacity: 0.6; cursor: progress; }
+.tb-pos-close-spacer { display: inline-block; }
/* — Audit — */
.tb-export { margin-top: 0 !important; }
@@ -771,6 +775,8 @@
@media (max-width: 540px) {
.tb-pos-row { grid-template-columns: 1fr 1fr; }
+ .tb-pos-close { grid-column: 1 / -1; justify-self: stretch; text-align: center; }
+ .tb-pos-close-spacer { display: none; }
.tb-audit-row { grid-template-columns: 1fr auto; }
.tb-audit-time, .tb-audit-amt { display: none; }
.tb-cand { flex-direction: column; align-items: flex-start; }
diff --git a/src/studio/money/trading-brain.js b/src/studio/money/trading-brain.js
index c7be2f7ba..ea76b893a 100644
--- a/src/studio/money/trading-brain.js
+++ b/src/studio/money/trading-brain.js
@@ -477,6 +477,43 @@ class TradingBrain {
}
}
+ // Force-close one open position now — the per-position "Sell now" lever. Sells
+ // the agent's full holding through the SAME guarded strategy-exit path the
+ // autonomous take-profit/stop uses (server-side), so manual and automatic exits
+ // can never drift. Selling moves SOL inward, so it works even with the kill
+ // switch on — getting out is always allowed.
+ async _closePosition(positionId) {
+ if (!positionId) return;
+ const btn = this.el.querySelector(`[data-action="close-pos"][data-pos="${CSS.escape(positionId)}"]`);
+ if (btn) { if (btn.disabled) return; btn.disabled = true; btn.textContent = 'Selling…'; }
+ try {
+ const res = await apiFetch(`/api/agents/${this.agentId}/strategies/close`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ position_id: positionId }),
+ });
+ const payload = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(payload?.error?.message || 'Could not close the position.');
+ const d = payload.data || {};
+ const pnl = d.pnl_sol;
+ this.studio.emitMarket?.({ type: 'trade:sell', mint: d.mint });
+ if (d.reconciled) {
+ this._toast(`${d.symbol || 'Position'} was already sold — reconciled`);
+ } else {
+ const pnlStr = pnl != null ? ` · ${pnl >= 0 ? '+' : ''}${fmtSol(pnl)} SOL` : '';
+ this._toast(`Closed ${d.symbol || short(d.mint)}${pnlStr}${d.unconfirmed ? ' (confirming…)' : ''}`);
+ }
+ // Refresh positions + audit so the close shows immediately; live polling
+ // keeps the rest current.
+ await this._refreshStrategies();
+ this._renderPositions();
+ this._fetchAudit().then((a) => { this.state.audit = a; this._renderAudit(); });
+ } catch (err) {
+ this._toast(err.message || 'Close failed', true);
+ if (btn) { btn.disabled = false; btn.textContent = 'Sell now'; }
+ }
+ }
+
async _writeTradeMemory(cand, signature) {
// Coordinate with P2: record the trade, its rationale, and the outcome so the
// agent remembers what it did and why. Best-effort — a memory hiccup never
@@ -886,6 +923,7 @@ class TradingBrain {
<span class="tb-pos-state">${live ? `<span class="tb-pos-live">● ${esc(p.status)}</span>` : esc(p.exit_reason || 'closed')}</span>
<span class="tb-pos-entry">${fmtSol(p.entry_sol)} SOL in</span>
<span class="tb-pos-pnl ${cls}" title="${live ? 'Unrealized — marked to live price' : 'Realized at exit'}">${pnlText}</span>
+ ${p.status === 'open' ? `<button class="studio-btn studio-btn-ghost tb-pos-close" data-action="close-pos" data-pos="${esc(p.id)}" title="Sell the full holding now at a real price">Sell now</button>` : `<span class="tb-pos-close-spacer" aria-hidden="true"></span>`}
</li>`;
}
@@ -936,6 +974,7 @@ class TradingBrain {
if (a === 'scan') return this._scan();
if (a === 'confirm-snipe') return this._confirmSnipe(btn.dataset.mint);
if (a === 'save-guardrails') return this._saveGuardrails();
+ if (a === 'close-pos') return this._closePosition(btn.dataset.pos);
if (a === 'export-audit') return this._exportAudit();
});
// Rule edits — live recompute (English + validation) and debounced meta save.