# Arbitron Terminal > Browser & Telegram Mini App multi-market trading workspace (CEX, Perp-DEX, DEX, TradFi & prediction markets) with native Remote MCP control and zero server-side tick storage. ## Key Pages - [Terminal App](https://arbitron.dev/): Live multi-tile BSP trading workspace - [Overview](https://arbitron.dev/overview): Architecture, native windows, supported market classes and Telegram entry - [Curated Desks](https://arbitron.dev/desks): Ready-to-open workspace presets for arbitrage, funding, DEX dossier, predictions and scalping - [MCP & CLI Documentation](https://arbitron.dev/docs/mcp): Remote MCP endpoint (https://arbitron.dev/mcp), live tool catalog, Claude Code / Cursor / Codex / @arbitron/cli setup - [Full LLM Reference](https://arbitron.dev/llms-full.txt): Complete technical specification and agent contract - [MCP Server Card](https://arbitron.dev/.well-known/mcp/server-card.json): Machine-readable discovery manifest ## Native Windows - **Chart (TradingView Advanced)** (`chart`): Multi-venue CEX, Perp-DEX, DEX & TradFi candles, customizable Token-State HUD and programmatic drawing primitives. - **Spread A/B** (`spread`): Interactive cross-exchange spread candles, funding A/B sparkline, net PnL calculator, L2 VWAP impact and open transfer-route check. - **Inefficiency Scanner** (`scanner`): Real-time Perp-Perp, Spot-Fut and Spot-Spot spreads with open deposit/withdrawal networks, funding APR, OI anomalies and prediction forks. - **Orderbook (Single & Aggregated L2)** (`orderbook`): Live depth across venues, whale wall detection, one-click wall-to-chart zone overlays and CVD trade flow. - **Tape & Whale Flow** (`tape`): Real-time trade stream, large print filtering, buy/sell delta and live flow telemetry. - **Watchlist** (`watchlist`): Customizable Pro DataTable with AST formula columns, custom sorting, filters and instant LinkGroup sync. - **Prediction Markets** (`prediction`): Live event-market odds, cross-venue forks and fast correlation charting. - **News & Macro Calendar** (`news`): Real-time crypto and macro headlines paired with high-impact scheduled events. - **On-Chain Explorer & DEX Dossier** (`explorer`): Token security checks, holder distribution, liquidity pools and wallet inspection across chains. - **AI Analyst & Sandbox** (`agent`): Context-bound market verdicts plus CSP-hardened custom sandbox views built by your MCP agent. ## Curated Desk Presets - [Perp-DEX Arbitrage (HL / Aster / Lighter)](https://arbitron.dev/d/perp-dex-arb): Cross-exchange perpetual spread scanner, interactive A/B spread chart, aggregated L2 orderbook and AI execution risk analyst. - [Funding Farm Desk](https://arbitron.dev/d/funding-farm): Cross-venue funding rate rankings, annualized APR differentials, open-interest anomalies and synced multi-leg perpetual charts. - [DEX Token Dossier](https://arbitron.dev/d/dex-token-dossier): On-chain DEX candles side by side with token security checks, holder concentration, liquidity pools and multi-chain explorer. - [Prediction Forks](https://arbitron.dev/d/prediction-forks): Event market odds comparison, cross-venue forks, real-time catalyst news feed and correlated crypto reaction charts. - [Scalp Microstructure](https://arbitron.dev/d/scalp-microstructure): Low-latency aggregated L2 depth, whale wall zone overlays on charts, real-time trade tape, CVD flow and customizable scalp HUD. ## Remote MCP & CLI - Streamable HTTP MCP Endpoint: `https://arbitron.dev/mcp` (protocol `2025-06-18`, Bearer auth via `@arbdevbot` / `arbitron.dev`) - CLI Package: `@arbitron/cli` (full parity with Remote MCP) - Telegram Bot & Mini App: https://t.me/arbdevbot and https://t.me/arbdevbot/app ## Ecosystem - [OpenAPI Hub](https://openapihub.dev): Unified crypto, DEX, Perp-DEX & prediction market data API - [LLMASS](https://llmass.arbitron.dev): Unified LLM API gateway - [Arbitron Main Channel](https://t.me/arbitron_lfg): Market inefficiencies, releases & updates - [Arbitron Terminal Updates](https://t.me/arbitron_dev): Changelogs, desks & terminal news --- # Arbitron Agent Core API (/v1) (Spec v2) Base URL: `https://arbitron.dev` ## Quick Start 1. Issue a personal token: POST https://arbitron.dev/v1/tokens/issue → { token: "arb_...", accountId } (or use an existing Bearer token). 2. Create an area: PUT https://arbitron.dev/v1/areas/main with Authorization: Bearer , If-Match: 0, and JSON {"title":"BTC Desk"} (returns 409 AREA_EXISTS if it already exists — use apply_ops to update). 3. Dry-run validate custom widget ESM code with POST https://arbitron.dev/v1/widgets/validate (or MCP arbitron_validate_widget) before applying ops. 4. Populate panes atomically via POST https://arbitron.dev/v1/areas/main/ops — mix the 10 native windows (chart, spread, tape, watchlist, prediction, news, explorer, scanner, agent, orderbook) and custom JS sandbox widgets. 5. Subscribe to live updates via SSE GET https://arbitron.dev/v1/events (area.updated, area.deleted, widget.state, widget.error) and check /v1/areas/:id/errors after changes. 6. Read market data through GET https://arbitron.dev/v1/data/* (authenticated read-only alias over /api/* powered by api-hub). ## Platform Reuse Rules — DO NOT Reinvent Native UI ### Rule 1 — Compose the 10 Native Windows first chart, spread, tape, watchlist, prediction, news, explorer, scanner, agent, and orderbook already exist natively with live WebSockets, TradingView charts, drawings, $ctx bindings, and LinkGroup sync. - NEVER rebuild candlestick charts, spread charts, trade tapes, watchlists, prediction lists, news feeds, block explorers, inefficiency scanners, AI analyst panes, or L2 orderbooks inside a sandbox widget. - Place native windows with add_widget (kind: 'chart' | 'spread' | 'tape' | 'watchlist' | 'prediction' | 'news' | 'explorer' | 'scanner' | 'agent' | 'orderbook') and synchronize them via linkGroup ('blue' | 'amber' | 'green' | 'purple') or reactive bind: { param: '$ctx.key' }. - Write custom kind: 'sandbox' widgets ONLY for genuinely new logic (token dossiers, multi-source aggregators, custom calculators, signals). ### Rule 2 — Reuse Native Instrument Search & LinkGroup NEVER build a custom token search bar or autocomplete dropdown inside a sandbox widget; delegate selection and navigation to the terminal host. - arbitron.pickInstrument({ scope?: 'all'|'cex'|'dex'|'tradfi', placeholder? }) — opens the terminal's native QuickSearchModal and resolves to the chosen ChartInstrument (or null if cancelled). - arbitron.ui.instrumentPicker({ into?, value?, scope?, label?, placeholder?, onChange? }) — ready-made themed button showing the current instrument with logo + badge that opens QuickSearchModal. - arbitron.instrument & arbitron.onInstrument(cb) — automatically track the tile's native LinkGroup dot in the SandboxTile header. - arbitron.openInstrument(symbolOrInst, { target?: 'linked' | 'new-chart' | 'tape' }) — opens or switches a native chart/tape pane when the user clicks a token in your widget. - arbitron.openExplorer(address, chainId?) — opens or focuses a native explorer pane for a wallet, contract, or tx hash. ### Rule 3 — Universal Server Images / Logos (via /api/media) NEVER put https://... URLs in inside a sandbox widget (blocked by sandbox CSP img-src data: blob:). - Use arbitron.ui.logo({ into?, url?, symbol?, chainId?, exchange?, size?, class? }) — renders the exact same logo component used across Arbitron, fetching server-proxied /api/media images as host-cached data: URLs with optional DEX chain mini-badge and automatic monogram fallback. - Or use declarative — auto-hydrated by the sandbox runtime over MessageChannel through /api/media. ### Rule 4 — Platform Utilities & Unified Formatters Use host-backed utilities and shared terminal formatters instead of blocked browser APIs or ad-hoc number/address formatting. - arbitron.copy(text) — copies to clipboard via host and shows a native toast (NEVER use navigator.clipboard, which is blocked in sandboxed iframes). - arbitron.toast(text, tone?) — displays a native terminal toast ('info' | 'success' | 'warning' | 'error'). - arbitron.openLink(url) — safely opens an external https:// URL via host on user click (NEVER use window.open). - arbitron.format — unified terminal formatters: price(n) with subscript notation (e.g. 0.0₅3546 for tiny DEX prices), shortenAddress(addr), age(ms), compact(n), percent(n)/pct(n), qty(n)/num(n), rate(n), time(ms), date(ms), ticker(sym). ## Agent Window & Customization Rules (Mandatory) ### 1. Customize Native Charts Before Writing a Sandbox Widget Never spin up a custom sandbox tile when native chart HUD badges, corner HUD popups, TradingView indicators, price overlays, or server-side scripts already solve the job. - Customize the Arcways-style Token-State HUD (`mode: 'strip' | 'card' | 'header' | 'off'`, presets `'perp-scalp' | 'funding-arb' | 'dex-dossier' | 'minimal'`, 18 built-in fields, plus up to 8 custom zero-eval AST `expr` or `catalog` fields) via `arbitron_ui_command(action='set_chart_hud', hudConfig={...}, applyToAll?)` or declaratively via `widget.params.hud`. - Add ad-hoc token info badges or corner HUD popups (`top-left` | `top-right` | `bottom-left` | `bottom-right`) via `arbitron_ui_command(action='set_chart_hud')` with `headerBadges`, `cards`, or `autoTokenHud: true`. Clear with `clear_chart_hud`. - Add or remove any TradingView indicator (`EMA`, `SMA`, `RSI`, `MACD`, `VWAP`, `Bollinger Bands`, `ATR`, `Stochastic`, `Ichimoku`, or exact TV study name) -> use `arbitron_ui_command(action='add_indicator' | 'remove_indicator')`. - Plot rich programmatic drawings (all 8 primitives: `hline`, `vline`, `marker`, `trendline`, `ray`, `zone` orderblock/FVG box, `fib` retracement, `position` Long/Short R:R setup) -> use `arbitron_ui_command(action='set_overlays' | 'clear_overlays')` or declaratively via `widget.params.overlays`. - Run background auto-updating checks or alerts (even when the browser is closed) -> use `arbitron_create_alert(kind='expr', dataSources=[...])` or `arbitron_manage_analyst_specs`. - Inspect everything currently open in the user's browser (including `/d/`, `$ctx`, active TV `studies`, corner `hudCards`, chart `hudConfigs`, `tables`, and `collapsedWidgets`) via `arbitron_get_session`. ### 1b. Customize Native Tables Before Writing a Sandbox Table Never rewrite Scanner, Watchlist, Tape, News/Calendar, Predictions, or Explorer tables in a sandbox widget when native table configuration already solves the task. - Inspect every open native table's available/visible columns, sort, customColumnIds, activeFilterCount, and rowCount via `arbitron_get_session` (`session.tables`). - Customize any native table live via `arbitron_ui_command(action='configure_table', widgetId, ...)` or declaratively via `widget.params.table` (up to 16 KiB params): reorder (`columnOrder`), hide/show (`hideColumns` / `showColumns` / `hiddenColumns`), resize (`columnWidths`), sort (`sort`), filter (`filters`, `searchQuery`, `presetFilters`), icons (`auto`|`minimal`|`off`), density (`compact`|`comfortable`), or `reset: true`. - Add up to 8 custom columns per table (`upsertCustomColumns` / `customColumns`) of 4 kinds: `expr` (safe zero-eval AST formulas with `abs/min/max/round/floor/ceil/clamp/coalesce/if/pct/bps/lower/upper/len`), `field` (dot-path into row fields), `metric` (live `price`/`change24hPct`/`volume24hUsd`/`fundingAprPct`/`oiUsd`/`maxSpreadPct`/`l2SpreadBps`/`dexLiquidityUsd`/etc.), or `catalog` (up to 3 api-hub Data Catalog batch-proxied routes via `POST /api/catalog/batch`), with optional `toneRule` and validated `hrefTemplate` (`https:///...` or `/w/...` | `/d/...`). - When you DO build a custom sandbox table for a truly novel view, always use `arbitron.ui.table({ columns, data, rowKey, reorderable, resizable, columnPicker, searchable, persistKey, bindParamsTable })` together with `arbitron.ui.assetBadge` and `arbitron.ui.venueBadge` instead of raw hand-rolled `` HTML. ### 2. Strict Terminal Aesthetic (No-AI-Slop) Every sandbox widget must look indistinguishable from native Arbitron terminal panes in both dark and light themes. - Use flat matte surfaces (`var(--bg)`, `var(--surface)`, `var(--surface-soft)`, `var(--surface-2)`), 1px hairline borders (`var(--line)` / `var(--edge)`), and `4px` corners (`var(--radius)`). - FORBIDDEN: cards nested inside cards, 999px oval status pills with glowing dots, `#hashtags`, decorative gradients, heavy drop shadows, oversized colored CTA buttons, and hardcoded hex colors instead of CSS theme variables. ### 3. Zero-Jitter Live Updates (No Layout Shifts) Live polling updates must never shift columns, jump rows, flash scrollbars, or destroy scroll/focus state. - Format all prices, percentages, and numeric columns with `font-variant-numeric: tabular-nums` (use `.a-num` / `.a-kpi-val` / `.a-table`) and fixed or `min-width` columns with `text-overflow: ellipsis`. - Place refresh/loading status, timestamps, and source counts in a fixed single-line widget header (`.a-header-status`) — NEVER mount/unmount status banners above tables or content on each poll tick. - On timer updates (`arbitron.data.subscribe` / `arbitron.data.poll` with `every >= 3000ms`), update DOM nodes in place (`textContent` or keyed row diffing) — NEVER wipe `root.innerHTML = ''` every tick. ### 4. Hyperlinks (Internal Desk + External Exchange/Explorer) Every navigation target or external venue/explorer jump must be a real, accessible hyperlink. - Internal transitions (switching `$ctx`, desk, or view): render real `` so right-click and Cmd/Ctrl+Click work natively. - External exchange / DEX / block explorer links: build URLs with `arbitron.links.exchange(symbolOrInst)`, `arbitron.links.dex(chainId, tokenAddress)`, or `arbitron.links.explorer(chainId, addressOrTx)` (never hand-craft brittle URLs) and render real `` — the sandbox runtime automatically intercepts clicks with a user gesture and opens them safely via host `openLink`. ### 5. Script Data Refresh, Sync & Limits Respect sandbox CSP isolation, polling minimums, server-side alert execution, and reactive synchronization. - Always fetch data via `arbitron.data.get` / `arbitron.data.subscribe` (alias `arbitron.data.poll`, minimum interval `3000ms`) or `arbitron.catalog.query` — NEVER call `fetch()` or `WebSocket` directly (blocked by CSP `default-src 'none'`). - Sandbox widgets can also update native chart HUDs and indicators directly via `arbitron.chart.setHud(payload)`, `arbitron.chart.clearHud(cardIds?)`, `arbitron.chart.addIndicator(name, opts?)`, and `arbitron.chart.removeIndicator(opts?)`. - For background monitoring and notifications when the browser tab is closed, create a server-side `expr` alert (`arbitron_create_alert`) with `dataSources`. - Persist widget state in `arbitron.state.set` / `patch` (never `localStorage`) and subscribe via `arbitron.onInstrument` / `arbitron.onCtx` for reactive sync with `linkGroup` and `$ctx`. ## Authentication - Header: `Authorization: Bearer ` - Token format: `arb_<48 lowercase hex chars> (or static tokens configured via ARBITRON_AGENT_TOKENS / POLE_TOKENS)` - Issue endpoint: `POST https://arbitron.dev/v1/tokens/issue` - Each token maps deterministically to accountId = sha256(token).slice(0, 16). Accounts are strictly isolated. - Never log or expose raw Bearer tokens in widget code or error payloads. - Pass optional X-Arbitron-Client: header on mutations so SSE clients can ignore self-originated updates. ## Limits - Max widgets per area: **12** - Max areas per account: **10** - Max layout tree depth: **24** - Max code module size: **128 KiB** - Max params JSON size: **16 KiB** - Max widget state JSON size: **64 KiB** - Max ops per batch: **50** - Max retained errors per account: **50** ## MCP Tools (26 tools — `/mcp` Streamable HTTP & `arbitron mcp` stdio) | Tool | Kind | Arguments | Summary | |---|---|---|---| | `arbitron_docs` | read | `{ format?: 'md' \| 'json' }` | Fetch full Arbitron API, SDK, CSP, and market-data specification. Call first. | | `arbitron_list_areas` | read | `{}` | List all workspaces (areas) in the authenticated account. | | `arbitron_get_area` | read | `{ areaId, includeCode?: boolean }` | Read one area's layout, widgets, rev, state, and optional transitive source map. | | `arbitron_create_area` | write | `{ areaId, name? }` | Create a new empty area. Returns 409 AREA_EXISTS if areaId already exists (use arbitron_apply_ops to update). | | `arbitron_apply_ops` | write | `{ areaId, ops: Op[], ifMatch? }` | Atomically apply 1..50 operations (add_widget, set_code, edit_code, set_params, set_bind, set_title, remove_widget, rename, set_layout). | | `arbitron_delete_area` | destructive | `{ areaId, ifMatch? }` | Permanently delete an area and its persisted widget states (emits SSE area.deleted). | | `arbitron_get_widget_code` | read | `{ areaId, widgetId }` | Read a sandbox widget's current source code and SHA-256 hash. | | `arbitron_get_widget_state` | read | `{ areaId, widgetId }` | Read persisted JSON state ({ value, updatedAt }) for a widget. | | `arbitron_set_widget_state` | write | `{ areaId, widgetId, value }` | Write persisted JSON state (<= 64 KiB) for a widget and emit SSE widget.state. | | `arbitron_widget_errors` | read | `{ areaId, widgetId? }` | List recent runtime errors reported by sandboxed widgets in an area. | | `arbitron_validate_widget` | read | `{ code? \| areaId, widgetId }` | Dry-run validate widget ESM syntax (V8 --check), module imports, CSP rules, and sandbox API paths without executing code. | | `arbitron_save_module` | write | `{ code }` | Store a shared ESM module in content-addressed storage → { hash, bytes } for arbitron:code/ imports. | | `arbitron_query_data` | read | `{ path, params?, maxChars? }` | Query any of the allowlisted read-only market data endpoints with automatic response-size guard (default maxChars=24000). | | `arbitron_get_session` | read | `{}` | Read full live terminal session state (activeAreaId, theme, zoomWidgetId, activeWidgetId, ctx, sharedDeskHash, sharedDeskTitle, url, studies, hudCards, hudConfigs, collapsedWidgets, tables, connectedClients) along with open areas summary. | | `arbitron_ui_command` | write | `{ action, areaId?, theme?, widgetId?, linkGroup?, widgetA?, widgetB?, symbol?, tf?, overlays?, ids?, legA?, legB?, coin?, formula?, ctx?, viewId?, hash?, presetId?, preset?, message?, tone?, tool?, mode?, scope?, name?, forceOverlay?, inputs?, overrides?, studyId?, autoTokenHud?, replace?, headerBadges?, cards?, hudConfig?, applyToAll?, cardIds?, collapsed?, all?, view?, reset?, sort?, columnOrder?, hideColumns?, showColumns?, hiddenColumns?, columnWidths?, upsertCustomColumns?, removeCustomColumnIds?, customColumns?, filters?, searchQuery?, presetFilters?, icons?, density? }` | Control live terminal UI via SSE ui.command (29 actions: layout, instruments, 8 programmatic overlay primitives, TV indicators, customizable Arcways chart HUD strip/card/header via set_chart_hud.hudConfig, mobile collapse, native table configuration via configure_table, spread pairs, $ctx, desks, watchlist, toast, drawing tools). | | `arbitron_catalog_search` | read | `{ q?, provider?, category?, plane?, tag?, limit? }` | Search the unified api-hub Data Catalog across all connected providers and routes. | | `arbitron_catalog_query` | read | `{ routeId, params?, body?, maxChars? }` | Execute any public REST/explorer route from the api-hub Data Catalog with response-size guard. | | `arbitron_desk_publish` | write | `{ desk? \| areaId?, title? }` | Publish an immutable content-addressed shareable Desk snapshot (/d/) from a DeskDoc or existing area. | | `arbitron_list_desks` | read | `{ hash?, deskId?, includePresets? }` | List curated built-in Desk presets and authenticated account desks, or fetch a specific desk by hash or deskId. | | `arbitron_fork_desk` | write | `{ hash?, presetId?, id?, title? }` | Fork any published /d/ Desk snapshot or built-in preset into the authenticated account. | | `arbitron_run_analyst` | read | `{ specId, ctx?, force? }` | Run a server-managed AgentActor analyst (spread-verdict, funding-radar, token-dossier, or specHash) on $ctx and get a structured verdict. | | `arbitron_manage_analyst_specs` | write | `{ action?: 'list' \| 'register', id?, title?, instructions?, tools?, bind?, cacheKey?, cooldownSec?, outputSchema? }` | List built-in & custom AI analyst specs or register a custom server-managed AgentActor spec. | | `arbitron_orderbook_depth` | read | `{ symbol, symbolB?, sizeUsd? }` | Fetch L2 orderbook depth & detected walls for a Perp-DEX symbol, or simulate cross-venue VWAP spread execution when symbolB is provided. | | `arbitron_create_alert` | write | `{ kind, symbol?, threshold?, expr?, dataSources?, title?, cooldownSec?, messageTemplate?, channels?, webhookUrl?, webhookFormat?, webhookHeaders?, telegramChatId?, telegramBotToken?, pushoverUserKey?, pushoverAppToken? }` | Create a server-side alert rule (built-in kinds or programmable safe 'expr' DSL with optional catalog dataSources) and multi-channel delivery (web, JSON/Discord/Slack webhook, Telegram, Pushover). | | `arbitron_update_alert` | write | `{ id?, enabled?, title?, kind?, symbol?, symbolB?, venue?, threshold?, expr?, dataSources?, cooldownSec?, messageTemplate?, channels?, webhookUrl?, webhookFormat?, telegramChatId?, telegramBotToken?, pushoverUserKey?, pushoverAppToken?, ackEvents?, test? }` | Update/pause/resume an alert rule, trigger a live test delivery (test: true), or acknowledge alert events (ackEvents: true). | | `arbitron_list_alerts` | read | `{ deleteId?, includeEvents? }` | List server-side alert rules (and optionally recent events), or delete an alert rule by deleteId. | ## Endpoints (`/v1/*`) | Method | Path | Auth | Summary | |---|---|---|---| | `GET` | `/v1/docs` | public | Full JSON agent specification (?format=md for Markdown). | | `POST` | `/v1/tokens/issue` | public | Issue a new personal arb_<48hex> token (strict rate-limit). | | `POST` | `/v1/code` | bearer | Store content-addressed JS ES-module code → { hash, bytes }. | | `GET` | `/v1/code/:hash` | bearer | Fetch JS module source by SHA-256 hash. | | `POST` | `/v1/widgets/validate` | bearer | Dry-run validate widget ESM syntax, imports, CSP rules, and sandbox API paths ({ code? \| areaId, widgetId }). | | `GET` | `/v1/areas` | bearer | List all areas for the authenticated account. | | `GET` | `/v1/areas/:id` | bearer | Get area doc, ETag rev, widget states; ?include=code adds transitive JS code map. | | `PUT` | `/v1/areas/:id` | bearer | Create or replace an area (If-Match: 0 returns 409 AREA_EXISTS if it already exists; other mismatches return 409 REVISION_CONFLICT). | | `DELETE` | `/v1/areas/:id` | bearer | Delete an area and its widget states (emits SSE area.deleted). | | `POST` | `/v1/areas/:id/ops` | bearer | Apply 1..50 atomic operations (all-or-nothing, supports If-Match, emits SSE area.updated). | | `GET` | `/v1/areas/:id/widgets/:widgetId/state` | bearer | Read persisted JSON state for one widget. | | `PUT` | `/v1/areas/:id/widgets/:widgetId/state` | bearer | Save widget JSON state (<= 64 KiB, emits SSE widget.state). | | `GET` | `/v1/areas/:id/errors` | bearer | List recent deduplicated runtime errors for an area (?widget=). | | `POST` | `/v1/areas/:id/errors` | bearer | Report a widget runtime error (deduplicated, emits SSE widget.error). | | `GET` | `/v1/session` | bearer | Get live terminal session snapshot (activeAreaId, theme, zoomWidgetId, activeWidgetId, ctx, sharedDeskHash, sharedDeskTitle, url, studies, hudCards, hudConfigs, collapsedWidgets, tables, connectedClients). | | `PUT` | `/v1/session` | bearer | Update live terminal session snapshot (including ctx, sharedDeskHash, url, studies, hudCards, hudConfigs, collapsedWidgets, tables) and emit SSE session.updated. | | `POST` | `/v1/session/command` | bearer | Dispatch any of the 29 live UI commands (switch_area, set_theme, zoom_widget, set_link_group, swap_widgets, set_instrument, set_timeframe, set_overlays, clear_overlays, open_spread_pair, swap_spread_legs, set_spread_formula, set_ctx, load_desk, fork_desk, apply_preset, undo, watchlist_add, watchlist_remove, show_toast, drawing_tool, drawing_magnet, drawing_clear, add_indicator, remove_indicator, set_chart_hud, clear_chart_hud, set_mobile_collapsed, configure_table) via SSE ui.command. | | `GET` | `/v1/events` | bearer | Per-account SSE stream (area.updated, area.deleted, widget.state, widget.error, session.updated, ui.command). | | `GET` | `/v1/data/*` | bearer | Authenticated read-only market data routes (same endpoints as /api/* and sandbox). | | `GET` | `/api/media?url=...` | public | Allowlisted media & logo proxy (local /assets/chains/* + /assets/venues/* + /arbitron-mark.png and allowlisted HTTPS image CDNs; <= 256 KiB, SVG-sanitized, cached; used automatically by arbitron.ui.logo, assetBadge, venueBadge and data-arbitron-src). | | `GET` | `/api/catalog/search` | public | Search unified api-hub Data Catalog across all connected providers (hyperliquid, aster, lighter, dydx, deribit, coinglass, polymarket, kalshi, etc.). | | `POST` | `/api/catalog/route` | public | Execute a public api-hub catalog route by { routeId, params?, body? } with TTL caching and safety checks. | | `POST` | `/api/catalog/batch` | public | Execute up to 20 public read-only api-hub catalog routes in one batch ({ requests: [{ key?, routeId, params? }] }) with concurrency=4 and TTL caching. | | `GET` | `/api/scanner/inefficiencies` | public | Aggregated cross-venue spreads, funding rates/arbitrage APR, OI/mark-oracle anomalies, and Polymarket<->Kalshi forks. | | `POST` | `/api/desks/publish` | public | Publish an immutable content-addressed Desk snapshot -> { hash, shortHash, url: '/d//' }. | | `GET` | `/api/desks/presets` | public | List built-in curated Desk templates (Perp-DEX Arb, Funding Farm, DEX Dossier, Prediction Forks, Scalp Microstructure) with deterministic shortHash. | | `GET` | `/api/desks/:hash` | public | Read an immutable content-addressed Desk snapshot (or built-in preset) by 12..64 hex hash. | | `GET` | `/api/orderbook/depth` | public | L2 orderbook depth snapshot with wall detection and imbalance across Hyperliquid, Aster, dYdX, Lighter, and Deribit (?symbol=HYPERLIQUID:BTCUSDC.P&force=0\|1). | | `GET` | `/api/orderbook/spread-sim` | public | Cross-venue VWAP execution simulator for a target notional size (?a=...&b=...&sizeUsd=10000&feeABps=4&feeBBps=4). | | `GET` | `/api/agents/:specId/stream` | public | SSE stream from Managed Backend AgentActor analyst (spread-verdict, funding-radar, token-dossier, or custom specHash) with single-flight semantic caching. | | `GET` | `/v1/alerts` | bearer | List per-account server-side alert rules. | | `POST` | `/v1/alerts` | bearer | Create a server-side alert rule (spread_pct, funding_apr, price_above, price_below, oi_spike, prediction_fork, wall_detected, expr) with full channel config (web, webhook JSON/Discord/Slack, Telegram, Pushover) and messageTemplate. | | `PATCH` | `/v1/alerts/:id` | bearer | Update, pause/resume, or edit an alert rule's expr, threshold, messageTemplate, or channels. | | `POST` | `/v1/alerts/:id/test` | bearer | Evaluate and send a test alert delivery across all configured channels for a rule. | | `GET` | `/v1/alerts/events` | bearer | List recent triggered alert events (?limit=25). | | `POST` | `/v1/alerts/ack` | bearer | Acknowledge all unacknowledged alert events for the authenticated account. | | `GET` | `/v1/alerts/stream` | bearer | Per-account SSE stream for real-time triggered alerts. | | `GET` | `/v1/auth/status` | public | Read Telegram auth configuration and linked account status (supports Bearer or session cookie). | | `GET` | `/v1/auth/tokens` | bearer | List named revocable MCP tokens (arbmcp_...) for the authenticated account. | ## Widget Kinds (Native & Sandbox) | Kind | Description | Example Params | |---|---|---| | `sandbox` | Custom JS ES-module widget executed inside the isolated sandbox with the arbitron/pole SDK. Optional params: linkGroup ('none'\|'blue'\|'amber'\|'green'\|'purple'), symbol, table (TableConfigSpec for ui.table bindParamsTable), plus any custom JSON keys (<= 16 KiB). | `{"symbol":"BINANCE:BTCUSDT","linkGroup":"blue","everyMs":5000}` | | `chart` | Native Arbitron candlestick & indicator chart pane (TradingView / CEX / DEX). Params: symbol (e.g. 'NASDAQ:NVDA', 'BINANCE:BTCUSDT', or DEX object { kind:'dex', symbol, chainId, tokenAddress }), tf ('1m'\|'5m'\|'15m'\|'1h'\|'4h'\|'1D' etc.), linkGroup ('none'\|'blue'\|'amber'\|'green'\|'purple'), hud (optional ChartHudConfigSpec: mode 'strip'\|'card'\|'header'\|'off', corner, density, preset, fields, hiddenFields, customFields expr/catalog), overlays (optional ChartOverlaySpec[] up to 64 drawings: hline, vline, marker, trendline, ray, zone, fib, position). | `{"symbol":"HYPERLIQUID:BTCUSDC.P","tf":"15m","linkGroup":"blue","hud":{"mode":"strip","preset":"perp-scalp"}}` | | `spread` | Native cross-exchange spread monitor pane. Params: symbol (leg A), legB (or spreadLegB / symbolB, or legs: [legA, legB]), formula ('pct'\|'diff'\|'ratio'\|'idx'), tf, linkGroup. | `{"symbol":"BINANCE:BTCUSDT.P","legB":"OKX:BTCUSDT.P","formula":"pct","tf":"15m","linkGroup":"blue"}` | | `tape` | Native live trades tape & DEX intel pane. Params: symbol (TV/CEX string or DEX object with chainId+tokenAddress), linkGroup, table (optional TableConfigSpec: sort, columnOrder, hiddenColumns, columnWidths, customColumns, filters, searchQuery, icons, density). | `{"symbol":"BINANCE:BTCUSDT","linkGroup":"blue"}` | | `watchlist` | Native multi-instrument live quotes watchlist. Params: symbols (or items / watchlistItems array of symbols or DEX objects), linkGroup, table (optional TableConfigSpec with sort, columnOrder, hiddenColumns, columnWidths, customColumns expr/field/metric/catalog, filters, searchQuery, icons, density). | `{"symbols":["NASDAQ:NVDA","NASDAQ:AMD","NASDAQ:AVGO","BINANCE:BTCUSDT"],"linkGroup":"blue"}` | | `prediction` | Native prediction markets pane (Polymarket & Kalshi) with interactive probability chart and source filter. Params: query (pre-fills live market search, e.g. 'nvidia' or 'huang'), source ('all'\|'polymarket'\|'kalshi'), table (optional TableConfigSpec). | `{"query":"nvidia","source":"polymarket"}` | | `news` | Native market news, macro economic calendar & corporate events pane. Params: tab ('news'\|'calendar'\|'events'), market ('all'\|'crypto'\|'stocks'\|'forex'), symbol (ticker to filter by), linkGroup (set non-'none', e.g. 'blue', to enable automatic ticker filtering and sync with chart), table (optional TableConfigSpec with views). | `{"tab":"news","market":"stocks","symbol":"NASDAQ:NVDA","linkGroup":"blue"}` | | `explorer` | Native on-chain address / transaction explorer across all supported chains from api-hub. Params: chain (e.g. 'ethereum'\|'solana'\|'bsc'\|'base'\|'arbitrum'), query (wallet address or tx hash to look up immediately), table (optional TableConfigSpec with views for tokens/txs). | `{"chain":"ethereum","query":"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"}` | | `scanner` | Native Inefficiency Scanner pane aggregating cross-venue spreads, funding arbitrage APR, OI/mark-oracle anomalies, and Polymarket<->Kalshi prediction forks. Params: tab ('spreads'\|'funding'\|'anomalies'\|'predictions'), table (optional TableConfigSpec with sort, columnOrder, hiddenColumns, columnWidths, customColumns expr/field/metric/catalog, filters, searchQuery, presetFilters, views). | `{"tab":"spreads"}` | | `agent` | Native Managed Backend AI Analyst pane streaming structured verdicts (OK/TRAP/WAIT/NEUTRAL), metrics, risks, and chart overlays from our server with shared semantic cache. Params: specId ('spread-verdict'\|'funding-radar'\|'token-dossier' or specHash), linkGroup. | `{"specId":"spread-verdict","linkGroup":"blue"}` | | `orderbook` | Native L2 orderbook depth & liquidity wall monitor across Perp-DEX venues (Hyperliquid, Aster, dYdX, Lighter, Deribit) with VWAP slippage simulation. Params: symbol (e.g. 'HYPERLIQUID:BTCUSDC.P'), sizeUsd (number, optional notional size for VWAP estimate), linkGroup. | `{"symbol":"HYPERLIQUID:BTCUSDC.P","sizeUsd":10000,"linkGroup":"blue"}` | ## Operations (`POST /v1/areas/:id/ops`) Send `{ "ops": [...] }` or a bare JSON array `[...]`. Pass `If-Match: ` for optimistic concurrency (returns `409 REVISION_CONFLICT` on mismatch; creating an already-existing area returns `409 AREA_EXISTS`). Batches are all-or-nothing. ### `add_widget` Add any of the 10 native windows (kind: chart|spread|tape|watchlist|prediction|news|explorer|scanner|agent|orderbook) OR a custom sandbox widget (kind: 'sandbox' + code or codeHash). Supports optional bind: Record for $ctx reactivity, plus near, side, ratio (0..1). ```json { "op": "add_widget", "id": "btc-chart", "kind": "chart", "title": "BTC · 1h", "params": { "symbol": "BINANCE:BTCUSDT", "tf": "60" }, "bind": { "symbol": "$ctx.a", "tf": "$ctx.tf" } } ``` ### `set_code` Replace code of an existing sandbox widget with inline source (`code`) or pre-uploaded `codeHash`. Marks previous errors for that widget as current: false. ```json { "op": "set_code", "widget": "my-widget", "code": "arbitron.root.textContent = 'ready';\nexport default () => {};" } ``` ### `edit_code` Targeted single-match string replacement in a sandbox widget's JS source (`find` / `replace`, with `old` / `new` aliases; search string must appear exactly once). Marks previous errors as current: false. ```json { "op": "edit_code", "widget": "my-widget", "find": "everyMs: 5000", "replace": "everyMs: 2000" } ``` ### `set_params` Replace widget params JSON object (<= 16 KiB, including optional params.table TableConfigSpec) without touching widget code; optional bind map (or null to clear) updates $ctx bindings. ```json { "op": "set_params", "widget": "btc-chart", "params": { "symbol": "BINANCE:ETHUSDT", "tf": "15" } } ``` ### `set_bind` Set or clear reactive $ctx parameter bindings ({ paramKey: '$ctx.key' }) on an existing widget (pass bind: null to clear). ```json { "op": "set_bind", "widget": "btc-chart", "bind": { "symbol": "$ctx.a", "tf": "$ctx.tf" } } ``` ### `set_title` Set widget pane header title, or pass null to clear it. ```json { "op": "set_title", "widget": "btc-chart", "title": "ETH · 15m" } ``` ### `remove_widget` Remove a widget from the area and collapse its parent split so its sibling expands. ```json { "op": "remove_widget", "widget": "btc-chart" } ``` ### `rename` Rename the area (`title`, or `name` alias). ```json { "op": "rename", "title": "Perps & News Desk" } ``` ### `set_layout` Replace the entire binary split tree ({ widget } | { axis: 'x'|'y', ratio, a, b }). Every widget must appear exactly once. ```json { "op": "set_layout", "layout": { "axis": "x", "ratio": 0.65, "a": { "widget": "btc-chart" }, "b": { "widget": "news-pane" } } } ``` ## Customizable Chart Token-State HUD (`set_chart_hud` & `widget.params.hud`) Customize the native chart Token-State HUD via `set_chart_hud` (`hudConfig`, optional `applyToAll: true`) or declaratively in `widget.params.hud` (`DeskDoc` / `AgentAreaDoc`). Supports Arcways-style top `strip`, corner `card`, compact `header` pills, or `off`, 4 built-in presets, 18 built-in market/perp/DEX fields, and up to 8 custom fields (zero-eval AST `expr` or up to 3 `catalog` api-hub routes with `toneRule` and validated `hrefTemplate`). Inspect active HUD state via `session.hudConfigs`. - Modes: `strip` | `card` | `header` | `off` - Corners: `top-left` | `top-right` | `bottom-left` | `bottom-right` - Densities: `compact` | `normal` - Presets: `perp-scalp` | `funding-arb` | `dex-dossier` | `minimal` - Built-in fields (19): `funding_rate`, `funding_countdown`, `funding_apr`, `oi_usd`, `volume_24h`, `vol_oi_ratio`, `basis_mi`, `change_24h`, `high_low_24h`, `bid_ask_spread`, `max_leverage`, `tick_size`, `dex_mcap`, `dex_liq`, `dex_holders`, `dex_top10`, `dex_risk`, `trade_link`, `networks_status` - Limits: max **20** visible fields, max **8** custom fields (max **3** `catalog`), zero-eval AST `expr` + validated `hrefTemplate`. ```json { "action": "set_chart_hud", "widgetId": "btc-chart", "hudConfig": { "mode": "strip", "preset": "funding-arb", "upsertCustomFields": [ { "id": "carry_score", "kind": "expr", "label": "Carry", "expr": "round(fundingApr / max(abs(basisPct), 0.1), 1)", "format": "number", "decimals": 1, "toneRule": { "kind": "threshold", "positiveAbove": 20, "negativeBelow": -20 } } ], "showFields": [ "carry_score" ] } } ``` ## Programmatic Chart Drawing Overlays (`set_overlays` & `widget.params.overlays`, max 64) | Kind | Fields | Notes | |---|---|---| | `hline` | `{ id, kind: 'hline', price, label?, color?, lineStyle?: 'solid'\|'dashed'\|'dotted', lineWidth?: 1..6 }` | Horizontal price level (support, resistance, liquidation, entry). | | `vline` | `{ id, kind: 'vline', timeSec, label?, color?, lineStyle?, lineWidth? }` | Vertical time marker (news release, FOMC, unlock, funding reset). | | `marker` | `{ id, kind: 'marker', timeSec, price?, text, color?, shape?: 'arrow_up'\|'arrow_down'\|'flag'\|'callout' }` | Annotated point/callout marker on a bar. | | `trendline` | `{ id, kind: 'trendline', p1: { timeSec, price }, p2: { timeSec, price }, label?, color?, lineStyle?, lineWidth?, extendLeft?, extendRight? }` | Two-point trendline with optional left/right extension. | | `ray` | `{ id, kind: 'ray', p1: { timeSec, price }, p2: { timeSec, price }, label?, color?, lineStyle?, lineWidth? }` | Two-point semi-infinite ray extending forward from p1 through p2. | | `zone` | `{ id, kind: 'zone', priceLow, priceHigh, timeStartSec?, timeEndSec?, label?, color?, fillColor?, fillOpacity?: 0..1, lineStyle?, lineWidth?, extendRight? }` | Price rectangle / orderblock / FVG / liquidity pool box. Omit timeStartSec/timeEndSec to span visible bars. | | `fib` | `{ id, kind: 'fib', p1: { timeSec, price }, p2: { timeSec, price }, levels?: number[], label?, color?, extendRight? }` | Fibonacci retracement between anchor points p1 and p2 with optional custom ratios and right extension. | | `position` | `{ id, kind: 'position', side: 'long'\|'short', entryPrice, stopPrice, targetPrice, timeStartSec?, timeEndSec?, label?, qtyUsd? }` | Long/Short risk-reward trade setup box showing entry, stop-loss, and take-profit zones. | ```json { "action": "set_overlays", "widgetId": "btc-chart", "overlays": [ { "id": "ob-1", "kind": "zone", "priceLow": 91800, "priceHigh": 92400, "label": "4h OB", "fillOpacity": 0.2, "extendRight": true }, { "id": "setup-1", "kind": "position", "side": "long", "entryPrice": 92200, "stopPrice": 91200, "targetPrice": 95200, "label": "3R Long", "qtyUsd": 5000 } ] } ``` ## Sandbox CSP & Security Rules - CSP: `default-src 'none'; script-src 'unsafe-inline' data:; style-src 'unsafe-inline'; font-src data: blob:; img-src data: blob:; base-uri 'none'; form-action 'none'` - Isolation: Opaque iframe origin (sandbox="allow-scripts", no allow-same-origin, no allow-popups) ### Forbidden in Sandbox Widgets - NO fetch() or XMLHttpRequest — all network calls are blocked by CSP default-src 'none'. Use arbitron.data.get / subscribe / source instead. - NO WebSocket — blocked by CSP. Use arbitron.data.subscribe(path, params, cb, { every }) (min interval 3000ms). - NO window.open() — blocked by iframe sandbox (no allow-popups). Use arbitron.openLink(url) on user click instead. - NO navigator.clipboard — blocked in sandboxed iframe. Use arbitron.copy(text) instead. - NO localStorage, sessionStorage, or document.cookie — throw SecurityError on opaque origin. Use arbitron.state.{get,set,patch,define,watch,onChange}. - NO external (including logoUrl returned by search or imageUrl from predictions) — blocked by img-src data: blob:. Use arbitron.ui.logo({ url, symbol, chainId, exchange, size }) or instead (loaded via host /api/media proxy). - NO external ES imports (https://..., bare npm package names) — only "arbitron:code/" and "pole:code/" modules uploaded via POST /v1/code are resolved by the importmap. ### Recommended Alternatives - Market data: arbitron.data.get(path, params), arbitron.data.subscribe(path, params, cb, { every }), or reactive arbitron.source(path, (state) => params, { every, map }). - Logos & images: arbitron.ui.logo({ url, symbol, chainId, exchange, size }) or (proxied via /api/media as cached data: URIs). - Instrument selection & navigation: arbitron.pickInstrument(), arbitron.ui.instrumentPicker(), arbitron.onInstrument(), arbitron.openInstrument(), arbitron.openExplorer(). - Clipboard, toasts & external links: arbitron.copy(text), arbitron.toast(text, tone), arbitron.openLink(url). - Persistence: arbitron.state.set / patch / get / define / watch / onChange (up to 64 KiB JSON persisted per widget). - Charts & visuals: inline SVG via arbitron.h('svg', ...), HTML5 Canvas, or built-in arbitron.ui.sparkline / arbitron.ui.chart. > Always dry-run validate widget ESM source with POST /v1/widgets/validate or MCP arbitron_validate_widget before calling apply_ops. ## Sandbox SDK (`arbitron` / `pole`) Compatible alias: `pole (compatible alias referencing the same SDK object as arbitron)`. ### Core Globals | Symbol | Signature | Description | |---|---|---| | `arbitron.root` | `HTMLElement` | Root container element for the widget pane. | | `arbitron.params` | `Readonly>` | Frozen widget params from the area document. | | `arbitron.instrument` | `ChartInstrument \| null` | Current instrument synchronized from this sandbox tile's native LinkGroup (null if unlinked or unset). | | `arbitron.onInstrument` | `(cb: (inst: ChartInstrument \| null) => void) => () => void` | Subscribe to LinkGroup instrument changes from the SandboxTile header link dot. | | `arbitron.pickInstrument` | `(opts?: { scope?: 'all'\|'cex'\|'dex'\|'tradfi', placeholder?: string }) => Promise` | Open the terminal's native QuickSearchModal and resolve with the chosen ChartInstrument (or null if cancelled). | | `arbitron.openInstrument` | `(symbolOrInst: string \| ChartInstrument, opts?: { target?: 'linked' \| 'new-chart' \| 'tape' }) => Promise` | Open or switch a native chart or tape pane when the user clicks an instrument inside the widget. | | `arbitron.openExplorer` | `(address: string, chainId?: string \| number) => Promise` | Open or focus a native explorer pane for a wallet address, contract, or transaction hash. | | `arbitron.copy` | `(text: string) => Promise` | Copy text to clipboard via host and show a native confirmation toast (use instead of blocked navigator.clipboard). | | `arbitron.toast` | `(text: string, tone?: 'info'\|'success'\|'warning'\|'error') => void` | Display a native terminal toast notification. | | `arbitron.openLink` | `(url: string) => Promise` | Safely open an external https:// URL via host on user click (use instead of blocked window.open). Regular clicks are also intercepted automatically. | | `arbitron.links` | `{ exchange(symbolOrInst): string \| null, dex(chainId, tokenAddress): string \| null, explorer(chainId, addressOrTx): string \| null }` | Build canonical external https:// URLs for exchanges (Binance, Bybit, OKX, Hyperliquid, Aster, Lighter, dYdX, Deribit, Gate, MEXC, Bitget, KuCoin), DEXScreener, and block explorers (Etherscan, Solscan, BscScan, BaseScan, Arbiscan, etc.). | | `arbitron.chart` | `{ setOverlays(overlays, target?), clearOverlays(target?), setHud(payload), clearHud(cardIds?, target?), addIndicator(name, opts?), removeIndicator(opts?) }` | Push overlays, header/corner HUD cards, or TradingView indicators directly to linked or targeted native chart panes. | | `arbitron.source` | `(path: string, params?: object \| ((state) => object), opts?: { every?: number, map?: (d) => any }) => { path, params, value, subscribe(fn) }` | Reactive data source bound to one of the 15 allowlisted sandbox API paths. When params is a function of state, automatically reconnects whenever state changes. | | `arbitron.data.get` | `(path: string, params?: Record) => Promise` | One-shot read of any of the 15 allowlisted sandbox API paths (same set as /v1/data/*). | | `arbitron.data.subscribe` | `(path: string, params: Record, cb: (data: any, info: { updatedAt, stale, error? }) => void, opts?: { every?: number }) => () => void` | Poll/subscribe to a market data route at interval `every` ms (minimum 3000 ms); returns unsubscribe function. Alias: `arbitron.data.poll`. | | `arbitron.state` | `{ value, get(key?), set(val), patch(obj), define(key, defaultVal), watch(cb), onChange(cb) }` | Per-widget persistent JSON state (<= 64 KiB) synced via /v1/areas/:id/widgets/:widgetId/state. `watch(cb)` receives merged state+defaults; `onChange(cb)` fires on BOTH local `state.set()`/`state.patch()` (including `ui.tabs`/`ui.select`/`ui.toggle` updates) AND host sync. | | `arbitron.onResize` | `(cb: ({ width, height }) => void) => () => void` | Subscribe to pane resize events (fires immediately if root already has non-zero dimensions). | | `arbitron.onTheme` | `(cb: (mode: 'dark' \| 'light') => void) => () => void` | Listen to dark/light theme switches. | | `arbitron.token` | `(name: string) => string` | Read a resolved CSS design token value (e.g. arbitron.token('accent'), 'positive', 'negative', 'text', 'muted', 'surface', 'edge'). | | `arbitron.h` | `(tag: string, props?: Record, ...children: any[]) => HTMLElement \| SVGElement` | Lightweight DOM/SVG hyperscript builder (auto-handles SVG namespace for svg/path/rect/circle/line/text/defs/linearGradient/etc.). | | `arbitron.css` | `(rules: string) => void` | Inject scoped CSS rules using theme CSS variables (--bg, --surface, --surface-soft, --surface-2, --text, --muted, --edge, --accent, --positive, --negative, --warning). | | `arbitron.format` | `{ price(n, ref?), shortenAddress(addr), age(ms), compact(n), percent(n), pct(n), qty(n), num(n), rate(n), time(ms), date(ms), ticker(sym) }` | Unified terminal formatters: price(n) with subscript notation (e.g. 0.0₅3546 for tiny DEX prices), shortenAddress(addr), age(ms), compact(n), percent/pct, qty/num, rate, time, date, ticker. | ### `arbitron.ui` Components | Component | Signature | Description | |---|---|---| | `arbitron.ui.instrumentPicker` | `({ into?, value?, scope?, label?, placeholder?, onChange? }) => { el, update(inst), destroy }` | Themed native instrument picker button displaying logo + badge; clicking opens the terminal's native QuickSearchModal. | | `arbitron.ui.logo` | `({ into?, url?, coin?, venue?, symbol?, chainId?, exchange?, size?, class? }) => { el, update(opts), destroy }` | Universal Arbitron token/coin/venue/exchange/chain logo component loaded via host /api/media proxy as a cached data: URI, with optional DEX chain mini-badge and monogram fallback. | | `arbitron.ui.assetBadge` | `({ into?, coin?, symbol?, chainId?, logoUrl?, subtitle?, tag?, size?, href?, onClick?, class? }) => { el, update(opts), destroy }` | Compact terminal asset badge with icon (via ui.logo), ticker, optional subtitle/tag, and optional validated hyperlink or click handler. | | `arbitron.ui.venueBadge` | `({ into?, venue?, exchange?, label?, short?, logoUrl?, size?, href?, onClick?, class? }) => { el, update(opts), destroy }` | Compact terminal venue/exchange badge with provider icon, short or full name, and optional validated hyperlink or click handler. | | `arbitron.ui.row` | `({ into?, class?, grow? }) => { el, destroy }` | Horizontal flex container; mounts into `into ?? arbitron.root`. Pass `parent.el` (or `parent`) as `into` for child components. | | `arbitron.ui.column` | `({ into?, class?, grow? }) => { el, destroy }` | Vertical flex container; mounts into `into ?? arbitron.root`. | | `arbitron.ui.tabs` | `({ into?, bind?, state?, value?, label?, options, onChange? }) => { el, value, set(v), destroy }` | Segmented tab switcher bound to `arbitron.state` key (`bind` or `state` alias). | | `arbitron.ui.select` | `({ into?, bind?, state?, value?, label?, options, onChange? }) => { el, value, destroy }` | Themed dropdown selector bound to `arbitron.state` key (`bind` or `state` alias). | | `arbitron.ui.toggle` | `({ into?, bind?, state?, value?, label, onChange? }) => { el, value, destroy }` | Boolean toggle button bound to `arbitron.state` key (`bind` or `state` alias). | | `arbitron.ui.button` | `({ into?, label, primary?, onClick }) => { el, destroy }` | Themed action button. | | `arbitron.ui.stat` | `({ into?, label?, data?, value?: (d)=>any\|string, change?: (d)=>number\|string, changeLabel?, format? }) => { el, update(data), destroy }` | KPI metric card. Bind a reactive `source` via `data` or call `.update(rawDataObj)`. | | `arbitron.ui.table` | `({ into?, columns, data?, rows?, rowKey?, sort?, limit?, empty?, onRowClick?, selected?, reorderable?, resizable?, columnPicker?, searchable?, persistKey?, bindParamsTable? }) => { el, refresh, update(data), getState(), reset(), destroy }` | Full terminal table view with sort arrows (nulls last), drag-and-drop column reorder, column resize handles, column picker popover, inline search, state persistence (`persistKey` / `bindParamsTable` reading `arbitron.params.table`), keyed zero-jitter DOM updates (`rowKey`), custom `col.render(val, row)` returning a DOM Node (e.g. `ui.assetBadge` / `ui.venueBadge`), and validated `col.href` hyperlinks. | | `arbitron.ui.feed` | `({ into?, data?, title?, tag?, time?, limit?, onClick? }) => { el, update(items), destroy }` | Scrollable timeline / news feed with optional field accessors. | | `arbitron.ui.sparkline` | `({ into?, data?, value?, label?, showValue?, format?, height?, color?, bars?, fill?, min?, max? }) => { el, update(points), destroy }` | Lightweight inline SVG sparkline or mini bar chart reactive to dark/light themes. | | `arbitron.ui.chart` | `({ into?, title?, type?: 'area'\|'line'\|'bar', data?, series?, value?, time?, label?, format?, height?, color?, grid?, min?, max?, empty? }) => { el, update(data), destroy }` | Interactive multi-series inline SVG chart with hover crosshair, legend, axes, and automatic theme re-rendering. | | `arbitron.ui.color` | `(tokenOrCssColor: string, fallback?: string) => string` | Resolve a theme token name (e.g. 'accent', 'positive', 'negative') to its current CSS color value. | | `arbitron.ui.alpha` | `(cssColor: string, opacity: number) => string` | Apply alpha transparency (0..1) to a hex or rgb() color string. | ### Shared Modules Upload shared JS utilities with POST /v1/code → { hash }, then import in any widget via `import { fn } from "arbitron:code/"` (or `"pole:code/"`). All referenced modules must exist before applying ops. ## Market Data Routes (`/v1/data/*` & `/api/*` — 24 routes) ### `/v1/data/klines` (alias `/api/klines`) OHLCV candlestick bars for TradingView/CEX or DEX tokens. - Query params: `kind=tv&symbol=BINANCE:BTCUSDT&tf=60&count=300[&to=&fresh=1] | kind=dex&chainId=1&tokenAddress=0x...&tf=15&count=200` - Response schema: `{ bars: [{ time (unix ms), open, high, low, close, volume }], noData: boolean, source: string }` - Notes: Timestamps are Unix milliseconds sorted ascending. DEX timeframes also accept 1s/5s/15s/30s/1/5/15/60/240/1D/1W. ### `/v1/data/quotes/batch` (alias `/api/quotes/batch`) Batch real-time quotes for TradingView/CEX/TradFi symbols. - Query params: `symbols=BINANCE:BTCUSDT,BINANCE:ETHUSDT` - Response schema: `{ quotes: { [symbol]: { price: number | null, changePct: number | null, volume: number | null } }, updatedAt: number }` - Notes: Spot `volume` is reported in base asset units; perp/futures `volume` unit varies by exchange. Cold, illiquid, or delisted symbols may return `price: null`. ### `/v1/data/search` (alias `/api/search`) Search instruments across TV, CEX, DEX and TradFi. - Query params: `q=BTC&scope=all|tv|cex|dex|tradfi&limit=40[&exchange=BINANCE]` - Response schema: `{ query, scope, items: [{ id, kind ('tv'|'dex'), symbol, displaySymbol, description, exchange, type ('spot'|'swap'|'futures'|'stock'|'index'|'fund'|'forex'|'cfd'|'dex'), marketCategory, chainId?, tokenAddress?, pairAddress?, price?, changePct?, priceUsd?, change24h?, liquidityUsd?, volume24h?, marketCapUsd?, logoUrl?, source }], sources: { tv, dex } }` - Notes: Leading `$` ticker prefix is normalized in queries and DEX token symbols (e.g. `WIF` and `$WIF` match seamlessly). Render `logoUrl` via `arbitron.ui.logo({ url: item.logoUrl, symbol: item.displaySymbol, chainId: item.chainId })` or `` (never direct ``, which is blocked by sandbox CSP). ### `/v1/data/search/bootstrap` (alias `/api/search/bootstrap`) Pre-indexed instrument bootstrap catalog (top CEX, TradFi, and trending DEX). - Query params: `(none)` - Response schema: `{ items: SearchItem[], updatedAt: number }` ### `/v1/data/search/exchanges` (alias `/api/search/exchanges`) Supported exchanges directory with categories and popularity rank. - Query params: `[q=&limit=1..1000] (omitting both returns full directory)` - Response schema: `{ items: [{ id, name, logoUrl?, categories: ('cex'|'tradfi')[], directWs: boolean, popularRank? }], total: number, updatedAt: number }` - Notes: Full list can be large; pass `q` and/or `limit` when querying from agents. ### `/v1/data/dex/intel` (alias `/api/dex/intel`) DEX token intelligence (risk score, holders, buy/sell flow, social links). - Query params: `chainId=1|56|8453|501&tokenAddress=
` - Response schema: `{ chainId, tokenAddress, price, change24h, marketCap, liquidity, volume24h, holders, top10Pct, devHoldingPct, sniperPct, suspiciousPct, riskLevel (1..5), buyVolumeUsd, sellVolumeUsd, buysCount, sellsCount, buyTraders, sellTraders, netInflowUsd, website?, explorerUrl?, twitter?, telegram?, updatedAt }` - Notes: `riskLevel` is 1..5 where 1 = lowest risk and 5 = highest risk. Holder ratios (`top10Pct`, `devHoldingPct`, `sniperPct`, `suspiciousPct`) are percentages 0..100. ### `/v1/data/predictions/markets` (alias `/api/predictions/markets`) Prediction markets search across Polymarket & Kalshi. - Query params: `[q=&]source=all|polymarket|kalshi&limit=25[&includeClosed=1|activeOnly=false]` - Response schema: `{ query, source, items: [{ id, source ('polymarket'|'kalshi'), slug, title, imageUrl?, category?, outcomes: [{ label, price (0..1), tokenId? }], volume24h, totalVolume, liquidity, endDate?, url? }], sources: { polymarket, kalshi }, updatedAt }` - Notes: Active/open markets are returned by default (closed/resolved/settled markets excluded unless `includeClosed=1` or `activeOnly=false`). When `q` is passed, strict word-boundary token matching is applied against title, question, category, and outcome labels. ### `/v1/data/predictions/history` (alias `/api/predictions/history`) Historical probability series for a prediction outcome token. - Query params: `source=polymarket|kalshi&tokenId=&interval=1d|1w|1m|max` - Response schema: `{ points: [{ time (unix ms), price (0..1) }], source, tokenId, interval }` ### `/v1/data/news` (alias `/api/news`) Real-time market news headlines. - Query params: `market=all|crypto|stocks|forex[&symbol=BINANCE:BTCUSDT]&limit=30` - Response schema: `{ items: [{ id, title, publishedMs, source, urgency, link?, relatedSymbols: [{ symbol, logoUrl? }] }], updatedAt }` ### `/v1/data/calendar` (alias `/api/calendar`) Macro economic calendar events. - Query params: `days=1..14 (default 3)` - Response schema: `{ items: [{ id, title, country, countryLogoUrl?, dateMs, importance (-1..1), actual, forecast, previous, unit? }], updatedAt }` ### `/v1/data/explorer/chains` (alias `/api/explorer/chains`) List supported block explorer chains. - Query params: `[q=&limit=1..1000] (omitting both returns full chain list)` - Response schema: `{ items: [{ id, name, family, chainId?, nativeSymbol, tier, capabilities: string[] }], total: number, updatedAt: number }` - Notes: Pass `q` and/or `limit` to filter large chain directories. ### `/v1/data/explorer/lookup` (alias `/api/explorer/lookup`) Look up an on-chain address or transaction hash. - Query params: `chain=ethereum&q=` - Response schema: `{ kind: 'address'|'tx', chain, query, tokens?: [{ address, symbol, name, decimals, standard?, logoUrl?, balance, priceUsd, valueUsd }], txs?: [{ hash, blockNumber, timestampMs, status, from, to, value, nativeSymbol, fee, direction, methodName? }], tx?: ExplorerTxItem, partialError?, updatedAt }` ### `/v1/data/scanner/inefficiencies` (alias `/api/scanner/inefficiencies`) Aggregated cross-venue spreads, funding arbitrage APR, OI/mark-oracle anomalies, and Polymarket<->Kalshi forks. - Query params: `[force=1]` - Response schema: `{ updatedAt, sources, spreads: [...], funding: [...], anomalies: [...], predictionForks: [...] }` ### `/v1/data/orderbook/depth` (alias `/api/orderbook/depth`) L2 orderbook depth, imbalance, VWAP impact, and wall detection for Perp-DEX venues (Hyperliquid, Aster, dYdX, Lighter, Deribit). - Query params: `symbol=HYPERLIQUID:BTCUSDC.P[&force=1]` - Response schema: `{ symbol, venue, coin, midPrice, bestBid, bestAsk, spreadBps, imbalance, bids, asks, walls, impact, updatedAt }` ### `/v1/data/orderbook/aggregated` (alias `/api/orderbook/aggregated`) Cross-venue consolidated L2 orderbook across up to 5 venues with venue breakdown, walls, crossed flag, and VWAP fill simulation. - Query params: `coin=BTC[&venues=hyperliquid,binance,bybit,okx,aster&sizeUsd=10000&force=1]` - Response schema: `{ coin, venues, activeVenues, venueStatuses, timestamp, bestBid, bestAsk, crossed, midPrice, spreadBps, bids, asks, totalBidUsd, totalAskUsd, imbalancePct, walls, vwapBySize }` ### `/v1/data/orderbook/spread-sim` (alias `/api/orderbook/spread-sim`) Cross-venue VWAP execution & net edge simulator for a target notional size. - Query params: `a=HYPERLIQUID:BTCUSDC.P&b=ASTER:BTCUSDT.P&sizeUsd=10000[&feeABps=4&feeBBps=4]` - Response schema: `{ symbolA, symbolB, sizeUsd, rawSpreadPct, netSpreadPct, legA, legB, updatedAt }` ### `/v1/data/markets/descriptors` (alias `/api/markets/descriptors`) Unified venue descriptors, capabilities, and market/exchange mappings. - Query params: `[force=1]` - Response schema: `{ venues: [...], updatedAt }` ### `/v1/data/markets/instrument` (alias `/api/markets/instrument`) Unified instrument snapshot (mark/index/spot price, funding, OI, 24h volume, transfer networks). - Query params: `symbol=BINANCE:BTCUSDT.P[&fresh=1]` - Response schema: `{ symbol, raw_symbol, exchange, market_type, base, quote, ticker: { last, mark_price, index_price, bid, ask, quote_volume_24h, open_interest, change_24h_pct }, funding: { rate, interval_hours, apr_pct, next_funding_ts_ms }, limits, links, networks, ws }` ### `/v1/data/markets/trades` (alias `/api/markets/trades`) Recent unified market trade prints for a CEX or perp-DEX symbol. - Query params: `symbol=BINANCE:BTCUSDT.P[&limit=50]` - Response schema: `{ symbol, exchange, count, trades: [{ ts_ms, price, qty, side }] }` ### `/v1/data/markets/flow` (alias `/api/markets/flow`) Orderflow & CVD/whale-tape summary across recent trades for a symbol. - Query params: `symbol=BINANCE:BTCUSDT.P[&limit=200]` - Response schema: `{ symbol, buyVolumeUsd, sellVolumeUsd, cvdUsd, buyRatioPct, tradeCount, whaleCount, whales, cvdBuckets, updatedAt }` ### `/v1/data/markets/funding-history` (alias `/api/markets/funding-history`) Historical funding rate series for a perpetual instrument. - Query params: `symbol=BINANCE:BTCUSDT.P[&limit=100]` - Response schema: `{ exchange, symbol, raw_symbol, interval_hours, count, items: [{ ts_ms, funding_rate, funding_rate_pct, interval_hours, mark_price? }] }` ### `/v1/data/markets/funding-spread-history` (alias `/api/markets/funding-spread-history`) Historical funding rate spread series between two perpetual venues. - Query params: `symbolA=HYPERLIQUID:BTCUSDC.P&symbolB=BINANCE:BTCUSDT.P[&limit=100]` - Response schema: `{ symbolA, symbolB, intervalA, intervalB, count, points: [{ tsMs, rateAPct, rateBPct, diffPct, aprDiffPct }], updatedAt }` ### `/v1/data/markets/transfer-check` (alias `/api/markets/transfer-check`) Deposit/withdraw network availability and fee check between two exchanges for a pair of symbols. - Query params: `symbolA=BINANCE:ETHUSDT&symbolB=BYBIT:ETHUSDT` - Response schema: `{ symbolA, symbolB, commonOpenCount, aToB, bToA, cheapestAToB, cheapestBToA, venueANetworksCount, venueBNetworksCount, updatedAt }` ### `/v1/data/markets/asset-profile` (alias `/api/markets/asset-profile`) Cross-venue asset profile aggregating venues, contracts, spot/perp coverage, and metadata. - Query params: `base=BTC[&canonical_id=...]` - Response schema: `{ base_symbol, canonical_id, contracts, spot_venues, futures_venues, active_spreads, icon_url }` ## Working Widget Examples (`arbitron.ui`) ### Example 1: Live Spread & Quotes Watchlist Subscribes to batch quotes, shows BTC/ETH ratio KPI + interactive filterable watchlist table. Default params: `{"symbols":["BINANCE:BTCUSDT","BINANCE:ETHUSDT","BINANCE:SOLUSDT","BYBIT:BTCUSDT"],"everyMs":5000}` ```js const { ui, data, state, format } = window.arbitron; const symbols = window.arbitron.params.symbols ?? ["BINANCE:BTCUSDT", "BINANCE:ETHUSDT", "BINANCE:SOLUSDT"]; state.define("filter", "all"); const topRow = ui.row(); const ratioStat = ui.stat({ into: topRow.el, label: "BTC / ETH Ratio", value: (d) => d?.ratio, change: (d) => d?.changePct, format: "price", }); ui.tabs({ into: topRow.el, bind: "filter", options: [ { value: "all", label: "All" }, { value: "up", label: "Gainers" }, { value: "down", label: "Losers" }, ], }); const table = ui.table({ columns: [ { key: "symbol", label: "Symbol" }, { key: "price", label: "Last", align: "right", format: "price" }, { key: "changePct", label: "24h %", align: "right", format: "percent", tone: "sign" }, ], }); let lastRows = []; function renderRows() { const f = state.get("filter") || "all"; const filtered = lastRows.filter((row) => { if (f === "up") return (row.changePct ?? 0) >= 0; if (f === "down") return (row.changePct ?? 0) < 0; return true; }); table.update(filtered); } state.onChange(renderRows); const stop = data.subscribe( "quotes/batch", { symbols: symbols.join(",") }, (payload) => { const qMap = payload?.quotes || {}; lastRows = symbols.map((sym) => ({ symbol: format.ticker(sym), price: qMap[sym]?.price ?? null, changePct: qMap[sym]?.changePct ?? null, })); const btc = qMap["BINANCE:BTCUSDT"]; const eth = qMap["BINANCE:ETHUSDT"]; if (btc?.price && eth?.price) { ratioStat.update({ ratio: btc.price / eth.price, changePct: btc.changePct ?? null }); } renderRows(); }, { every: window.arbitron.params.everyMs ?? 5000 }, ); export default () => stop(); ``` ### Example 2: Market News & Predictions Pulse Combines live TradingView news feed with top Polymarket/Kalshi probability KPI and reactive state selection. Default params: `{"market":"crypto","query":"bitcoin","limit":15}` ```js const { ui, data, state } = window.arbitron; state.define("market", window.arbitron.params.market ?? "crypto"); const controls = ui.row(); ui.select({ into: controls.el, bind: "market", options: [ { value: "all", label: "All Markets" }, { value: "crypto", label: "Crypto" }, { value: "stocks", label: "Stocks" }, { value: "forex", label: "Forex" }, ], }); ui.button({ into: controls.el, label: "Refresh", onClick: () => void refresh() }); const oddsStat = ui.stat({ label: "Top Prediction (Yes)", value: (d) => (d?.yesPrice != null ? Math.round(d.yesPrice * 100) : null), format: (v) => (v == null ? "—" : v + "%"), }); const newsFeed = ui.feed({ title: (n) => n.title, tag: (n) => n.source, time: (n) => n.publishedMs, }); async function refresh() { const [newsRes, predRes] = await Promise.all([ data.get("news", { market: state.get("market") || "crypto", limit: window.arbitron.params.limit ?? 15 }), data.get("predictions/markets", { q: window.arbitron.params.query ?? "bitcoin", source: "all", limit: 5 }), ]); const top = predRes?.items?.[0]; if (top) { const yes = (top.outcomes || [])[0]; oddsStat.update({ title: top.title, yesPrice: yes?.price ?? null }); } newsFeed.update(Array.isArray(newsRes?.items) ? newsRes.items : []); } const off = state.onChange(() => void refresh()); await refresh(); export default () => off(); ``` ### Example 3: Linked Token Dossier (Platform Reuse Showcase) Demonstrates Release 2 platform primitives: native QuickSearchModal via ui.instrumentPicker, LinkGroup sync via onInstrument, server-proxied logos via ui.logo, host openInstrument/openExplorer/copy/openLink, and unified format.price/shortenAddress/age. Default params: `{}` ```js const { ui, data, format, h, css } = window.arbitron; css(`.dossier-head { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-bottom:8px; } .dossier-addr { font-family:var(--font-mono,monospace); font-size:11px; color:var(--muted); }`); const head = h("div", { class: "dossier-head" }); window.arbitron.root.appendChild(head); const logoSlot = h("span"); head.appendChild(logoSlot); let current = window.arbitron.instrument; const picker = ui.instrumentPicker({ into: head, scope: "all", value: current, placeholder: "Pick instrument…", onChange: (inst) => { current = inst; void loadDossier(inst); }, }); const actions = ui.row({ into: head }); ui.button({ into: actions.el, label: "Open Chart", primary: true, onClick: () => { if (current) void window.arbitron.openInstrument(current, { target: "linked" }); }, }); ui.button({ into: actions.el, label: "Copy Symbol", onClick: () => { const val = current?.tokenAddress || current?.symbol; if (val) void window.arbitron.copy(val); }, }); const metaRow = ui.row(); const priceStat = ui.stat({ into: metaRow.el, label: "Price", value: (d) => d?.price, format: "price" }); const capStat = ui.stat({ into: metaRow.el, label: "Liquidity / Vol", value: (d) => d?.liq, format: "compact" }); const infoEl = h("div", { class: "dossier-addr" }); window.arbitron.root.appendChild(infoEl); async function loadDossier(inst) { logoSlot.replaceChildren(); if (!inst) { infoEl.textContent = "Link this tile or click Pick instrument to inspect a token."; return; } ui.logo({ into: logoSlot, url: inst.logoUrl, symbol: inst.displaySymbol || inst.symbol, chainId: inst.chainId, exchange: inst.exchange, size: 24, }); if (inst.kind === "dex" && inst.chainId && inst.tokenAddress) { const intel = await data.get("dex/intel", { chainId: inst.chainId, tokenAddress: inst.tokenAddress }); priceStat.update({ price: intel?.price ?? null }); capStat.update({ liq: intel?.liquidity ?? null }); infoEl.textContent = format.shortenAddress(inst.tokenAddress) + " · risk " + (intel?.riskLevel ?? "?") + "/5 · updated " + format.age(intel?.updatedAt ?? Date.now()); } else { const q = await data.get("quotes/batch", { symbols: inst.symbol }); const row = q?.quotes?.[inst.symbol]; priceStat.update({ price: row?.price ?? null }); capStat.update({ liq: row?.volume ?? null }); infoEl.textContent = format.ticker(inst.symbol) + " · " + (inst.exchange || "CEX"); } } const offInst = window.arbitron.onInstrument((inst) => { current = inst; picker.update?.(inst); void loadDossier(inst); }); await loadDossier(current); export default () => offInst(); ```