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(liquidation-collector): implement standalone service for futures liquidation data collection and REST API

fudjia54ef861626a0
diff --git a/api/_lib/market-data.js b/api/_lib/market-data.js
new file mode 100644
index 000000000..8424ad44b
--- /dev/null
+++ b/api/_lib/market-data.js
@@ -0,0 +1,399 @@
+// DeFiLlama market-data layer: protocol TVL, yield pools, chain TVL, and DEX
+// volumes. Ported from SperaxOS's CryptoMarketDataService (TypeScript) into a
+// plain-ESM JS module matching three.ws conventions — see
+// _prompts/sperax/ref/crypto-market-data/{service,types}.ts for the source.
+//
+// three.ws already has a CoinGecko layer (api/_lib/coingecko.js) and
+// page-specific DeFiLlama proxies (api/defi/protocols.js, api/defi/chains.js)
+// tuned for their own pages' rendering shapes. This module is a separate,
+// generic library layer for programmatic consumers (the trading copilot,
+// future yield/protocol endpoints) that want the reference's typed shape
+// (camelCase, single `chain`, `slug`-addressable protocol lookup) rather than
+// a page's bespoke normalization — it does not replace either.
+//
+// Caching: a per-instance in-memory Map, burst-shield only (serverless
+// instances are ephemeral). Fetches retry with exponential backoff on 429/5xx,
+// max 2 retries, mirroring the reference's fetchWithRetry.
+
+/**
+ * @typedef {Object} Protocol
+ * @property {string} slug
+ * @property {string} name
+ * @property {number} tvl
+ * @property {string} category
+ * @property {string} chain
+ * @property {number} change1d
+ * @property {number} change7d
+ * @property {string} logo
+ */
+
+/**
+ * @typedef {Object} ProtocolTvl
+ * @property {string} slug
+ * @property {string} name
+ * @property {number} tvl
+ * @property {string} category
+ * @property {string} chain
+ * @property {number} change1d
+ * @property {number} change7d
+ * @property {string[]} chains
+ */
+
+/**
+ * @typedef {Object} YieldFilter
+ * @property {string} [chain]
+ * @property {string} [project]
+ * @property {boolean} [stablecoin]
+ * @property {number} [minTvl]
+ * @property {number} [limit]
+ */
+
+/**
+ * @typedef {Object} YieldPool
+ * @property {string} pool
+ * @property {string} project
+ * @property {string} chain
+ * @property {string} symbol
+ * @property {number} tvlUsd
+ * @property {number} apy
+ * @property {number} apyBase
+ * @property {number} apyReward
+ * @property {boolean} stablecoin
+ * @property {string} ilRisk
+ */
+
+/**
+ * @typedef {Object} ChainTvl
+ * @property {string} name
+ * @property {number} tvl
+ * @property {string} tokenSymbol
+ * @property {number} dominance
+ * @property {number} change1d
+ */
+
+/**
+ * @typedef {Object} DexVolume
+ * @property {string} name
+ * @property {number} volume24h
+ * @property {number} change1d
+ * @property {string} chain
+ */
+
+/**
+ * @typedef {Object} FearGreedIndex
+ * @property {number} value
+ * @property {string} classification
+ * @property {string} timestamp
+ */
+
+// ---------------------------------------------------------------------------
+// Cache TTLs (ms) — per source, mirroring the reference's DEFAULT_CACHE_TTL
+// with the values decision 2 calls for.
+// ---------------------------------------------------------------------------
+export const CACHE_TTL = {
+ protocols: 600_000, // 10 min
+ yields: 900_000, // 15 min
+ fearGreed: 1_800_000, // 30 min
+ dexVolumes: 600_000, // 10 min
+};
+
+const _cache = new Map(); // key -> { data, expires }
+const MAX_ENTRIES = 512;
+
+function getCached(key) {
+ const entry = _cache.get(key);
+ if (!entry) return undefined;
+ if (Date.now() > entry.expires) {
+ _cache.delete(key);
+ return undefined;
+ }
+ return entry.data;
+}
+
+function setCache(key, data, ttlMs) {
+ _cache.set(key, { data, expires: Date.now() + ttlMs });
+ if (_cache.size > MAX_ENTRIES) _cache.delete(_cache.keys().next().value);
+}
+
+/** Drop every cached entry. Exposed for tests; not used in product code. */
+export function clearMarketDataCache() {
+ _cache.clear();
+}
+
+// ---------------------------------------------------------------------------
+// Fetch with retry + exponential backoff on 429/5xx (max 2 retries).
+// ---------------------------------------------------------------------------
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+/**
+ * GET a URL as JSON, retrying up to `maxRetries` times with exponential
+ * backoff on HTTP 429 or 5xx responses (and on network errors). Throws on a
+ * non-retryable error status (4xx other than 429) or once retries are spent.
+ * @param {string} url
+ * @param {{ maxRetries?: number, timeoutMs?: number }} [options]
+ */
+export async function fetchWithRetry(url, options = {}) {
+ const { maxRetries = 2, timeoutMs = 10_000 } = options;
+
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
+ let res;
+ try {
+ res = await fetch(url, {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ } catch (err) {
+ if (attempt === maxRetries) throw err;
+ await sleep(Math.min(1000 * 2 ** attempt, 10_000));
+ continue;
+ }
+
+ if (res.status === 429 || res.status >= 500) {
+ if (attempt === maxRetries) {
+ const err = new Error(`HTTP ${res.status} for ${url}`);
+ err.status = res.status;
+ throw err;
+ }
+ await sleep(Math.min(2000 * 2 ** attempt, 30_000));
+ continue;
+ }
+
+ if (!res.ok) {
+ const err = new Error(`HTTP ${res.status} for ${url}`);
+ err.status = res.status;
+ throw err;
+ }
+
+ return res.json();
+ }
+
+ throw new Error('fetchWithRetry: unreachable');
+}
+
+// ---------------------------------------------------------------------------
+// DeFiLlama — https://api.llama.fi/ and https://yields.llama.fi/
+// ---------------------------------------------------------------------------
+
+const finite = (n, fallback = 0) => (Number.isFinite(n) ? n : fallback);
+
+/**
+ * Top DeFi protocols by TVL, optionally filtered to one chain.
+ * @param {{ chain?: string, limit?: number }} [options]
+ * @returns {Promise<Protocol[]>}
+ */
+export async function getProtocols(options = {}) {
+ const { chain, limit = 20 } = options;
+ const cacheKey = `dl:protocols:${chain ?? 'all'}:${limit}`;
+ const cached = getCached(cacheKey);
+ if (cached) return cached;
+
+ const data = await fetchWithRetry('https://api.llama.fi/protocols');
+ if (!Array.isArray(data)) throw new Error('unexpected protocols payload');
+
+ let protocols = data;
+ if (chain) {
+ const lc = chain.toLowerCase();
+ protocols = protocols.filter(
+ (p) =>
+ (p.chain ?? '').toLowerCase() === lc ||
+ (Array.isArray(p.chains) ? p.chains : []).some((c) => String(c).toLowerCase() === lc),
+ );
+ }
+
+ const result = protocols
+ .slice()
+ .sort((a, b) => finite(Number(b.tvl)) - finite(Number(a.tvl)))
+ .slice(0, limit)
+ .map((p) => ({
+ slug: p.slug ?? '',
+ name: p.name ?? '',
+ tvl: finite(Number(p.tvl)),
+ category: p.category ?? 'Unknown',
+ chain: p.chain ?? 'Multi-chain',
+ change1d: finite(Number(p.change_1d)),
+ change7d: finite(Number(p.change_7d)),
+ logo: p.logo ?? '',
+ }));
+
+ setCache(cacheKey, result, CACHE_TTL.protocols);
+ return result;
+}
+
+/**
+ * Single protocol's TVL detail by DeFiLlama slug.
+ * @param {string} slug
+ * @returns {Promise<ProtocolTvl>}
+ */
+export async function getProtocol(slug) {
+ if (!slug || typeof slug !== 'string') {
+ throw Object.assign(new Error('slug is required'), { status: 400 });
+ }
+ const cacheKey = `dl:protocol:${slug}`;
+ const cached = getCached(cacheKey);
+ if (cached) return cached;
+
+ const data = await fetchWithRetry(`https://api.llama.fi/protocol/${encodeURIComponent(slug)}`);
+
+ const result = {
+ slug: data?.slug ?? slug,
+ name: data?.name ?? slug,
+ tvl: finite(Number(data?.tvl)),
+ category: data?.category ?? 'Unknown',
+ chain: data?.chain ?? 'Multi-chain',
+ change1d: finite(Number(data?.change_1d)),
+ change7d: finite(Number(data?.change_7d)),
+ chains: Array.isArray(data?.chains) ? data.chains.filter((c) => typeof c === 'string') : [],
+ };
+
+ setCache(cacheKey, result, CACHE_TTL.protocols);
+ return result;
+}
+
+/**
+ * Yield pools from DeFiLlama's yields API, filtered server-side.
+ * @param {YieldFilter} [filter]
+ * @returns {Promise<YieldPool[]>}
+ */
+export async function getYieldPools(filter = {}) {
+ const { chain, project, stablecoin, minTvl = 0, limit = 15 } = filter;
+ const cacheKey = `dl:yields:${chain ?? ''}:${project ?? ''}:${stablecoin ?? ''}:${minTvl}`;
+ let pools = getCached(cacheKey);
+ if (!pools) {
+ const data = await fetchWithRetry('https://yields.llama.fi/pools');
+ const raw = Array.isArray(data?.data) ? data.data : [];
+
+ let filtered = raw;
+ if (chain) {
+ const lc = chain.toLowerCase();
+ filtered = filtered.filter((p) => (p.chain ?? '').toLowerCase() === lc);
+ }
+ if (project) {
+ const lp = project.toLowerCase();
+ filtered = filtered.filter((p) => (p.project ?? '').toLowerCase() === lp);
+ }
+ if (stablecoin !== undefined) {
+ filtered = filtered.filter((p) => Boolean(p.stablecoin) === Boolean(stablecoin));
+ }
+ filtered = filtered.filter((p) => finite(Number(p.tvlUsd)) >= minTvl);
+
+ pools = filtered
+ .sort((a, b) => finite(Number(b.tvlUsd)) - finite(Number(a.tvlUsd)))
+ .map((p) => ({
+ pool: p.pool ?? '',
+ project: p.project ?? '',
+ chain: p.chain ?? '',
+ symbol: p.symbol ?? '',
+ tvlUsd: finite(Number(p.tvlUsd)),
+ apy: finite(Number(p.apy)),
+ apyBase: finite(Number(p.apyBase)),
+ apyReward: finite(Number(p.apyReward)),
+ stablecoin: Boolean(p.stablecoin),
+ ilRisk: p.ilRisk ?? 'unknown',
+ }));
+
+ setCache(cacheKey, pools, CACHE_TTL.yields);
+ }
+
+ return pools.slice(0, limit);
+}
+
+/**
+ * Cross-chain TVL breakdown, sorted by TVL desc, with each chain's dominance
+ * (% of total TVL across all chains).
+ * @returns {Promise<ChainTvl[]>}
+ */
+export async function getChainTvls() {
+ const cacheKey = 'dl:chains';
+ const cached = getCached(cacheKey);
+ if (cached) return cached;
+
+ const data = await fetchWithRetry('https://api.llama.fi/v2/chains');
+ if (!Array.isArray(data)) throw new Error('unexpected chains payload');
+
+ const totalTvl = data.reduce((sum, c) => sum + finite(Number(c?.tvl)), 0);
+
+ const result = data
+ .slice()
+ .sort((a, b) => finite(Number(b.tvl)) - finite(Number(a.tvl)))
+ .slice(0, 20)
+ .map((c) => ({
+ name: c.name ?? '',
+ tvl: finite(Number(c.tvl)),
+ tokenSymbol: c.tokenSymbol ?? '',
+ dominance: totalTvl > 0 ? (finite(Number(c.tvl)) / totalTvl) * 100 : 0,
+ change1d: finite(Number(c.change_1d)),
+ }));
+
+ setCache(cacheKey, result, CACHE_TTL.protocols);
+ return result;
+}
+
+/**
+ * Top DEX protocols by 24h trading volume, optionally filtered to one chain.
+ * @param {{ chain?: string }} [options]
+ * @returns {Promise<DexVolume[]>}
+ */
+export async function getDexVolumes(options = {}) {
+ const { chain } = options;
+ const cacheKey = `dl:dex:${chain ?? 'all'}`;
+ const cached = getCached(cacheKey);
+ if (cached) return cached;
+
+ const data = await fetchWithRetry('https://api.llama.fi/overview/dexs');
+ let dexes = Array.isArray(data?.protocols) ? data.protocols : [];
+ if (chain) {
+ const lc = chain.toLowerCase();
+ dexes = dexes.filter((d) => (Array.isArray(d.chains) ? d.chains : []).some((c) => String(c).toLowerCase() === lc));
+ }
+
+ const result = dexes
+ .slice()
+ .sort((a, b) => finite(Number(b.total24h)) - finite(Number(a.total24h)))
+ .slice(0, 15)
+ .map((d) => ({
+ name: d.name ?? '',
+ volume24h: finite(Number(d.total24h)),
+ change1d: finite(Number(d.change_1d)),
+ chain: (Array.isArray(d.chains) ? d.chains : []).join(', '),
+ }));
+
+ setCache(cacheKey, result, CACHE_TTL.dexVolumes);
+ return result;
+}
+
+// ---------------------------------------------------------------------------
+// Fear & Greed Index — https://api.alternative.me/
+//
+// three.ws already has a fully-featured fear/greed endpoint at
+// api/coin/fear-greed.js (history + week-over-week delta, its own cache).
+// getFearGreed() here is the reference's minimal single-reading shape, kept
+// as a library function only so a future internal consumer (e.g. the trading
+// copilot scoring a market snapshot) can pull one lightweight reading without
+// depending on the page endpoint's richer/history-shaped response. It is not
+// wired to any endpoint in this task.
+// ---------------------------------------------------------------------------
+
+/**
+ * Latest Fear & Greed reading (single data point, no history).
+ * @returns {Promise<FearGreedIndex>}
+ */
+export async function getFearGreed() {
+ const cacheKey = 'fng:latest';
+ const cached = getCached(cacheKey);
+ if (cached) return cached;
+
+ const data = await fetchWithRetry('https://api.alternative.me/fng/?limit=1');
+ const entry = Array.isArray(data?.data) ? data.data[0] : undefined;
+
+ const result = {
+ value: finite(Number(entry?.value), 50),
+ classification: String(entry?.value_classification ?? 'Neutral'),
+ timestamp: String(entry?.timestamp ?? Math.floor(Date.now() / 1000).toString()),
+ };
+
+ setCache(cacheKey, result, CACHE_TTL.fearGreed);
+ return result;
+}
diff --git a/api/intel/yields.js b/api/intel/yields.js
new file mode 100644
index 000000000..0857f9254
--- /dev/null
+++ b/api/intel/yields.js
@@ -0,0 +1,56 @@
+// GET /api/intel/yields?chain=<name>&project=<slug>&stablecoin=<bool>&limit=<1..100>
+// ---------------------------------------------------------------------------
+// DeFi yield pools from DeFiLlama's keyless yields API (yields.llama.fi/pools),
+// filtered server-side and sorted by TVL desc. Backs the trading copilot and
+// future yield-discovery surfaces (consumers land separately — this task
+// ships the data layer + endpoint only). Real upstream data, no fabrication.
+//
+// Response: { pools: [{ pool, project, chain, symbol, tvlUsd, apy, apyBase,
+// apyReward, stablecoin }] }
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getYieldPools } from '../_lib/market-data.js';
+
+const DEFAULT_LIMIT = 25;
+const MAX_LIMIT = 100;
+
+function parseBool(v) {
+ if (v === null || v === undefined) return undefined;
+ const s = String(v).toLowerCase();
+ if (s === 'true' || s === '1') return true;
+ if (s === 'false' || s === '0') return false;
+ return undefined;
+}
+
+function clampLimit(v) {
+ const n = parseInt(v ?? '', 10);
+ if (!Number.isFinite(n) || n <= 0) return DEFAULT_LIMIT;
+ return Math.min(MAX_LIMIT, n);
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const chain = params.get('chain') || undefined;
+ const project = params.get('project') || undefined;
+ const stablecoin = parseBool(params.get('stablecoin'));
+ const limit = clampLimit(params.get('limit'));
+
+ try {
+ const pools = await getYieldPools({ chain, project, stablecoin, limit });
+ return json(
+ res,
+ 200,
+ { pools: pools.map(({ ilRisk, ...rest }) => rest) },
+ { 'cache-control': 'public, s-maxage=60, stale-while-revalidate=300' },
+ );
+ } catch {
+ return error(res, 502, 'upstream_error', 'DeFi yield data is temporarily unavailable — retry shortly');
+ }
+});
diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.md
index 3b475703f..292931a02 100644
--- a/docs/ops/gcp-production.md
+++ b/docs/ops/gcp-production.md
@@ -61,13 +61,27 @@ could not "move" it; Cloud Run connects to the same instance via `DATABASE_URL`.
- **NOT production:** `ep-rapid-surf-ak9p7occ` (Neon project `wild-river-11025097`)
appears in old env archives — it is a **stale/smaller copy** (85 tables /
~127k rows / 224 avatars). Do not point production at it.
-- ⚠️ **DECOMMISSION HAZARD:** this Neon project was likely provisioned via
- Vercel's Postgres integration. **Deleting the Vercel project may delete or
- orphan the Neon database.** Before decommissioning Vercel, log into
- neon.tech, confirm the `ep-muddy-morning` project is owned by a standalone
- Neon account (not a Vercel-managed org), and transfer/claim it if not. This
- is the single highest-stakes item in the whole migration — the data is the
- crown jewels.
+- ⚠️ **DECOMMISSION HAZARD (confirmed 2026-07-08):** this Neon project was
+ provisioned via Vercel's Postgres integration. If it's the **Vercel-Managed
+ Integration** (billing inside Vercel), Neon's own docs state that deleting
+ the database from Vercel's interface **removes the underlying Neon project
+ permanently**, and Neon does **not** offer a self-serve transfer for
+ Vercel-integrated projects ("projects with Vercel integrations cannot be
+ transferred" — [neon.com/docs/manage/orgs-project-transfer](https://neon.com/docs/manage/orgs-project-transfer)).
+ There is no dashboard "claim it" button — do not assume one exists.
+ Two real paths before the Vercel account is closed:
+ 1. Open a Neon support ticket asking to detach/transfer `ep-muddy-morning`
+ into a standalone (non-Vercel) Neon org — some users have gotten this
+ handled manually by support even though it isn't self-serve.
+ 2. Cut over independently: provision a fresh standalone Postgres (Neon-native
+ org or Cloud SQL), restore into it, swap `DATABASE_URL` on the Cloud Run
+ service, verify, then let the old Vercel-linked project go.
+ - **Safety net taken 2026-07-08:** full `pg_dump -Fc` of `neondb` (344
+ tables, 673 MB live / 47 MB compressed) uploaded to Cloudflare R2 at
+ `s3://chatty-storage/db-backups/neondb-2026-07-08.dump` — durable, off
+ both Neon and Vercel. This is a point-in-time backup for disaster
+ recovery, not a replacement for resolving ownership above; retention/
+ rotation isn't automated yet.
### Service accounts (IMPORTANT — the project's default compute SA was deleted)
diff --git a/package-lock.json b/package-lock.json
index 938466420..a06da8e2c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -18,6 +18,7 @@
"mcp-bridge",
"mcp-server",
"multiplayer",
+ "services/liquidation-collector",
"packages/avatar-schema",
"packages/avatar-cli",
"packages/defi-utils",
@@ -21806,6 +21807,10 @@
"resolved": "packages/kol-mcp",
"link": true
},
+ "node_modules/@three-ws/liquidation-collector": {
+ "resolved": "services/liquidation-collector",
+ "link": true
+ },
"node_modules/@three-ws/loom-mcp": {
"resolved": "packages/loom-mcp",
"link": true
@@ -52849,6 +52854,16 @@
}
}
},
+ "services/liquidation-collector": {
+ "name": "@three-ws/liquidation-collector",
+ "version": "1.0.0",
+ "dependencies": {
+ "ws": "^8.21.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"solana-agent-sdk": {
"name": "@three-ws/solana-agent",
"version": "0.2.1",
diff --git a/package.json b/package.json
index 4c4d4731f..d0b344ba9 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"mcp-bridge",
"mcp-server",
"multiplayer",
+ "services/liquidation-collector",
"packages/avatar-schema",
"packages/avatar-cli",
"packages/defi-utils",
diff --git a/services/liquidation-collector/README.md b/services/liquidation-collector/README.md
new file mode 100644
index 000000000..50bb3fe5f
--- /dev/null
+++ b/services/liquidation-collector/README.md
@@ -0,0 +1,103 @@
+# @three-ws/liquidation-collector
+
+Standalone Node service that subscribes to the **public** futures liquidation
+WebSocket streams of Binance, Bybit, and OKX, classifies each liquidation by
+USD size, keeps a rolling 4-hour in-memory window, and serves an aggregate
+REST snapshot.
+
+It feeds the "liquidations pulse" strip on [three.ws/coins](https://three.ws/coins)
+via the proxy endpoint [`api/coin/liquidations.js`](../../api/coin/liquidations.js).
+
+Ported from a battle-tested 283-line SperaxOS collector — same stream URLs,
+per-exchange parsing, size buckets, reconnect/backoff, rolling window, and
+aggregate math.
+
+## Why a separate service
+
+This process holds three long-lived WebSocket connections open indefinitely.
+That is fundamentally incompatible with Vercel/serverless functions (which are
+short-lived, request-scoped invocations) — it **cannot** be deployed as a
+Vercel function. It must run on an always-on Node host: a small VM, a Cloud
+Run service with `min-instances >= 1` and no request timeout, a Fly.io app, a
+Railway/Render worker, etc. Point `LIQUIDATION_COLLECTOR_URL` (set on the main
+three.ws deployment) at wherever it ends up.
+
+## Run it
+
+```sh
+cd services/liquidation-collector
+npm install
+npm start
+# or, for local iteration with auto-restart on save:
+npm run dev
+```
+
+No API keys or credentials are required — all three streams are public.
+Liquidations on majors (BTC, ETH, SOL, …) typically start arriving within a
+minute or two of connecting.
+
+## Env vars
+
+| Var | Default | Description |
+| ------ | ------- | --------------------------------------------- |
+| `PORT` | `3033` | HTTP port the REST API listens on |
+
+## HTTP surface
+
+### `GET /health`
+
+```json
+{ "ok": true, "cached": 1234, "uptime": 5821.4 }
+```
+
+### `GET /liquidations`
+
+Returns the 50 most recent liquidations (across the tracked symbol list) plus
+aggregate stats over the rolling 4-hour window.
+
+```json
+{
+ "liquidations": [
+ {
+ "exchange": "Binance",
+ "price": 61234.5,
+ "qty": 0.42,
+ "severity": "LARGE",
+ "side": "LONG",
+ "symbol": "BTC",
+ "time": 1735689600000,
+ "value": 257184.89
+ }
+ ],
+ "summary": {
+ "dominantSide": "LONG PAIN",
+ "largeCount": 12,
+ "longCount": 340,
+ "longValue": 8123456.12,
+ "megaCount": 1,
+ "shortCount": 190,
+ "shortValue": 2456789.01,
+ "totalCount": 530,
+ "totalValue": 10580245.13
+ },
+ "symbolStats": [
+ { "count": 210, "longValue": 5123456.0, "shortValue": 890123.0, "symbol": "BTC" }
+ ],
+ "timestamp": "2026-07-08T12:00:00.000Z"
+}
+```
+
+- `severity` buckets: `SMALL` (< $10k), `MEDIUM` (< $100k), `LARGE` (< $1M), `MEGA` (>= $1M).
+- `side` is the side that got liquidated: a forced-sell of a long is `LONG`, a forced-buy-back of a short is `SHORT`.
+- `summary.dominantSide` is `LONG PAIN` when long liquidations exceed short liquidations by 1.5x, `SHORT SQUEEZE` for the inverse, `BALANCED` otherwise.
+
+## Tracked symbols
+
+BTC, ETH, SOL, DOGE, XRP, ARB, OP, AVAX, LINK, BNB, SUI, WIF, PEPE, BONK, INJ, TIA, APT, NEAR.
+
+## Deploy note
+
+Not a Vercel function — deploy to any always-on Node host (VM, Fly.io,
+Railway, a dedicated Cloud Run service with `min-instances=1`, etc.). The
+service reconnects each exchange stream automatically on disconnect (5s
+backoff) and exits cleanly on process signals delivered by the host platform.
diff --git a/services/liquidation-collector/package.json b/services/liquidation-collector/package.json
new file mode 100644
index 000000000..5539933a2
--- /dev/null
+++ b/services/liquidation-collector/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "@three-ws/liquidation-collector",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "description": "Standalone collector for public Binance/Bybit/OKX futures liquidation WebSocket streams — serves an aggregate REST snapshot consumed by api/coin/liquidations.js.",
+ "main": "src/index.js",
+ "scripts": {
+ "start": "node src/index.js",
+ "dev": "node --watch src/index.js"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "dependencies": {
+ "ws": "^8.21.0"
+ }
+}
diff --git a/services/liquidation-collector/src/index.js b/services/liquidation-collector/src/index.js
new file mode 100644
index 000000000..8c4eef2d5
--- /dev/null
+++ b/services/liquidation-collector/src/index.js
@@ -0,0 +1,314 @@
+// three.ws liquidation-collector — standalone always-on Node service.
+//
+// Subscribes to the PUBLIC futures liquidation WebSocket streams of Binance,
+// Bybit, and OKX, classifies each liquidation by USD size, keeps a rolling
+// 4-hour in-memory window, and serves an aggregate REST snapshot consumed by
+// `api/coin/liquidations.js` (proxy) → the "liquidations pulse" strip on
+// three.ws/coins.
+//
+// Ported faithfully from the reference SperaxOS collector
+// (_prompts/sperax/ref/liquidation-collector/index.ts) — same stream URLs,
+// per-exchange parsing, size buckets, reconnect/backoff, rolling window, and
+// aggregate math. The only change is swapping the Hono HTTP layer for plain
+// node:http so this package has zero framework dependencies beyond `ws`.
+//
+// This process holds long-lived WebSocket connections — it is NOT deployable
+// as a Vercel serverless function. Run it on any always-on Node host (see
+// README.md) and point `LIQUIDATION_COLLECTOR_URL` at it.
+
+import { createServer } from 'node:http';
+import { WebSocket } from 'ws';
+
+// ---------------------------------------------------------------------------
+// Config
+// ---------------------------------------------------------------------------
+
+const TRACKED = [
+ 'BTC', 'ETH', 'SOL', 'DOGE', 'XRP', 'ARB', 'OP', 'AVAX', 'LINK',
+ 'BNB', 'SUI', 'WIF', 'PEPE', 'BONK', 'INJ', 'TIA', 'APT', 'NEAR',
+];
+
+const MAX_CACHE = 10_000;
+const MAX_AGE_MS = 4 * 60 * 60 * 1000; // 4 hours
+
+// ---------------------------------------------------------------------------
+// In-memory store
+// ---------------------------------------------------------------------------
+
+/** @typedef {{ exchange: string, price: number, qty: number, severity: string, side: 'LONG'|'SHORT', symbol: string, time: number, value: number }} LiquidationEntry */
+
+/** @type {LiquidationEntry[]} */
+const cache = [];
+
+function classify(value) {
+ if (value >= 1_000_000) return 'MEGA';
+ if (value >= 100_000) return 'LARGE';
+ if (value >= 10_000) return 'MEDIUM';
+ return 'SMALL';
+}
+
+function push(entry) {
+ cache.push({ ...entry, severity: classify(entry.value) });
+ if (cache.length > MAX_CACHE) cache.shift();
+}
+
+// ---------------------------------------------------------------------------
+// Binance — public stream: wss://fstream.binance.com/ws/!forceOrder@arr
+// ---------------------------------------------------------------------------
+
+function connectBinance() {
+ const ws = new WebSocket('wss://fstream.binance.com/ws/!forceOrder@arr');
+ let ping;
+
+ ws.on('open', () => {
+ console.log('[Binance] connected');
+ ping = setInterval(() => ws.ping(), 20_000);
+ });
+
+ ws.on('message', (data) => {
+ try {
+ const msg = JSON.parse(data.toString());
+ const o = msg.o;
+ if (!o) return;
+ const base = String(o.s).replace('USDT', '').replace('BUSD', '');
+ if (!TRACKED.includes(base)) return;
+ const price = parseFloat(o.ap || o.p);
+ const qty = parseFloat(o.q);
+ if (isNaN(price) || isNaN(qty)) return;
+ push({
+ exchange: 'Binance',
+ price,
+ qty,
+ side: o.S === 'BUY' ? 'SHORT' : 'LONG',
+ symbol: base,
+ time: o.T ?? Date.now(),
+ value: price * qty,
+ });
+ } catch {}
+ });
+
+ ws.on('close', () => {
+ clearInterval(ping);
+ console.log('[Binance] disconnected — reconnecting in 5s');
+ setTimeout(connectBinance, 5_000);
+ });
+
+ ws.on('error', (err) => {
+ console.error('[Binance] error', err.message);
+ ws.terminate();
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Bybit — public stream: wss://stream.bybit.com/v5/public/linear
+// Topics: liquidation.{SYMBOL}USDT
+// ---------------------------------------------------------------------------
+
+function connectBybit() {
+ const ws = new WebSocket('wss://stream.bybit.com/v5/public/linear');
+ let ping;
+
+ ws.on('open', () => {
+ console.log('[Bybit] connected');
+ const args = TRACKED.map((s) => `liquidation.${s}USDT`);
+ ws.send(JSON.stringify({ op: 'subscribe', args }));
+ ping = setInterval(() => ws.send(JSON.stringify({ op: 'ping' })), 20_000);
+ });
+
+ ws.on('message', (data) => {
+ try {
+ const msg = JSON.parse(data.toString());
+ // skip pong / subscribe confirmations
+ if (msg.op || !msg.data) return;
+ const d = msg.data;
+ const base = (d.symbol ?? '').replace('USDT', '');
+ if (!TRACKED.includes(base)) return;
+ const price = parseFloat(d.price);
+ const qty = parseFloat(d.size);
+ if (isNaN(price) || isNaN(qty)) return;
+ push({
+ exchange: 'Bybit',
+ price,
+ qty,
+ side: d.side === 'Buy' ? 'SHORT' : 'LONG',
+ symbol: base,
+ time: Number(d.updatedTime ?? d.updateTime) || Date.now(),
+ value: price * qty,
+ });
+ } catch {}
+ });
+
+ ws.on('close', () => {
+ clearInterval(ping);
+ console.log('[Bybit] disconnected — reconnecting in 5s');
+ setTimeout(connectBybit, 5_000);
+ });
+
+ ws.on('error', (err) => {
+ console.error('[Bybit] error', err.message);
+ ws.terminate();
+ });
+}
+
+// ---------------------------------------------------------------------------
+// OKX — public stream: wss://ws.okx.com:8443/ws/v5/public
+// Channel: liquidation-orders (all SWAP instruments, real-time)
+// ---------------------------------------------------------------------------
+
+function connectOKX() {
+ const ws = new WebSocket('wss://ws.okx.com:8443/ws/v5/public');
+ let ping;
+
+ ws.on('open', () => {
+ console.log('[OKX] connected');
+ ws.send(
+ JSON.stringify({
+ op: 'subscribe',
+ args: [{ channel: 'liquidation-orders', instType: 'SWAP' }],
+ }),
+ );
+ ping = setInterval(() => ws.send('ping'), 20_000);
+ });
+
+ ws.on('message', (data) => {
+ try {
+ const text = data.toString();
+ if (text === 'pong') return;
+ const msg = JSON.parse(text);
+ if (msg.event) return; // subscribe ack
+ if (!Array.isArray(msg.data)) return;
+ for (const item of msg.data) {
+ const base = String(item.instId).split('-')[0];
+ if (!TRACKED.includes(base)) continue;
+ for (const d of item.details ?? []) {
+ const price = parseFloat(d.bkPx);
+ const qty = parseFloat(d.sz);
+ if (isNaN(price) || isNaN(qty)) continue;
+ push({
+ exchange: 'OKX',
+ price,
+ qty,
+ side: d.side === 'buy' ? 'SHORT' : 'LONG',
+ symbol: base,
+ time: parseInt(d.ts) || Date.now(),
+ value: price * qty,
+ });
+ }
+ }
+ } catch {}
+ });
+
+ ws.on('close', () => {
+ clearInterval(ping);
+ console.log('[OKX] disconnected — reconnecting in 5s');
+ setTimeout(connectOKX, 5_000);
+ });
+
+ ws.on('error', (err) => {
+ console.error('[OKX] error', err.message);
+ ws.terminate();
+ });
+}
+
+// ---------------------------------------------------------------------------
+// REST API (consumed by api/coin/liquidations.js)
+// ---------------------------------------------------------------------------
+
+function buildSnapshot() {
+ const cutoff = Date.now() - MAX_AGE_MS;
+ const recent = cache
+ .filter((l) => l.time > cutoff)
+ .sort((a, b) => b.time - a.time);
+
+ const longLiqs = recent.filter((l) => l.side === 'LONG');
+ const shortLiqs = recent.filter((l) => l.side === 'SHORT');
+ const longValue = longLiqs.reduce((s, l) => s + l.value, 0);
+ const shortValue = shortLiqs.reduce((s, l) => s + l.value, 0);
+
+ const bySymbol = {};
+ for (const l of recent) {
+ if (!bySymbol[l.symbol]) {
+ bySymbol[l.symbol] = { count: 0, longValue: 0, shortValue: 0, symbol: l.symbol };
+ }
+ bySymbol[l.symbol].count++;
+ if (l.side === 'LONG') bySymbol[l.symbol].longValue += l.value;
+ else bySymbol[l.symbol].shortValue += l.value;
+ }
+
+ return {
+ liquidations: recent.slice(0, 50),
+ summary: {
+ dominantSide:
+ longValue > shortValue * 1.5
+ ? 'LONG PAIN'
+ : shortValue > longValue * 1.5
+ ? 'SHORT SQUEEZE'
+ : 'BALANCED',
+ largeCount: recent.filter((l) => l.severity === 'LARGE').length,
+ longCount: longLiqs.length,
+ longValue,
+ megaCount: recent.filter((l) => l.severity === 'MEGA').length,
+ shortCount: shortLiqs.length,
+ shortValue,
+ totalCount: recent.length,
+ totalValue: longValue + shortValue,
+ },
+ symbolStats: Object.values(bySymbol).sort(
+ (a, b) => b.longValue + b.shortValue - (a.longValue + a.shortValue),
+ ),
+ timestamp: new Date().toISOString(),
+ };
+}
+
+function sendJson(res, status, body) {
+ const payload = JSON.stringify(body);
+ res.writeHead(status, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'content-length': Buffer.byteLength(payload),
+ 'access-control-allow-origin': '*',
+ });
+ res.end(payload);
+}
+
+const server = createServer((req, res) => {
+ const url = new URL(req.url ?? '/', 'http://localhost');
+
+ if (req.method === 'OPTIONS') {
+ res.writeHead(204, {
+ 'access-control-allow-origin': '*',
+ 'access-control-allow-methods': 'GET, OPTIONS',
+ });
+ res.end();
+ return;
+ }
+
+ if (req.method !== 'GET') {
+ sendJson(res, 405, { error: 'method_not_allowed' });
+ return;
+ }
+
+ if (url.pathname === '/health') {
+ sendJson(res, 200, { ok: true, cached: cache.length, uptime: process.uptime() });
+ return;
+ }
+
+ if (url.pathname === '/liquidations') {
+ sendJson(res, 200, buildSnapshot());
+ return;
+ }
+
+ sendJson(res, 404, { error: 'not_found' });
+});
+
+// ---------------------------------------------------------------------------
+// Boot
+// ---------------------------------------------------------------------------
+
+connectBinance();
+connectBybit();
+connectOKX();
+
+const port = parseInt(process.env.PORT ?? '3033', 10);
+server.listen(port, () => {
+ console.log(`liquidation-collector listening on :${port}`);
+});