stray-mcp 0.1.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,31 +1,64 @@
1
1
  #!/usr/bin/env node
2
2
  // Stray MCP server: the Stray API (https://stray.fi/docs) as read-only tools for Claude, Cursor or any MCP client.
3
- // Runs over stdio. Needs STRAY_API_KEY (a key from https://stray.fi/console). Every tool call is one API call.
3
+ // Runs over stdio. Needs STRAY_API_KEY (a key from https://stray.fi/console). Most tools make one API call; the composed
4
+ // tools (stray_book_check, stray_unusual, stray_brief) say in their description how many they make, and report it.
5
+ import { readFileSync } from "node:fs";
4
6
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
7
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
8
  import { z } from "zod";
7
9
 
10
+ const VERSION = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version;
8
11
  const BASE = (process.env.STRAY_BASE_URL || "https://stray.fi/v1").replace(/\/+$/, "");
12
+ if (!/^https:\/\/|^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?\//.test(BASE + "/")) throw new Error("STRAY_BASE_URL must be https:// (or http://localhost for testing).");
9
13
  const KEY = process.env.STRAY_API_KEY;
14
+ const KEY_BAD = KEY && /[\s\x00-\x1f\x7f]/.test(KEY);
15
+ const scrub = (msg) => (KEY ? String(msg).split(KEY).join("[key]") : String(msg));
10
16
  const CORE = ["BTC", "ETH", "HYPE", "SOL", "XRP", "DOGE", "BNB", "SUI"];
11
17
  const HOUR = 3600e3;
12
18
  const MAX_ROWS = 200;
19
+ const BANDS = ["0.5%", "1%", "2%"];
20
+ const LIQ_SAMPLE = "the top 1,500 Hyperliquid accounts by account value; not every position";
13
21
 
14
- async function get(path, params = {}) {
15
- if (!KEY) throw new Error("STRAY_API_KEY is not set. Make a key at https://stray.fi/console and add it to this server's env.");
16
- const url = new URL(BASE + path);
17
- for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
18
- const res = await fetch(url, { headers: { authorization: `Bearer ${KEY}`, "user-agent": "stray-mcp/0.1" } });
19
- const body = await res.json().catch(() => ({}));
20
- if (!res.ok) {
21
- const wait = res.headers.get("retry-after");
22
- throw new Error(`Stray API ${res.status}: ${body.error || res.statusText}${wait ? ` Retry after ${wait} s.` : ""}`);
23
- }
24
- return body;
22
+ // One API client per tool call, so a composed tool can report how many calls it made. Slow-moving reads (the hour
23
+ // profile, crowding, the liquidation map, the Draw) are cached for 60 s across calls; a cache hit costs no quota.
24
+ const CACHE = new Map();
25
+ const CACHED = /^\/(profile|crowding|liqmap|draw)(\/|$)/;
26
+ function client() {
27
+ const api = { calls: 0 };
28
+ api.get = async (path, params = {}) => {
29
+ if (!KEY) throw new Error("STRAY_API_KEY is not set. Make a key at https://stray.fi/console and add it to this server's env.");
30
+ if (KEY_BAD) throw new Error("STRAY_API_KEY contains a space or line break. Copy it again from https://stray.fi/console.");
31
+ const url = new URL(BASE + path);
32
+ for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
33
+ const base = new URL(BASE);
34
+ if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname + "/")) throw new Error("Refused: that request would leave the Stray API.");
35
+ const hit = CACHED.test(path) && CACHE.get(url.href);
36
+ if (hit && Date.now() - hit.at < 60e3) return hit.body;
37
+ api.calls++;
38
+ const res = await fetch(url, { headers: { authorization: `Bearer ${KEY}`, "user-agent": `stray-mcp/${VERSION}` } });
39
+ const body = await res.json().catch(() => null);
40
+ if (res.ok && (body === null || typeof body !== "object")) throw new Error("The Stray API answered with something that isn't JSON (a proxy or captive portal?). Nothing was read.");
41
+ if (!res.ok) {
42
+ const wait = res.headers.get("retry-after");
43
+ throw new Error(`Stray API ${res.status}: ${body?.error || res.statusText}${wait ? ` Retry after ${wait} s.` : ""}`);
44
+ }
45
+ if (CACHED.test(path)) {
46
+ for (const [k, v] of CACHE) if (Date.now() - v.at >= 60e3) CACHE.delete(k); // keep only what can still be served
47
+ CACHE.set(url.href, { at: Date.now(), body });
48
+ }
49
+ return body;
50
+ };
51
+ return api;
25
52
  }
26
53
 
27
- // Time series come back as {fields, rows: [[...]]} or {rows: [{...}]}. Turn them into at most MAX_ROWS objects,
28
- // one per `step` minutes, newest last, so a model reads named values and the reply stays small.
54
+ const iso = (t) => (Number.isFinite(t) ? new Date(t).toISOString() : null);
55
+ const round = (x, d = 4) => (Number.isFinite(x) ? Number(x.toFixed(d)) : null);
56
+ const sig = (x, s = 6) => (Number.isFinite(x) ? Number(x.toPrecision(s)) : null);
57
+ const sum = (xs) => xs.reduce((a, b) => a + (Number.isFinite(b) ? b : 0), 0);
58
+
59
+ // Time series come back as {fields, rows: [[...]]} or {rows: [{...}]}. Turn them into at most `keep` objects,
60
+ // one per `step` minutes, newest last, so a model reads named values and the reply stays small. `all` keeps every
61
+ // row (before trimming) for summaries.
29
62
  function series(body, { step, keep = MAX_ROWS } = {}) {
30
63
  const { fields, rows = [], ...rest } = body;
31
64
  let objs = fields ? rows.map((r) => Object.fromEntries(fields.map((f, i) => [f, r[i]]))) : rows;
@@ -33,113 +66,475 @@ function series(body, { step, keep = MAX_ROWS } = {}) {
33
66
  const seen = new Set();
34
67
  objs = objs.filter((o) => { const b = Math.floor(o.t / (step * 60e3)); if (seen.has(b)) return false; seen.add(b); return true; });
35
68
  }
36
- const shown = objs.slice(-keep).map((o) => ({ ...o, time: new Date(o.t).toISOString() }));
37
- return { ...rest, rows: shown, rows_total: objs.length, ...(objs.length > shown.length ? { rows_note: `Showing the newest ${shown.length}. Use a larger step for a longer span.` } : {}) };
69
+ const shown = objs.slice(-keep).map((o) => ({ ...o, time: iso(o.t) }));
70
+ const out = { ...rest, rows: shown, rows_total: objs.length, ...(objs.length > shown.length ? { rows_note: `Showing the newest ${shown.length} of ${objs.length}. Narrow the window, or use a larger step where the tool has one.` } : {}) };
71
+ Object.defineProperty(out, "all", { value: objs, enumerable: false });
72
+ return out;
73
+ }
74
+
75
+ // The window a series tool reads: `hours` back from `end` (default now). A window that ends before the record for
76
+ // that series starts is an error that names the start; one in the future is refused.
77
+ const endArg = z.iso.datetime({ offset: true }).optional()
78
+ .describe("End of the window, ISO 8601 UTC (e.g. 2026-11-25T14:00:00Z). Default now. Set it to read a past window.");
79
+ function span(hours, end) {
80
+ const now = Date.now();
81
+ let to = Math.ceil(now / 60e3) * 60e3; // "now", rounded up to the minute so repeat reads can share the cache
82
+ if (end) {
83
+ to = Date.parse(end);
84
+ if (!Number.isFinite(to)) throw new Error("end must be an ISO 8601 time, e.g. 2026-11-25T14:00:00Z.");
85
+ if (to > now + 60e3) throw new Error("end is in the future. Stray records what markets have done.");
86
+ }
87
+ return { from: Math.round(to - hours * HOUR), to: Math.round(to) };
88
+ }
89
+ const windowOf = (sp) => ({ from: iso(sp.from), to: iso(sp.to) });
90
+ function checkEmpty(out, sp) {
91
+ if (out.rows_total) return out;
92
+ const since = Date.parse(out.recording_since ?? "");
93
+ if (Number.isFinite(since) && sp.to < since) throw new Error(`That window ends before Stray's record of it starts (${out.recording_since}).`);
94
+ return { ...out, rows_note: "No rows in this window." };
38
95
  }
39
96
 
40
- const span = (hours) => { const to = Date.now(); return { from: to - hours * HOUR, to }; };
41
97
  const coreCoin = z.enum(CORE).describe("A core market: " + CORE.join(", "));
42
- const anyCoin = z.string().describe('A core market (e.g. "BTC") or a HIP-3 market by its full name (e.g. "xyz:NVDA"; see stray_markets)');
98
+ // Market names only: letters and digits, optionally "dex:NAME". Anything path-shaped never reaches the URL.
99
+ const anyCoin = z.string().regex(/^([A-Za-z0-9]{1,20}|[A-Za-z0-9]{1,12}:[A-Za-z0-9]{1,20})$/, "a market name like BTC or xyz:NVDA")
100
+ .describe('A core market (e.g. "BTC") or a HIP-3 market by its full name (e.g. "xyz:NVDA"; see stray_markets)');
101
+ const market = (c) => (c.includes(":") ? c.replace(/^[^:]+/, (d) => d.toLowerCase()) : CORE.includes(c.toUpperCase()) ? c.toUpperCase() : c);
43
102
  const hours = (def, max) => z.number().min(0.2).max(max).default(def).describe(`How many hours back, up to ${max}. Default ${def}.`);
44
103
  const step = (def) => z.number().int().min(1).max(1440).default(def).describe(`Minutes between rows. Default ${def}.`);
45
104
 
46
105
  const server = new McpServer(
47
- { name: "stray", version: "0.1.0" },
106
+ { name: "stray", version: VERSION },
48
107
  {
49
108
  instructions:
50
109
  "Stray records Hyperliquid perp markets: order-book depth, funding, open interest, flow, whale positioning and liquidation levels, " +
51
110
  "plus the same markets on Binance, Bybit and OKX. Core markets: " + CORE.join(", ") + ". " +
111
+ "Where to start: 'how crowded is the exit', 'can the book take $X' or 'is the book thin' → stray_book_check; " +
112
+ "'is this move unusual' → stray_unusual; 'what is stretched' → stray_brief, then stray_draw with a coin; " +
113
+ "'are positions being opened or closed' → stray_oi_change; 'is the funding gap between venues real' → stray_funding_venues; " +
114
+ "'what happened during that move' → stray_history, stray_flow or stray_liquidity with `end`. " +
115
+ "Every result starts with as_of and source: give the time of every number you quote and what it is compared with. " +
52
116
  "Fractions are decimals (-0.1379 = -13.79%); times are UTC; USD values are US dollars. " +
53
- "Everything describes the past or the present. Nothing here is a forecast or advice, so don't present it as one. " +
54
- "Each tool call costs one call from the user's monthly quota; prefer stray_draw for a quick read of the whole market.",
117
+ "Everything describes the past or the present. Nothing here is a forecast or advice: if asked what a price will do, " +
118
+ "say Stray records what markets have done and give the current readings. Report readings and their comparisons; don't argue what they " +
119
+ "imply for price, which way a squeeze or flush would go, or what would have to change for one. " +
120
+ "Most tools cost one call from the user's monthly quota; the composed tools say how many they make.",
55
121
  },
56
122
  );
57
123
 
58
- function tool(name, title, description, inputSchema, run) {
124
+ // Every result starts with when it is from and where it comes from, then the window and the norm where there is one.
125
+ function envelope(r, source) {
126
+ const { as_of, source: own, window, norm, ...rest } = r;
127
+ const rows = Array.isArray(rest.rows) ? rest.rows : null;
128
+ const at = as_of ?? (Number.isFinite(rest.t) ? iso(rest.t) : rows?.length ? rows[rows.length - 1].time : new Date().toISOString());
129
+ const src = typeof source === "function" ? source(r) : (own && typeof own === "string" && own.length > 8 ? own : source);
130
+ return { as_of: at, source: src, ...(window ? { window } : {}), ...(norm ? { norm } : {}), ...rest };
131
+ }
132
+
133
+ function tool(name, title, description, inputSchema, source, run) {
59
134
  server.registerTool(name, { title, description, inputSchema, annotations: { readOnlyHint: true, openWorldHint: true } }, async (args) => {
60
- try { return { content: [{ type: "text", text: JSON.stringify(await run(args)) }] }; }
61
- catch (e) { return { content: [{ type: "text", text: e.message }], isError: true }; }
135
+ const api = client();
136
+ try {
137
+ const out = envelope(await run(args, api), source);
138
+ if (api.calls > 1) out.api_calls = api.calls;
139
+ return { content: [{ type: "text", text: JSON.stringify(out) }] };
140
+ } catch (e) {
141
+ const spent = api.calls ? ` (${api.calls} API call${api.calls > 1 ? "s" : ""} used)` : "";
142
+ return { content: [{ type: "text", text: scrub(e.message) + spent }], isError: true };
143
+ }
62
144
  });
63
145
  }
64
146
 
147
+ // ── single-endpoint tools ───────────────────────────────────────────────────────────────────────────────────────
148
+
65
149
  tool("stray_markets", "Markets", "The markets Stray covers, the HIP-3 (builder-deployed) markets it records, and when recording began.", {},
66
- () => get("/markets"));
150
+ "Stray", (_, api) => api.get("/markets"));
67
151
 
68
- tool("stray_draw", "The Draw", "The Draw: how tense a market is right now against its own history, 0 (calm) to 100 (stressed), with its band " +
152
+ tool("stray_draw", "The Draw", "The Draw: how tense a market is against its own history, 0 (calm) to 100 (stressed), with its band " +
69
153
  "(Sheathed, Resting, Hand on hilt, Drawing, Drawn). Without a coin: the whole market, each core market's reading and their weights. " +
70
- "With a coin: the seven components (vol, thin, crowding, funding, liquidation, positioning, flow) and the inputs behind them. Updated every 10 minutes.",
71
- { coin: coreCoin.optional().describe("A core market. Leave out for the whole market."), hours: hours(24, 24 * 30) },
72
- async ({ coin, hours: h }) => {
73
- const b = await get(coin ? `/draw/${coin}` : "/draw", { ...span(h), step: h > 72 ? 1440 : 60 });
74
- const { history, history_step_min, ...rest } = b;
75
- return { ...rest, history: series({ fields: ["t", "draw"], rows: history }).rows.map(({ time, draw }) => ({ time, draw })), history_step_min };
154
+ "With a coin: the seven components (vol, thin, crowding, funding, liquidation, positioning, flow) and the inputs behind them. " +
155
+ "Start here for 'what is stretched on this market'. Components are measured conditions, each ranked against its own history, " +
156
+ "not a call on what comes next. Updated every 10 minutes. With `end`, the reading nearest before that time (as_of says when; keep hours at 24 " +
157
+ "or less for one within 10 minutes); without a coin, the per-market readings are today's only, so they are left out of a past reading.",
158
+ { coin: coreCoin.optional().describe("A core market. Leave out for the whole market."), hours: hours(24, 24 * 30), end: endArg },
159
+ "Stray's Draw, computed every 10 minutes from the record",
160
+ async ({ coin, hours: h, end }, api) => {
161
+ const sp = span(h, end);
162
+ const st = end ? (h <= 24 ? 10 : h <= 72 ? 60 : 1440) : (h > 72 ? 1440 : 60);
163
+ const b = await api.get(coin ? `/draw/${coin}` : "/draw", { ...sp, step: st });
164
+ let { history, history_step_min, markets, ...rest } = b;
165
+ const past = end && Date.now() - sp.to > 30 * 60e3;
166
+ if (!past && markets) rest.markets = markets;
167
+ if (past && !coin) rest.markets_note = "Per-market readings exist for now only; ask stray_draw with each coin and the same end for the past.";
168
+ if (end && Number.isFinite(rest.t) && sp.to - rest.t > 15 * 60e3) rest.reading_note = `The reading is from ${iso(rest.t)}, the first row of the last ${st}-minute step before end.`;
169
+ return { ...rest, window: windowOf(sp), history: series({ fields: ["t", "draw"], rows: history }).rows.map(({ time, draw }) => ({ time, draw })), history_step_min };
76
170
  });
77
171
 
78
172
  tool("stray_ranges", "Past ranges", "How far the market moved over past windows of the same length: percentiles (p10 to p90) of the move, and where the " +
79
- "latest window sits. Past ranges, not a forecast.", { coin: coreCoin, window: z.union([1, 3, 7, 14, 30, 60, 90].map((n) => z.literal(n))).default(7).describe("Days: 1, 3, 7, 14, 30, 60 or 90. Default 7.") },
80
- ({ coin, window }) => get(`/ranges/${coin}`, { window }));
173
+ "latest window sits. Past ranges, not a forecast. For 'is this move unusual' across several windows at once, use stray_unusual.",
174
+ { coin: coreCoin, window: z.union([1, 3, 7, 14, 30, 60, 90].map((n) => z.literal(n))).default(7).describe("Days: 1, 3, 7, 14, 30, 60 or 90. Default 7.") },
175
+ "Hyperliquid daily closes", ({ coin, window }, api) => api.get(`/ranges/${coin}`, { window }));
81
176
 
82
177
  tool("stray_depth", "Order-book depth", "US dollars resting on each side of the live Hyperliquid book within ±0.5%, ±1% and ±2% of mid. Updated every 5 seconds. " +
83
- "To say whether that is thin or deep for the time of day, compare the ±1% total with stray_profile for the current UTC hour.",
84
- { coin: anyCoin }, ({ coin }) => get(`/depth/${coin}`));
178
+ "Answers 'how deep is the book'. For 'is that thin for the hour' or 'can it take $X', use stray_book_check.",
179
+ { coin: anyCoin },
180
+ (r) => (r.source === "live" ? "Hyperliquid live book" : "Stray's record, last minute (the live book did not answer)"),
181
+ async ({ coin }, api) => { const b = await api.get(`/depth/${market(coin)}`); return b.source === "live" ? b : { ...b, stale: true }; });
85
182
 
86
183
  tool("stray_funding", "Funding", "Funding on Hyperliquid (hourly, since listing), Binance or Bybit (every 8 hours). The summary ranks the latest rate " +
87
- "against all history, with the annualized rate; recent rows follow.",
88
- { coin: coreCoin, venue: z.enum(["hyperliquid", "binance", "bybit"]).default("hyperliquid"), hours: hours(24, 24 * 366) },
89
- async ({ coin, venue, hours: h }) => series(await get(`/funding/${coin}`, { venue, ...span(h) }), { keep: 48 }));
184
+ "against all history, gives the annualized rate, who pays whom, what it costs per $10,000 of position per day, the sum over the window, " +
185
+ "and how many hours the rate has kept its sign; recent rows follow. Positive = longs pay shorts.",
186
+ { coin: coreCoin, venue: z.enum(["hyperliquid", "binance", "bybit"]).default("hyperliquid"), hours: hours(24, 24 * 366), end: endArg },
187
+ (r) => `${r.venue === "hyperliquid" || !r.venue ? "Hyperliquid" : r.venue[0].toUpperCase() + r.venue.slice(1)} settled funding`,
188
+ async ({ coin, venue, hours: h, end }, api) => {
189
+ const sp = span(h, end);
190
+ const s = series(await api.get(`/funding/${coin}`, { venue, ...sp }), { keep: 48 });
191
+ const per = s.interval_hours ?? 1; // rows are per settlement period; the summary is hourly
192
+ const rated = s.all.filter((o) => Number.isFinite(o.rate ?? o.rate_per_8h));
193
+ const rates = rated.map((o) => o.rate ?? o.rate_per_8h);
194
+ let same = 0;
195
+ for (let i = rates.length - 1; i >= 0 && Math.sign(rates[i]) === Math.sign(rates[rates.length - 1]); i--) same++;
196
+ const lastHourly = rates.length ? rates[rates.length - 1] / per : null; // the window's last settlement, on the hourly scale
197
+ const summary = {
198
+ ...s.summary,
199
+ window_last: rated.length ? { time: iso(rated[rated.length - 1].t), hourly: sig(lastHourly) } : null,
200
+ longs_pay_shorts: lastHourly === null ? null : lastHourly > 0,
201
+ cost_per_10k_usd_per_day: lastHourly === null ? null : round(lastHourly * 24 * 1e4, 2),
202
+ settled_sum_window: round(sum(rates), 8),
203
+ hours_same_sign: rates.length ? same * per : null,
204
+ ...(rates.length && same === rates.length ? { hours_same_sign_note: "Every row in the window has this sign; it may run longer. Widen hours to see." } : {}),
205
+ ...(end ? { summary_note: "latest_* and the percentile describe the most recent settlement, not this window. window_last, longs_pay_shorts, cost_per_10k_usd_per_day, settled_sum_window and hours_same_sign all follow the window." } : {}),
206
+ };
207
+ return { ...checkEmpty(s, sp), venue, window: windowOf(sp), summary };
208
+ });
90
209
 
91
210
  tool("stray_conditional", "When funding was like today", "Every day since 2023 is put into one of ten bands by its average hourly funding. Returns " +
92
- "today's band and the spread of moves over the next N days after past days in that band, beside all days. Past, not a forecast.",
93
- { coin: coreCoin, horizon: z.union([1, 3, 7, 14, 30].map((n) => z.literal(n))).default(7).describe("Days ahead: 1, 3, 7, 14 or 30. Default 7.") },
94
- ({ coin, horizon }) => get(`/conditional/${coin}`, { horizon }));
211
+ "today's band and the spread of moves over the N days that followed past days in that band, beside all days. Past, not a forecast. " +
212
+ "Shows the spread of what followed, beside all days; if the two spreads look alike, say so.",
213
+ { coin: coreCoin, horizon: z.union([1, 3, 7, 14, 30].map((n) => z.literal(n))).default(7).describe("Days after each past day: 1, 3, 7, 14 or 30. Default 7.") },
214
+ "Hyperliquid daily funding and closes since 2023", ({ coin, horizon }, api) => api.get(`/conditional/${coin}`, { horizon }));
95
215
 
96
216
  tool("stray_crowding", "Crowding", "Hyperliquid open interest in USD divided by USD resting within ±1% of mid: dollars of positions per dollar of book. " +
97
- "The latest reading's percentile ranks it against the window.", { coin: coreCoin, hours: hours(168, 168) },
98
- async ({ coin, hours: h }) => series(await get(`/crowding/${coin}`, span(h)), { step: 60, keep: 24 }));
217
+ "The latest reading's percentile ranks it against the window (default and maximum 7 days).", { coin: coreCoin, hours: hours(168, 168), end: endArg },
218
+ "Hyperliquid open interest and live book, from Stray's record",
219
+ async ({ coin, hours: h, end }, api) => {
220
+ const sp = span(h, end);
221
+ const b = await api.get(`/crowding/${coin}`, sp);
222
+ const s = checkEmpty(series(b, { step: 60, keep: 24 }), sp);
223
+ return { ...s, window: windowOf(sp), norm: { what: "every 10-minute reading in this window", period_hours: h, samples: (b.rows ?? []).length } };
224
+ });
99
225
 
100
226
  tool("stray_profile", "The typical day", "What is usual for each hour of the day (UTC): median depth within ±1% (both sides, USD), spread and " +
101
- "Hyperliquid volume per 10 minutes, over the last N days. Use it as the baseline for 'is the book thin right now' and 'when do books thin out'.",
102
- { coin: coreCoin, days: z.number().int().min(1).max(30).default(7) },
103
- ({ coin, days }) => get(`/profile/${coin}`, { days }));
227
+ "Hyperliquid volume per 10 minutes, over the last N days. Adds the current hour's row and the three thinnest and deepest hours. " +
228
+ "Use it as the baseline for 'is the book thin right now' and 'when do books thin out'.",
229
+ { coin: coreCoin, days: z.number().int().min(1).max(30).default(14).describe("Days of record to take medians over, 1 to 30. Default 14.") },
230
+ "Stray's record, medians by UTC hour",
231
+ async ({ coin, days }, api) => {
232
+ const b = await api.get(`/profile/${coin}`, { days });
233
+ const rows = (b.hours_utc ?? []).filter((r) => Number.isFinite(r.depth_1pct_usd));
234
+ const hour = new Date().getUTCHours();
235
+ const by = [...rows].sort((a, c) => a.depth_1pct_usd - c.depth_1pct_usd);
236
+ const pick = (r) => ({ hour_utc: r.hour, depth_1pct_usd: r.depth_1pct_usd });
237
+ return { ...b, current_hour_utc: hour, current_hour: rows.find((r) => r.hour === hour) ?? null,
238
+ thinnest_hours: by.slice(0, 3).map(pick), deepest_hours: by.slice(-3).reverse().map(pick) };
239
+ });
104
240
 
105
241
  tool("stray_venues", "Hyperliquid vs Binance, Bybit, OKX", "The same market on four venues side by side: USD within ±0.05% to ±2% of each venue's mid, " +
106
- "spread, funding and open interest, and Hyperliquid's share of the four venues' depth in the tightest bands.", { coin: coreCoin, hours: hours(1, 168), step: step(10) },
107
- async ({ coin, hours: h, step: s }) => series(await get(`/venues/${coin}`, { ...span(h), step: s }), { keep: 3 }));
242
+ "spread, funding and open interest, and Hyperliquid's share of the four venues' depth in the tightest bands. Each venue is measured against its " +
243
+ "own mid; null means that venue's book doesn't reach the band (Binance and Bybit often stop near ±0.1% for BTC). Funding here is the venue's " +
244
+ "current rate: per hour on Hyperliquid, per 8 hours elsewhere; stray_funding_venues puts them on one scale.",
245
+ { coin: coreCoin, hours: hours(1, 168), step: step(10), end: endArg }, "Hyperliquid, Binance, Bybit and OKX books, from Stray's record",
246
+ async ({ coin, hours: h, step: s, end }, api) => {
247
+ const sp = span(h, end);
248
+ return { ...checkEmpty(series(await api.get(`/venues/${coin}`, { ...sp, step: s }), { keep: 6 }), sp), window: windowOf(sp) };
249
+ });
108
250
 
109
- tool("stray_flow", "Trade flow", "Hyperliquid volume by aggressor side in USD, number of buys and sells, the largest trade, and liquidations on Binance " +
110
- "and Bybit by side (liq_long_usd = longs closed).", { coin: coreCoin, hours: hours(6, 168), step: step(60) },
111
- async ({ coin, hours: h, step: s }) => series(await get(`/flow/${coin}`, { ...span(h), step: s })));
251
+ tool("stray_flow", "Trade flow", "Hyperliquid volume by aggressor side in USD, number of buys and sells, and the largest trade; liquidations on " +
252
+ "Binance and Bybit by side (liq_long_usd = longs closed). Hyperliquid's own liquidations are not in this data. The summary totals the window: " +
253
+ "buy share, net USD, the largest trade and its share, and the liquidation totals.",
254
+ { coin: coreCoin, hours: hours(6, 168), step: step(60), end: endArg },
255
+ "Hyperliquid trades; Binance and Bybit liquidations",
256
+ async ({ coin, hours: h, step: s, end }, api) => {
257
+ const sp = span(h, end);
258
+ const out = checkEmpty(series(await api.get(`/flow/${coin}`, { ...sp, step: s })), sp);
259
+ const all = out.all ?? [];
260
+ const buy = sum(all.map((o) => o.buy_usd)), sell = sum(all.map((o) => o.sell_usd)), big = Math.max(0, ...all.map((o) => o.max_trade_usd ?? 0));
261
+ const summary = all.length ? {
262
+ volume_source: "Hyperliquid", buy_usd: buy, sell_usd: sell, buy_share: round(buy / (buy + sell)), net_usd: buy - sell,
263
+ largest_trade_usd: big, largest_trade_share_of_volume: round(big / (buy + sell), 6),
264
+ liq_source: "Binance and Bybit", liq_long_usd_total: sum(all.map((o) => o.liq_long_usd)), liq_short_usd_total: sum(all.map((o) => o.liq_short_usd)),
265
+ } : null;
266
+ return { ...out, window: windowOf(sp), summary };
267
+ });
112
268
 
113
269
  tool("stray_positioning", "Binance positioning", "Binance's open interest, share of accounts long, top traders' long share and taker buy/sell volume, " +
114
- "every 5 minutes (shown hourly).", { coin: coreCoin, hours: hours(24, 24 * 31) },
115
- async ({ coin, hours: h }) => series(await get(`/positioning/${coin}`, span(h)), { step: 60 }));
270
+ "every 5 minutes (shown hourly by default).", { coin: coreCoin, hours: hours(24, 24 * 31), step: step(60), end: endArg }, "Binance futures data",
271
+ async ({ coin, hours: h, step: s, end }, api) => { const sp = span(h, end); return { ...checkEmpty(series(await api.get(`/positioning/${coin}`, sp), { step: s }), sp), window: windowOf(sp) }; });
116
272
 
117
273
  tool("stray_whales", "Whale positioning", "Open perp positions of the top 1,500 Hyperliquid accounts by account value, totalled per coin: long, short and " +
118
- "net USD, accounts on each side, size-weighted leverage, and HLP's net position. Totals only; no wallets.", { coin: coreCoin, hours: hours(24, 24 * 31), step: step(60) },
119
- async ({ coin, hours: h, step: s }) => series(await get(`/whales/${coin}`, { ...span(h), step: Math.max(10, s) })));
274
+ "net USD, accounts on each side, size-weighted leverage, and HLP's net position. Totals only; no wallets. The summary gives the long share, " +
275
+ "net and gross USD now, and how they changed over 1 hour, 24 hours and 7 days where the window covers it (default window 7 days; rows show the newest 24).",
276
+ { coin: coreCoin, hours: hours(168, 24 * 31), step: step(60), end: endArg }, "Hyperliquid's largest accounts, from Stray's 10-minute sweep",
277
+ async ({ coin, hours: h, step: s, end }, api) => {
278
+ const sp = span(h, end);
279
+ const out = checkEmpty(series(await api.get(`/whales/${coin}`, { ...sp, step: Math.max(10, s) }), { keep: 24 }), sp);
280
+ const all = out.all ?? [];
281
+ const read = (o) => ({ time: iso(o.t), long_share: round(o.long_usd / (o.long_usd + o.short_usd)), net_usd: o.net_usd, gross_usd: o.long_usd + o.short_usd });
282
+ const last = all[all.length - 1];
283
+ const back = (hrs) => {
284
+ const target = last.t - hrs * HOUR;
285
+ const o = all.reduce((best, x) => (Math.abs(x.t - target) < Math.abs(best.t - target) ? x : best), all[0]);
286
+ if (o === last || Math.abs(o.t - target) > Math.max(0.1 * hrs * HOUR, 30 * 60e3)) return null; // the window must reach back that far
287
+ const a = read(o), b = read(last);
288
+ return { from: a.time, long_share_from: a.long_share, long_share_change: round(b.long_share - a.long_share), net_usd_from: a.net_usd, net_usd_change: b.net_usd - a.net_usd };
289
+ };
290
+ const summary = last ? { now: read(last), change: { "1h": back(1), "24h": back(24), "7d": back(168) } } : null;
291
+ return { ...out, window: windowOf(sp), summary };
292
+ });
120
293
 
121
294
  tool("stray_liqmap", "Liquidation map", "Where the top Hyperliquid accounts' positions get liquidated, by distance from the mark, in USD of position value, " +
122
- "grouped 0-2%, 2-5%, 5-10%, 10-20% and 20-50% below and above. A sample of the largest accounts, not every position.",
295
+ "grouped 0-2%, 2-5%, 5-10%, 10-20% and 20-50% below and above, with the price at each edge. A sample of the largest accounts, not every position. " +
296
+ "For these levels next to the resting book, use stray_book_check.",
123
297
  { coin: coreCoin, detail: z.boolean().default(false).describe("Also return the 0.5% bands from -50% to +50%.") },
124
- async ({ coin, detail }) => { const { map, ...b } = await get(`/liqmap/${coin}`); return detail ? { ...b, map } : b; });
298
+ "Hyperliquid's largest accounts, from Stray's 10-minute sweep",
299
+ async ({ coin, detail }, api) => {
300
+ const { map, ...b } = await api.get(`/liqmap/${coin}`);
301
+ const priced = (xs) => (xs ?? []).map((x) => ({ ...x, from_price: sig(b.mark * (1 + x.from_pct / 100)), to_price: sig(b.mark * (1 + x.to_pct / 100)) }));
302
+ const out = { ...b, bands: b.bands ? { below: priced(b.bands.below), above: priced(b.bands.above) } : b.bands, sample_note: LIQ_SAMPLE };
303
+ return detail ? { ...out, map } : out;
304
+ });
125
305
 
126
306
  tool("stray_implied", "Implied vs realized volatility", "Deribit's implied volatility index beside realized volatility from Hyperliquid daily closes, " +
127
- "the one-sigma moves each implies over 1, 7 and 30 days, and where implied ranks against every day since 2021.", { coin: z.enum(["BTC", "ETH"]) },
128
- async ({ coin }) => { const b = await get(`/implied/${coin}`); return { ...series(b, { keep: 7 }) }; });
307
+ "the size of a one-standard-deviation move each figure corresponds to over 1, 7 and 30 days (a measure of size, not a call), and where implied ranks against every day since 2021.", { coin: z.enum(["BTC", "ETH"]) },
308
+ "Deribit volatility index; Hyperliquid daily closes",
309
+ async ({ coin }, api) => series(await api.get(`/implied/${coin}`), { keep: 7 }));
129
310
 
130
311
  tool("stray_basis", "HYPE spot-perp basis", "HYPE's perp mark against HYPE/USDC spot on Hyperliquid, in basis points (positive = perp above spot), with " +
131
- "funding, circulating supply and spot volume.", { hours: hours(24, 24 * 31), step: step(60) },
132
- async ({ hours: h, step: s }) => series(await get("/basis/HYPE", { ...span(h), step: s })));
312
+ "funding, circulating supply and spot volume.", { hours: hours(24, 24 * 31), step: step(60), end: endArg }, "Hyperliquid perp and spot, from Stray's record",
313
+ async ({ hours: h, step: s, end }, api) => { const sp = span(h, end); return { ...checkEmpty(series(await api.get("/basis/HYPE", { ...sp, step: s })), sp), window: windowOf(sp) }; });
133
314
 
134
315
  tool("stray_correlation", "Correlation", "Correlation of daily returns between the core markets over 30, 90 or 180 days, as a matrix in the order of coins.",
135
- { window: z.union([30, 90, 180].map((n) => z.literal(n))).default(30) }, ({ window }) => get("/correlation", { window }));
316
+ { window: z.union([30, 90, 180].map((n) => z.literal(n))).default(30) }, "Hyperliquid daily closes", ({ window }, api) => api.get("/correlation", { window }));
136
317
 
137
318
  tool("stray_liquidity", "Top of book", "Ten-minute medians of the top of the Hyperliquid book: spread in basis points and USD in the top 5 and top 20 levels " +
138
- "on each side.", { coin: coreCoin, hours: hours(24, 24 * 366) },
139
- async ({ coin, hours: h }) => series(await get(`/liquidity/${coin}`, span(h)), { step: 60 }));
319
+ "on each side.", { coin: coreCoin, hours: hours(24, 24 * 366), step: step(60), end: endArg }, "Hyperliquid book, ten-minute medians",
320
+ async ({ coin, hours: h, step: s, end }, api) => { const sp = span(h, end); return { ...checkEmpty(series(await api.get(`/liquidity/${coin}`, sp), { step: s }), sp), window: windowOf(sp) }; });
140
321
 
141
322
  tool("stray_history", "Stray's record", "Stray's own minute-by-minute record of a market: mark, oracle, hourly funding, open interest in coins, and USD " +
142
- "resting within ±0.05% to ±2% of mid on each side.", { coin: anyCoin, hours: hours(24, 168), step: step(60) },
143
- async ({ coin, hours: h, step: s }) => series(await get(`/history/${coin}`, { ...span(h), step: s })));
323
+ "resting within ±0.05% to ±2% of mid on each side. With `end`, any past window since recording began.", { coin: anyCoin, hours: hours(24, 168), step: step(60), end: endArg },
324
+ "Stray's minute record of Hyperliquid",
325
+ async ({ coin, hours: h, step: s, end }, api) => { const sp = span(h, end); return { ...checkEmpty(series(await api.get(`/history/${market(coin)}`, { ...sp, step: s })), sp), window: windowOf(sp) }; });
326
+
327
+ // ── composed tools: the comparison already made ─────────────────────────────────────────────────────────────────
328
+
329
+ const tightest = (side, usdWithin, usd) => {
330
+ for (const b of BANDS) {
331
+ const v = usdWithin?.[b]?.[side];
332
+ if (Number.isFinite(v) && v >= usd) return { covered_within: b, band_usd: v, share_of_band: round(usd / v) };
333
+ }
334
+ return { covered_within: "beyond 2%", band_usd: usdWithin?.["2%"]?.[side] ?? null, share_of_band: null };
335
+ };
336
+ const median = (xs) => { const s = xs.filter(Number.isFinite).sort((a, b) => a - b); return s.length ? (s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2) : null; };
337
+
338
+ tool("stray_book_check", "Book check: the exit, the size, the hour",
339
+ "Answers 'how crowded is the exit', 'is the book thin for this hour' and 'can the book take $X' in one read. Returns the live book within " +
340
+ "±0.5/1/2% of mid; the usual depth for this UTC hour (median over 14 days) and the ratio now/usual; with `usd`, the tightest band whose resting " +
341
+ "orders cover that size on each side (selling meets bids, buying meets asks); dollars of open positions per dollar of book and its 7-day " +
342
+ "percentile; and liquidation levels within 5% of the mark from the largest accounts. Resting orders can be pulled, so this is not a fill price. " +
343
+ "Makes 4 API calls for a core market; 2 for a HIP-3 market (book and the 7-day record; crowding and liquidations are core-only).",
344
+ { coin: anyCoin, usd: z.number().positive().max(1e10).optional().describe("A position size in US dollars to check against the book."),
345
+ side: z.enum(["both", "sell", "buy"]).default("both").describe("Which side of the size to check: sell (into bids), buy (into asks) or both.") },
346
+ "Hyperliquid live book; Stray's record",
347
+ async ({ coin: raw, usd, side }, api) => {
348
+ const coin = market(raw), core = CORE.includes(coin);
349
+ const [depth, profile, crowdR, liqR, hist] = await Promise.all([
350
+ api.get(`/depth/${coin}`),
351
+ core ? api.get(`/profile/${coin}`, { days: 14 }) : null,
352
+ core ? api.get(`/crowding/${coin}`, span(168)).then((v) => ({ v }), (e) => ({ e })) : null, // optional: a miss is reported, not fatal
353
+ core ? api.get(`/liqmap/${coin}`).then((v) => ({ v }), (e) => ({ e })) : null,
354
+ core ? null : api.get(`/history/${coin}`, { ...span(168), step: 60 }),
355
+ ]);
356
+ const w = depth.usd_within ?? {};
357
+ const now1 = (w["1%"]?.bids ?? NaN) + (w["1%"]?.asks ?? NaN);
358
+ const hour = new Date(Date.parse(depth.as_of) || Date.now()).getUTCHours();
359
+ let usual;
360
+ if (core) {
361
+ const row = (profile.hours_utc ?? []).find((r) => r.hour === hour);
362
+ usual = { hour_utc: hour, median_usd_within_1pct: row?.depth_1pct_usd ?? null, period_days: 14, source: "Stray's record, median by UTC hour" };
363
+ } else {
364
+ const rows = series(hist).all.filter((o) => new Date(o.t).getUTCHours() === hour && Number.isFinite(o.bid_1) && Number.isFinite(o.ask_1)).map((o) => o.bid_1 + o.ask_1);
365
+ usual = { hour_utc: hour, median_usd_within_1pct: median(rows), samples: rows.length, period_days: 7, source: "Stray's record, one reading per hour" };
366
+ }
367
+ usual.vs_norm = Number.isFinite(now1) && usual.median_usd_within_1pct ? round(now1 / usual.median_usd_within_1pct, 3) : null;
368
+ const out = {
369
+ coin, mid: depth.mid,
370
+ book: { as_of: depth.as_of, source: depth.source === "live" ? "Hyperliquid live book" : "Stray's record, last minute", usd_within: w },
371
+ usual_hour: usual,
372
+ };
373
+ if (usd) {
374
+ out.size = { usd, caveat: "Resting orders at the book's as_of; they can be pulled or added to. Not a fill price." };
375
+ if (side !== "buy") out.size.sell = { against: "bids", ...tightest("bids", w, usd) };
376
+ if (side !== "sell") out.size.buy = { against: "asks", ...tightest("asks", w, usd) };
377
+ }
378
+ const crowd = crowdR?.v, liq = liqR?.v;
379
+ if (crowdR?.e) out.positions_per_book_dollar = { error: scrub(crowdR.e.message) };
380
+ if (liqR?.e) out.liquidations_within_5pct = { error: scrub(liqR.e.message) };
381
+ if (crowd) {
382
+ out.positions_per_book_dollar = { value: crowd.latest?.ratio ?? null, percentile: crowd.latest?.percentile ?? null, period_days: 7, as_of: iso(crowd.latest?.t),
383
+ source: "Hyperliquid open interest over USD within ±1%" };
384
+ }
385
+ if (liq) {
386
+ const band = (list, a, b) => (list ?? []).find((x) => {
387
+ const lo = Math.min(Math.abs(x.from_pct), Math.abs(x.to_pct)), hi = Math.max(Math.abs(x.from_pct), Math.abs(x.to_pct));
388
+ return lo === a && hi === b;
389
+ })?.usd ?? null;
390
+ const bl = liq.bands?.below, ab = liq.bands?.above;
391
+ out.liquidations_within_5pct = {
392
+ as_of: iso(liq.t), mark: liq.mark, sample: LIQ_SAMPLE,
393
+ below_0_2pct_usd: band(bl, 0, 2), below_2_5pct_usd: band(bl, 2, 5), above_0_2pct_usd: band(ab, 0, 2), above_2_5pct_usd: band(ab, 2, 5),
394
+ book_within_2pct_usd: { bids: w["2%"]?.bids ?? null, asks: w["2%"]?.asks ?? null },
395
+ note: "Levels below the mark are longs' (forced sells into bids); above are shorts' (forced buys into asks). The book is only measured to ±2%.",
396
+ };
397
+ }
398
+ if (!core) {
399
+ out.omitted = "Crowding and liquidation levels are recorded for core markets only.";
400
+ }
401
+ return { as_of: depth.as_of, ...out };
402
+ });
403
+
404
+ tool("stray_unusual", "Is this move unusual?",
405
+ "Where the latest move sits among every past window of the same length, for up to three window lengths at once (default 1, 7 and 30 days): " +
406
+ "the move, its percentile, p10 to p90, and whether it is inside the middle 80%. For BTC and ETH, adds implied against realized volatility " +
407
+ "and implied's percentile since 2021. Makes one API call per window, plus one for BTC or ETH.",
408
+ { coin: coreCoin, windows: z.array(z.union([1, 3, 7, 14, 30, 60, 90].map((n) => z.literal(n)))).min(1).max(3).default([1, 7, 30])
409
+ .describe("Window lengths in days (1, 3, 7, 14, 30, 60 or 90), up to three. Default [1, 7, 30].") },
410
+ "Hyperliquid closes",
411
+ async ({ coin, windows }, api) => {
412
+ const ws = [...new Set(windows)];
413
+ const settle = (p) => p.then((v) => ({ v }), (e) => ({ e })); // one failed read doesn't sink the others
414
+ const [got, impliedR] = await Promise.all([
415
+ Promise.all(ws.map((window) => settle(api.get(`/ranges/${coin}`, { window })))),
416
+ coin === "BTC" || coin === "ETH" ? settle(api.get(`/implied/${coin}`)) : null,
417
+ ]);
418
+ if (got.every((g) => g.e)) throw got[0].e;
419
+ const ranges = got.filter((g) => g.v).map((g) => g.v), implied = impliedR?.v;
420
+ const out = {
421
+ coin,
422
+ windows: ranges.map((r) => ({ window_days: r.window_days, latest_move: r.latest, latest_percentile: r.latest_percentile,
423
+ p10: r.p10, p25: r.p25, p50: r.p50, p75: r.p75, p90: r.p90, samples: r.samples,
424
+ inside_p10_p90: Number.isFinite(r.latest_percentile) ? r.latest_percentile >= 10 && r.latest_percentile <= 90 : null, source: r.source, as_of: r.as_of }))
425
+ .concat(got.map((g, i) => (g.e ? { window_days: ws[i], error: scrub(g.e.message) } : null)).filter(Boolean)),
426
+ norm: { what: "every past window of the same length (overlapping windows; 1- and 3-day from 4-hour closes, longer from daily closes)", samples: Math.min(...ranges.map((r) => r.samples ?? 0)) },
427
+ };
428
+ if (impliedR?.e) out.volatility = { error: scrub(impliedR.e.message) };
429
+ if (implied?.summary) {
430
+ const s = implied.summary;
431
+ out.volatility = { implied_annual_pct: s.implied_annual_pct, implied_percentile: s.implied_percentile, implied_since: s.implied_since,
432
+ realized_annual_pct: s.realized_annual_pct, ratio_implied_to_realized_30d: s.ratio_implied_to_realized_30d, source: "Deribit volatility index; Hyperliquid daily closes" };
433
+ }
434
+ return { as_of: ranges[0]?.as_of, ...out };
435
+ });
436
+
437
+ tool("stray_oi_change", "Open interest and price changes",
438
+ "Answers 'are positions being opened or closed into this move': the change in mark price and in open interest (in coins, so price moves " +
439
+ "don't count as new positions) over 1 hour, 4 hours, 24 hours and 7 days, from Stray's minute record, plus the latest hourly funding. " +
440
+ "Changes are fractions (0.012 = 1.2%). Works for core and HIP-3 markets.",
441
+ { coin: anyCoin, end: endArg }, "Stray's minute record of Hyperliquid",
442
+ async ({ coin: raw, end }, api) => {
443
+ const coin = market(raw), sp = span(168, end);
444
+ const rows = series(await api.get(`/history/${coin}`, { ...sp, step: 60 })).all.filter((o) => Number.isFinite(o.mark) && Number.isFinite(o.oi));
445
+ if (!rows.length) throw new Error("No record for that market in that window.");
446
+ const last = rows[rows.length - 1];
447
+ const back = (hrs) => {
448
+ const target = last.t - hrs * HOUR;
449
+ const o = rows.reduce((best, x) => (Math.abs(x.t - target) < Math.abs(best.t - target) ? x : best), rows[0]);
450
+ if (o === last || Math.abs(o.t - target) > Math.max(0.1 * hrs * HOUR, 30 * 60e3)) return { note: "The record doesn't reach back that far in this window." };
451
+ return { from: iso(o.t), to: iso(last.t), mark_from: o.mark, mark_to: last.mark, mark_change: round(last.mark / o.mark - 1, 5),
452
+ oi_coins_from: sig(o.oi, 8), oi_coins_to: sig(last.oi, 8), oi_change: round(last.oi / o.oi - 1, 5) };
453
+ };
454
+ return { as_of: iso(last.t), coin, window: windowOf(sp), changes: { "1h": back(1), "4h": back(4), "24h": back(24), "7d": back(168) },
455
+ funding_latest_hourly: last.funding ?? null };
456
+ });
457
+
458
+ tool("stray_funding_venues", "Funding across venues",
459
+ "Answers 'is the funding gap between Hyperliquid and the other venues real': each venue's current rate as an hourly equivalent and annualized " +
460
+ "(Hyperliquid settles hourly; Binance, Bybit and OKX every 8 hours, divided by 8 here), each venue's gap to Hyperliquid, and how many hours " +
461
+ "that gap has kept its sign in the window; plus the next funding rates Hyperliquid publishes for Binance and Bybit. Positive = longs pay shorts.",
462
+ { coin: coreCoin, hours: hours(24, 168), end: endArg }, "Hyperliquid, Binance, Bybit and OKX funding, from Stray's record",
463
+ async ({ coin, hours: h, end }, api) => {
464
+ const sp = span(h, end);
465
+ const rows = series(await api.get(`/venues/${coin}`, { ...sp, step: 60 })).all;
466
+ if (!rows.length) throw new Error("No venue rows in that window.");
467
+ const last = rows[rows.length - 1];
468
+ const pred = last.predicted_funding ?? {};
469
+ const interval = { hyperliquid: 1, binance: pred.BinPerp?.[1] ?? 8, bybit: pred.BybitPerp?.[1] ?? 8, okx: 8 };
470
+ const hourly = (row, v) => (Number.isFinite(row?.[v]?.funding) ? row[v].funding / interval[v] : null);
471
+ const venues = {};
472
+ for (const v of ["hyperliquid", "binance", "bybit", "okx"]) {
473
+ const f = hourly(last, v);
474
+ const entry = { funding_hourly: sig(f), funding_annualized: f === null ? null : round(f * 24 * 365), settles_every_hours: interval[v],
475
+ ...(v === "okx" ? { interval_note: "assumed 8 hours (OKX's interval isn't in the record)" } : v !== "hyperliquid" ? { interval_note: pred[v === "binance" ? "BinPerp" : "BybitPerp"] ? "as Hyperliquid publishes it" : "assumed 8 hours" } : {}) };
476
+ if (v !== "hyperliquid") {
477
+ const gap = (row) => { const a = hourly(row, v), b = hourly(row, "hyperliquid"); return a === null || b === null ? null : a - b; };
478
+ const g = gap(last);
479
+ let same = 0;
480
+ for (let i = rows.length - 1; i >= 0; i--) { const x = gap(rows[i]); if (x === null || g === null || Math.sign(x) !== Math.sign(g)) break; same++; }
481
+ Object.assign(entry, { gap_vs_hyperliquid_hourly: sig(g), gap_vs_hyperliquid_annualized: g === null ? null : round(g * 24 * 365),
482
+ gap_same_sign_hours: g === null ? null : same, ...(g !== null && same === rows.length ? { gap_same_sign_note: "The whole window; widen hours to see further." } : {}) });
483
+ }
484
+ venues[v] = entry;
485
+ }
486
+ const next = Object.fromEntries(Object.entries(pred).filter(([, v]) => Array.isArray(v) && Number.isFinite(v[0]) && v[1] > 0)
487
+ .map(([k, [rate, every]]) => [k, { rate_per_period: rate, every_hours: every, hourly: sig(rate / every) }]));
488
+ return { as_of: iso(last.t), coin, window: windowOf(sp), venues, next_funding_published_by_hyperliquid: next };
489
+ });
490
+
491
+ tool("stray_brief", "The market in one read",
492
+ "The whole market's Draw and band, its change over 24 hours, all eight core markets ranked by their Draw, and for the top one to three the seven " +
493
+ "components with their inputs. Answers 'what is stretched right now' across markets. Makes 1 API call plus one per market in `top` (default 2).",
494
+ { top: z.number().int().min(1).max(3).default(2).describe("How many of the most tense markets to break down, 1 to 3. Default 2.") },
495
+ "Stray's Draw, computed every 10 minutes from the record",
496
+ async ({ top }, api) => {
497
+ const m = await api.get("/draw", { ...span(24), step: 60 });
498
+ const entries = Object.entries(m.markets ?? {});
499
+ const ranked = entries.filter(([, r]) => r && Number.isFinite(r.draw)).map(([coin, r]) => ({ coin, draw: r.draw, band: r.band, weight: m.weights?.[coin] ?? null }))
500
+ .sort((a, b) => b.draw - a.draw);
501
+ const missing = entries.filter(([, r]) => !r || !Number.isFinite(r.draw)).map(([coin]) => coin);
502
+ const parts = await Promise.all(ranked.slice(0, top).map((r) => api.get(`/draw/${r.coin}`, { ...span(1), step: 60 })));
503
+ const first = m.history?.[0]?.[1], latest = m.draw;
504
+ return {
505
+ as_of: iso(m.t), market: { draw: m.draw, band: m.band, draw_24h_ago: first ?? null, change_24h: Number.isFinite(first) ? round(latest - first, 1) : null },
506
+ ranked, ...(missing.length ? { missing, missing_note: "No Draw reading in the last 30 minutes for these." } : {}),
507
+ breakdown: parts.map((p) => ({ coin: p.coin, draw: p.draw, band: p.band, components: p.components, inputs: p.inputs, as_of: iso(p.t) })),
508
+ bands: m.bands, method: m.method,
509
+ };
510
+ });
511
+
512
+ // ── prompts: the common questions, ready to ask ─────────────────────────────────────────────────────────────────
513
+
514
+ const CLOSE = "Report what the record shows, with the time of each number and what it is compared with. Do not say what price will do. " +
515
+ "If asked, say Stray records what markets have done.";
516
+ function prompt(name, title, description, argsSchema, text) {
517
+ server.registerPrompt(name, { title, description, argsSchema }, (a) => ({ messages: [{ role: "user", content: { type: "text", text: `${text(a)}\n\n${CLOSE}` } }] }));
518
+ }
519
+ const coinArg = z.string().describe('A market, e.g. "BTC" or "xyz:NVDA"');
520
+
521
+ prompt("exit", "How crowded is the exit?", "The book near the price against the usual hour, positions per dollar of book, and liquidation levels nearby.",
522
+ { coin: coinArg, usd: z.string().optional().describe("Optional position size in USD") },
523
+ ({ coin, usd }) => `How crowded is the exit on ${coin}? Use stray_book_check${usd ? ` with usd ${usd}` : ""}: how much resting book sits near the price on each ` +
524
+ "side against the usual depth for this hour, how many dollars of positions there are per dollar of book, and how much is set to liquidate within 5% of the mark.");
525
+ prompt("unusual", "Is this move unusual?", "The latest 1-, 7- and 30-day moves against every past window of the same length.", { coin: coinArg },
526
+ ({ coin }) => `Is ${coin}'s recent move unusual? Use stray_unusual and say where each window's move sits among past windows of the same length.`);
527
+ prompt("pressure", "Which conditions are unusual right now?", "The measured conditions on a market that sit at unusual levels now, and how unusual each is.", { coin: coinArg },
528
+ ({ coin }) => `Which measured conditions on ${coin} are at unusual levels right now? Use stray_draw with the coin for its seven components and inputs, ` +
529
+ "and stray_book_check for the book, crowding and liquidation levels nearby. List each condition and how unusual it is against its own history. " +
530
+ "Say nothing about what tends to follow.");
531
+ prompt("thin", "Is the book thin for this hour?", "The book now against the usual hour, and the hours when it is usually thinnest and deepest.", { coin: coinArg },
532
+ ({ coin }) => `Is ${coin}'s book thin for this hour, and when is it usually thinnest? Use stray_book_check, then stray_profile for the thinnest and deepest hours.`);
533
+ prompt("venues", "Hyperliquid against the other venues", "Depth and funding on Hyperliquid, Binance, Bybit and OKX side by side.", { coin: coinArg },
534
+ ({ coin }) => `How does ${coin} on Hyperliquid compare with Binance, Bybit and OKX right now? Use stray_venues for depth and stray_funding_venues for funding.`);
535
+ prompt("replay", "What did the book do?", "A past window from the record: the book, trade flow and top of book.",
536
+ { coin: coinArg, from: z.string().describe("Start, ISO 8601 UTC"), to: z.string().describe("End, ISO 8601 UTC") },
537
+ ({ coin, from, to }) => `What did ${coin}'s book do between ${from} and ${to}? Use stray_history, stray_flow and stray_liquidity with end set to ${to}, ` +
538
+ `hours covering the window from ${from}, and step 10 for a window of a few hours.`);
144
539
 
145
540
  await server.connect(new StdioServerTransport());