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(exit-lab): counterfactual exit-policy replay over real closed positions
nirholasde35d1ba1d6d
diff --git a/api/_lib/exit-replay.js b/api/_lib/exit-replay.jsindex 4d7fe6d68..95602a525 100644--- a/api/_lib/exit-replay.js+++ b/api/_lib/exit-replay.js@@ -1,5 +1,5 @@/**- * Exit Lab — counterfactual replay of REAL closed positions under a different+ * Exit Lab: counterfactual replay of REAL closed positions under a different* exit policy.** What this is, and why it is not the backtester@@ -12,7 +12,7 @@* This module answers the opposite, and much sharper, question: **the fleet* already spent this SOL. Were the exits right?** It takes positions that were* genuinely entered and closed on-chain and re-runs each one through- * `decideLadderedExit` — the SAME function the live position loop calls — with a+ * `decideLadderedExit` (the SAME function the live position loop calls) with a* different set of exit parameters, mirroring the live partial-sell bookkeeping* leg for leg. Nothing here is synthesized: every input is a recorded price* point from a position that cost real money.diff --git a/api/sniper/exit-lab.js b/api/sniper/exit-lab.jsindex 615a289cb..64c7ab178 100644--- a/api/sniper/exit-lab.js+++ b/api/sniper/exit-lab.js@@ -1,6 +1,6 @@// @ts-check/**- * Exit Lab — the replayable corpus of REAL closed sniper positions.+ * Exit Lab: the replayable corpus of REAL closed sniper positions.** GET /api/sniper/exit-lab?network=mainnet&window=90&limit=400*diff --git a/docs/exit-lab.md b/docs/exit-lab.mdnew file mode 100644index 000000000..bd5a8467c--- /dev/null+++ b/docs/exit-lab.md@@ -0,0 +1,224 @@+# Exit Lab++**Live surface: [three.ws/exit-lab](https://three.ws/exit-lab)**++The fleet has already spent the SOL. Exit Lab answers the question that follows:+**were the exits right?**++It takes positions the agent fleet genuinely opened and closed on-chain, re-runs+each one through the exact exit code the live worker runs with the rules changed+to whatever you choose, and shows what those same trades would have returned. No+part of it is simulated. Every entry price, high-water mark and final quote is a+recorded number from a position that cost real money.++---++## Why this is not the backtester++three.ws already ships a backtester ([`api/_lib/strategy-backtest.js`](../api/_lib/strategy-backtest.js),+documented in [trading-experiment.md](trading-experiment.md)). The two answer+different questions and neither replaces the other.++| | Backtester (`/api/sniper/backtest`) | Exit Lab (`/exit-lab`) |+|---|---|---|+| Question | Would this strategy have **entered** profitably? | Were our **exits** right? |+| Corpus | Captured launch intel, including launches we never touched | Positions the fleet actually bought and sold |+| Money | Hypothetical | Real, already spent |+| Exit model | `decideExit`, the single-shot decider | `decideLadderedExit`, the live laddered decider |+| Models the moon bag | No | Yes, leg for leg |++The backtester tells you whether a filter is worth arming. Exit Lab tells you+whether the rule that sold was the rule that should have.++---++## What you can change++Every knob is declared once, in `PARAM_SPECS` in+[`api/_lib/exit-replay.js`](../api/_lib/exit-replay.js). The page builds its+sliders from that list and the search builds its grid from it, so a new+parameter appears in the console, the grid and this table without being written+down three times.++| Knob | What it does | Live default |+|---|---|---|+| Hard stop-loss | Sell everything once the position is this far below cost. Outranks every other rule. | 35% |+| Trailing stop | Sell after the price falls this far from its high-water mark. Only arms once the position has been green. | 25% |+| Take-profit ceiling | Close the remainder once the position is this far up. With the ladder armed, only applies after initials are out. | off |+| Take initials at | The multiple at which the stake comes back off the table. At 2x that is a half sell. Fires once. | 2x |+| Moon-bag floor | The share of the bag that always keeps riding on a profitable exit. | 15% |++A nullable knob set to `off` is **null, not zero**. That distinction is+load-bearing: `Number(null) === 0`, and a 0% stop-loss fires immediately on every+position. The `pct()` contract in+[`workers/agent-sniper/exit-logic.js`](../workers/agent-sniper/exit-logic.js) is+the single source of truth for it.++---++## How a replay works++A closed position records three honest price points and a duration:++```+entry_quote_lamports the SOL spent (cost basis)+peak_value_lamports the high-water mark of the bag's quoted SOL value+last_value_lamports the bag's quoted value when the exit fired+opened_at → closed_at how long it was held+```++The replay walks that path in two phases.++**Rising, from 1x to the peak.** Only two rules can fire while price climbs:+take-initials and the take-profit ceiling. Both are monotone in price, so the+next event is whichever triggers at the lower multiple. When a leg sells, the+replay mirrors the live partial-sell bookkeeping exactly (see the partial branch+in [`workers/agent-sniper/executor.js`](../workers/agent-sniper/executor.js)):+the cost basis is scaled down by the sold fraction, the high-water mark is reset+to the remaining bag, and `initials_recovered` flips.++**Falling, from the peak to the final quote.** Whichever protective trigger sits+highest is the one hit first on the way down. Whatever is still riding at the end+is valued at the last price the fleet actually observed, never at a guess about+what came after.++Every decision in both phases is made by calling `decideLadderedExit` with a+position-like object using the live column names. The replay does not+reimplement the exit rules; it feeds production code and reads the answer. The+two can therefore never drift.++---++## What it can and cannot tell you++This is the part that matters. A counterfactual tool that overstates itself is+worse than no tool, so the limits are on the page, not buried in a footnote.++**Every trade is real.** The corpus is closed positions with an on-chain buy+signature that is not the `SIMULATED` sentinel. Paper fills cannot enter it.++**Compare replays to replays, not to the ledger.** The replay prices an exit at+the quote the fleet recorded. It does not model slippage, priority fees or the+spread actually paid. Replaying the live policy will therefore **not** reproduce+the booked number, and it is not supposed to. The gap between two replays is the+signal; the gap between a replay and the ledger is execution cost.++**Exiting earlier is exact. Holding longer is a floor.** The recorded path stops+where the real policy sold. A counterfactual that would have kept holding runs+out of observations there, so its result is a lower bound and never an upper one.+The page reports how many trades are bounded this way under the current policy.++**Some positions are excluded, and it says which.** A position whose initials+were already taken has had its cost basis scaled down and its high-water mark+reset by the partial-sell path, so its recorded points describe the moon bag+rather than the original position. Replaying it would produce a confident number+computed from figures that no longer mean what they look like. Those rows are+dropped with a stated reason and counted, so you always know what fraction of+the fleet's history the answer covers.++**An in-sample optimum is not a forecast.** The search finds the policy that+would have paid best on trades that already happened. Under about 30 closed+positions a grid of this size will always find a flattering corner of noise, and+the page says so instead of letting a leader row read as a recommendation.++---++## The API++```+GET /api/sniper/exit-lab?network=mainnet&window=all&limit=500+```++Public and IP rate-limited, like the leaderboard. The tx signatures are the+proof, so anyone can check the fleet's homework.++`network` is `mainnet` (default) or `devnet`. `window` is `7`, `30`, `90`+(default) or `all` days. `limit` caps at 500.++```bash+curl -s 'https://three.ws/api/sniper/exit-lab?window=all&limit=5' | jq '{replayable, scanned, excluded, first: .trades[0]}'+```++```json+{+ "replayable": 234,+ "scanned": 239,+ "excluded": [+ {+ "key": "laddered",+ "count": 5,+ "reason": "Initials were already taken, so the recorded cost basis and high-water mark describe the moon bag, not the original position."+ }+ ],+ "first": {+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "symbol": "THREE",+ "entryLamports": 20000000,+ "peakLamports": 20000000,+ "terminalLamports": 18154034,+ "actualPnlLamports": -498908,+ "actualReason": "timeout",+ "buyUrl": "https://solscan.io/tx/..."+ }+}+```++The replay itself runs in the browser, against the same kernel the server+imports. That is why a slider move is instant: the server has no better claim to+the answer than the client does, so it ships the facts and the client does the+arithmetic.++---++## Using the kernel yourself++`api/_lib/exit-replay.js` is pure. No I/O, no clock, no Node built-ins. Import it+from a script, a worker or a browser bundle.++```js+import { replayFleet, sweepParams, DEFAULT_PARAMS, toSol } from './api/_lib/exit-replay.js';++const res = await fetch('https://three.ws/api/sniper/exit-lab?window=all&limit=500');+const { trades } = await res.json();++// What the live policy would have returned over this corpus.+const live = replayFleet(trades, DEFAULT_PARAMS);+console.log(`${live.trades} trades, ${toSol(live.pnlLamports).toFixed(4)} SOL, ${live.roiPct}% ROI`);+console.log(`actually booked: ${toSol(live.actual.pnlLamports).toFixed(4)} SOL`);++// Search a grid for something better.+const search = sweepParams(trades, {+ stopLossPct: [10, 15, 20, 25, 35, 50, null],+ trailingStopPct: [10, 15, 25, 40, null],+ initialsOutMultiple: [1.5, 2, 3, null],+}, { limit: 5 });++for (const leader of search.leaders) {+ console.log(toSol(leader.pnlLamports).toFixed(4), 'SOL', JSON.stringify(leader.params));+}+if (search.overfitRisk) console.log('corpus is too thin to lean on these');+```++`replayFleet` returns aggregate metrics plus a `rows` array with one entry per+replayed position, each carrying `bounded` (still holding at the end of the+recorded path) and `keptMoonbag` so a caller can filter on the same honesty+signals the page shows.++---++## Sharing a finding++The console writes the current policy into the query string, so any state of the+page is a link. `https://three.ws/exit-lab?stopLossPct=15&trailingStopPct=10&takeProfitPct=off&initialsOutMultiple=2&moonbagMinPct=15`+opens with that exact policy applied. A hand-edited value out of range is clamped+to the nearest legal one rather than throwing.++---++## Related++- [Agent Sniper](agent-sniper.md), the worker whose positions this replays+- [Autonomous Trading hub](trading-hub.md), the front door to every trading surface+- [Trading experiment](trading-experiment.md), the policy this fleet runs and why+- [Read the trading fleet](tutorials/read-the-trading-fleet.md), how to interpret fleet vitals+- Tutorial: [Find a better exit policy](tutorials/find-a-better-exit-policy.md)diff --git a/docs/tutorials/find-a-better-exit-policy.md b/docs/tutorials/find-a-better-exit-policy.mdnew file mode 100644index 000000000..0cc33c0f8--- /dev/null+++ b/docs/tutorials/find-a-better-exit-policy.md@@ -0,0 +1,231 @@+# Find a Better Exit Policy From Trades You Already Made++Most trading advice is about entries. Most losses are about exits.++Entries are the visible decision, so they get the attention. But a fleet that+buys the same coins and sells them differently produces wildly different results,+and the exit rules are the cheapest thing in the whole system to change. You do+not need a new signal or a faster feed. You need to move a number.++The problem is knowing which number, and by how much. Opinions about stop-losses+are free and mostly worthless. What you actually want is the boring version:+**take the trades you already made and re-run them under different rules.**++That is [/exit-lab](/exit-lab). By the end of this tutorial you will have found a+policy that beats the one the fleet is running, understood exactly how much of+that finding you are allowed to believe, and known which part of it is a real+result and which part is noise wearing a suit.++Nothing here requires an agent, a wallet or a login. The corpus is public and+every trade in it is a signed transaction anyone can verify.++**What you will learn:**++- Why "what would this have returned" is a different question from "would this have worked"+- How to read the one number that tells you a counterfactual is trustworthy+- Why a policy that looks 3x better on the grid may be worth nothing+- Which of the five exit knobs actually moves the result, and which are theater+- How to turn a finding into a change you can defend++---++## Step 1: See what the fleet actually did++Open [/exit-lab](/exit-lab). The page loads every closed position the fleet+opened with real SOL and settled on-chain, then replays them under the live+policy, which is the state the page opens in.++Read the verdict card first. It has three numbers:++- **Net result** over N real trades, in SOL+- **ROI**, that net against the SOL actually staked+- **Actually booked**, from the ledger++You can get the same corpus without the page:++```bash+curl -s 'https://three.ws/api/sniper/exit-lab?window=all&limit=500' \+ | jq '{scanned, replayable, excluded: [.excluded[].key]}'+```++```json+{+ "scanned": 239,+ "replayable": 234,+ "excluded": ["laddered"]+}+```++**The first thing to notice is that "net result" and "actually booked" are not+the same number, and they are not supposed to be.**++This trips people up, so it is worth being blunt about. The replay prices an exit+at the quote the fleet recorded. Real exits pay slippage, priority fees and the+spread. The difference between the replay of the live policy and the booked+figure is roughly what execution cost, and it is real money, but it is not the+thing this page is measuring.++So: **compare replays to replays.** Never compare a replay to the ledger and call+the difference a finding.++---++## Step 2: Change one thing++Drag the **Hard stop-loss** slider from 35% down to 15%.++Watch the delta on the right of the verdict card. It now reads a signed SOL+figure "versus the live policy over the same trades". That is a replay-to-replay+comparison, which is the honest one.++Now put it back and try the **Trailing stop** instead. Then the **Take initials+at** multiple.++You will notice quickly that the five knobs are not equally interesting. On a+corpus dominated by positions that never went green, the trailing stop and the+take-initials ladder barely register, because neither rule can fire on a coin+that never rose above cost. The hard stop-loss does almost all the work. That is+not a quirk of the tool, it is a fact about the fleet's trades, and it is the+first genuinely useful thing the page tells you.++The `?` next to each label opens a plain-language explanation of what that rule+does and when it can fire. Read the one for the trailing stop: the detail that it+only arms once a position has been green is the reason it does nothing on a+losing corpus, and it is also the reason it is safe.++---++## Step 3: Read the honesty numbers before you believe anything++Scroll to **What this can and cannot tell you**. Two lines there decide how much+of your finding survives contact with reality.++**"Exiting earlier is exact; holding longer is a floor."** The recorded price+path stops where the real policy sold. A counterfactual that would have kept+holding runs out of observations at that point, so its result is valued at the+last price the fleet saw. That is a lower bound, never an upper one.++This has a sharp practical consequence:++- A policy that is **tighter** than the live one (smaller stop, tighter trail)+ exits earlier on almost every trade. Its number is essentially exact.+- A policy that is **looser** (wider stop, no trail) holds longer. Its number is+ a floor, and the true answer could be better or, more often, much worse.++**So a tight policy that beats the live one is a real finding. A loose policy+that beats the live one is a hypothesis.** The page tells you which you are+looking at: the bounded-trade count in that same section is how many positions+were still holding when the observations ran out.++The second line to read is the excluded count. Positions whose initials were+already taken cannot be replayed, because the partial sell rewrote their cost+basis and high-water mark to describe the moon bag instead of the original+position. Those rows are dropped and counted. If that count is a large share of+the corpus, your answer covers a small share of the fleet's history.++---++## Step 4: Search the grid++Press **Run the search**.++The page replays the entire corpus against every combination on a grid of exit+policies. This is an exact enumeration, not a sample and not an optimizer: every+policy on the grid is genuinely replayed against every trade. The progress bar+counts real completed policies.++The result is a ranked table. Each row has the policy, the net SOL, the ROI, the+win rate and the max drawdown, plus an **Apply** button that loads it into the+sliders so you can inspect it.++Now the important part. Read the leaders in this order:++1. **Drawdown before profit.** The deepest fall from a high-water mark is what+ decides whether a policy is survivable. A policy that makes more money through+ a drawdown you would have turned off halfway is not a policy you can run.+2. **Is it tighter or looser than live?** Tighter means the number is close to+ exact (Step 3). Looser means it is a floor.+3. **How far apart are the top rows?** If the top eight policies are within a few+ thousandths of a SOL of each other, you have found a plateau, which is good+ news: the result is not balanced on one lucky setting. If the top row is far+ ahead of the second, be suspicious.++If the corpus has fewer than about 30 closed positions the page replaces the+explanatory note with a warning, because a grid this size will always find a+flattering corner of noise in a small sample. Believe the warning.++---++## Step 5: Check the finding trade by trade++A grid result is an aggregate, and aggregates hide their sources. Scroll to+**Trade by trade** with your candidate policy applied.++The default sort is **biggest divergence**: the positions where the counterfactual+disagrees most with what the fleet really did. Read the top five.++You are looking for one specific failure mode. If the entire improvement comes+from two or three positions, you have not found a better policy, you have found a+policy that happened to catch a couple of specific coins. Real findings are+spread across the corpus. A policy whose delta is concentrated in the tail will+not repeat.++Every row links the buy and the sell to Solscan. Click one. The transaction is+signed by the agent's own key and the amounts are on-chain. This is what+separates the exercise from a spreadsheet: you can verify that the trade being+replayed happened.++---++## Step 6: Share it, then argue with it++Press **Copy a link to this policy**. The URL carries every slider value, so+anyone opening it sees exactly the state you were looking at:++```+https://three.ws/exit-lab?stopLossPct=15&trailingStopPct=10&takeProfitPct=off&initialsOutMultiple=2&moonbagMinPct=15+```++That link is the unit of a useful argument about exits. Instead of "I think the+stop is too wide", you can send a page that shows what a tighter stop would have+returned over 234 real trades, with the caveats attached and the underlying+transactions one click away.++If you run your own agent, the same parameters are what+[`/api/sniper/strategy`](../api-reference.md) accepts, so a finding here maps+directly onto a strategy you can arm. Read+[Arm an autonomous sniper](/tutorials/arm-an-agent-sniper) for that path, and+size it small first: an in-sample optimum is a description of the past, and the+past does not have to repeat.++---++## What to take away++The honest summary of this whole exercise is short.++**Tightening the exits is measurable.** The recorded path fully determines what+an earlier exit would have returned, so a tight-policy improvement is a fact+about trades that happened.++**Loosening the exits is not.** The moment a policy would have held past the+point the fleet sold, the data stops and the number becomes a floor.++**The knob that matters is the one that can fire.** On a corpus of coins that+mostly never went green, the stop-loss is the whole game and the trailing stop is+decoration. On a corpus with real winners in it, that reverses. Look at which+rules actually fired before deciding which one to tune.++And the general version, which outlives this particular page: a counterfactual+tool is only worth anything if it tells you where it stops being reliable. The+bounded-trade count, the excluded-position count and the overfit warning are not+disclaimers bolted onto the result. They are the result.++---++## Related++- [Exit Lab reference](/docs/exit-lab), the method and the API in full+- [Read the trading fleet](/tutorials/read-the-trading-fleet), how to tell a working strategy from a lucky one+- [Arm an autonomous sniper](/tutorials/arm-an-agent-sniper), from finding to armed strategy+- [Agent Sniper](/docs/agent-sniper), the worker whose positions this replaysdiff --git a/pages/exit-lab.html b/pages/exit-lab.htmlindex 679dfbd65..f0c7980c6 100644--- a/pages/exit-lab.html+++ b/pages/exit-lab.html@@ -33,7 +33,7 @@/><metaproperty="og:image"- content="https://three.ws/api/page-og?s=crypto&t=Exit+Lab&d=Replay+the+fleet%27s+real+closed+trades+under+a+different+exit+policy.+Real+positions%2C+real+on-chain+fills%2C+no+synthetic+data.&p=%2Fexit-lab"+ content="https://three.ws/api/page-og?s=crypto&t=Exit+Lab&d=Replay+the+fleet%27s+real+closed+trades+under+a+different+exit+policy.+Move+the+stop-loss%2C+trailing+stop%2C+take-initials+ladder+and+moon-bag+floor+and+see+what&p=%2Fexit-lab"/><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" />@@ -48,7 +48,7 @@/><metaname="twitter:image"- content="https://three.ws/api/page-og?s=crypto&t=Exit+Lab&d=Replay+the+fleet%27s+real+closed+trades+under+a+different+exit+policy.&p=%2Fexit-lab"+ content="https://three.ws/api/page-og?s=crypto&t=Exit+Lab&d=Replay+the+fleet%27s+real+closed+trades+under+a+different+exit+policy.+Move+the+stop-loss%2C+trailing+stop%2C+take-initials+ladder+and+moon-bag+floor+and+see+what&p=%2Fexit-lab"/><meta name="theme-color" content="#09090b" /><link rel="icon" href="/favicon.ico" sizes="any" />diff --git a/src/exit-lab.css b/src/exit-lab.cssindex 45f19004d..f9092d964 100644--- a/src/exit-lab.css+++ b/src/exit-lab.css@@ -1,4 +1,4 @@-/* /exit-lab — the counterfactual exit console.+/* /exit-lab: the counterfactual exit console.** Layered on /src/coin-pages.css (.cv-container, .cv-h1, .cv-sub, .cv-section,* .cv-crumbs). Everything is namespaced .xl-* so it cannot leak into the shared@@ -616,6 +616,24 @@background: color-mix(in srgb, var(--color-danger) 6%, transparent);}+/* Loading is a skeleton of the layout that is coming, not a spinner: the shapes+ below match the verdict card, the curve and the metric row, so nothing jumps+ when the real numbers land. */+.xl-state-loading {+ border-style: dashed;+}++/* Empty is a real state with somewhere to go. The fleet has genuinely not closed+ a replayable position yet, and the copy says what would change that. */+.xl-state-empty {+ border-style: dashed;+}++.xl-state-empty a,+.xl-state-error a {+ color: var(--color-text-bright);+}+.xl-skeleton {height: 1.25rem;border-radius: var(--radius-sm);diff --git a/src/exit-lab.js b/src/exit-lab.jsindex 43cc06c9b..55be5d66d 100644--- a/src/exit-lab.js+++ b/src/exit-lab.js@@ -1,4 +1,4 @@-// /exit-lab — counterfactual replay of the fleet's real closed positions.+// /exit-lab: counterfactual replay of the fleet's real closed positions.//// The corpus comes from /api/sniper/exit-lab (real on-chain closed positions,// nothing simulated). The replay runs HERE, in the browser, against the samediff --git a/tests/exit-replay.test.js b/tests/exit-replay.test.jsindex 428b78934..d3266438b 100644--- a/tests/exit-replay.test.js+++ b/tests/exit-replay.test.js@@ -259,7 +259,7 @@ describe('PARAM_SPECS', () => {expect(spec.min).toBeLessThan(spec.max);expect(spec.step).toBeGreaterThan(0);expect(spec.help.length).toBeGreaterThan(40);- expect(spec.help).not.toMatch(/—|–/); // the repo's dash ban applies to UI copy+ expect(spec.help).not.toMatch(/[\u2013\u2014]/); // the repo dash ban applies to UI copy}});