# Heisenberg AI — Full Documentation > Heisenberg AI is a prediction market intelligence platform. It exposes production agents and a direct REST API over Polymarket and Kalshi data, including H-Score sharp-trader rankings, Wallet 360 analytics, market pulse, smart-money positions, and copy-trade signals. > > MCP endpoint: https://narrative.agent.heisenberg.so/sse > REST: https://prediction.heisenberg.so/docs/api-reference > Index (small): https://prediction.heisenberg.so/llms.txt --- # Heisenberg SDK _Source: https://prediction.heisenberg.so/docs/sdk_ SDK # Heisenberg SDK One typed client for the entire intelligence API — markets, trades, wallet 360, smart money, H-Score leaderboards, CLV, and real-time trades — for **TypeScript** and **Python**, generated from a single spec so both languages stay identical. **Now available.** Install: `pip install heisenberg_ai` `npm install heisenberg-ai` Examples use your [API token](/docs/getting-started/authentication). Source on [GitHub](https://github.com/SeshatLabs/heisenberg-sdk). ## Quickstart TypeScript ``` import { Heisenberg } from 'heisenberg-ai'; const hb = new Heisenberg({ token: process.env.HEISENBERG_TOKEN }); // Free tier — no subscription needed. const markets = await hb.polymarket.markets({ min_volume: 1000, closed: false, limit: 5 }); const profile = await hb.wallets.profile('0xabc…', { window_days: 15 }); // A Query is awaitable (first page) or async-iterable (auto-paginates). for await (const trade of hb.polymarket.trades({ condition_id: '0x…' })) { // … } ``` Python ``` from heisenberg import Heisenberg hb = Heisenberg(token="…") # or set HEISENBERG_TOKEN markets = hb.polymarket.markets({"min_volume": 1000, "closed": False, "limit": 5}).page() profile = hb.wallets.profile("0xabc…", {"window_days": 15}).page() for trade in hb.polymarket.trades({"condition_id": "0x…"}): # auto-paginates ... ``` ## Two ways in ### Venues `hb.polymarket`, `hb.kalshi`, `hb.hyperliquid` — each exposes the capabilities that venue supports (`.markets`, `.trades`, …). Same shape everywhere. ### Intelligence `hb.wallets`, `hb.smartMoney`, `hb.leaderboards`, `hb.sports`, `hb.social` — curated, typed methods over the highest-value signals. ### Real-time `hb.stream.trades({…})` streams live Polymarket trades with automatic reconnect and resubscribe. ### Read-only Typed reads over HTTPS with your bearer token — no custody or signing to manage. The token is only ever sent in the Authorization header. ## What the client handles for you - Native param types → the API's string wire format (booleans, dates). - Envelope unwrapping and **auto-pagination**. - Encoded JSON response columns decoded transparently. - Retries with backoff on 429/5xx. - Typed errors — including `PlanError` for gated endpoints, which preserves the API message and tells you which plan unlocks it. [TypeScript guide](/docs/sdk/typescript)[Python guide](/docs/sdk/python) ## Method → endpoint reference Every SDK method calls one API endpoint (agent). Names below are TypeScript; Python uses the snake\_case equivalent (e.g. `hb.smartMoney` → `hb.smart_money`, `closingLine` → `closing_line`). Click an endpoint to open its full API reference. ### Polymarket `hb.polymarket` markets(params) [Polymarket Markets](/docs/api-reference/polymarket-markets) #574 trades(params) [Polymarket Trades](/docs/api-reference/polymarket-trades) #556 candlesticks(params) [Polymarket Candlesticks](/docs/api-reference/polymarket-candlesticks) #568 orderbook(params) [Polymarket Orderbook](/docs/api-reference/polymarket-orderbook) #572 priceJumps(params) [Polymarket Price Jumps](/docs/api-reference/polymarket-price-jumps) #596 ### Kalshi `hb.kalshi` markets(params) [Kalshi Markets](/docs/api-reference/kalshi-markets) #565 trades(params) [Kalshi Trades](/docs/api-reference/kalshi-trades) #573 ### Hyperliquid `hb.hyperliquid` walletTrades(params) [Hyperliquid Wallet Trades](/docs/api-reference/hyperliquid-wallet-trades) #612 marketTrades(params) [Hyperliquid Market Trades](/docs/api-reference/hyperliquid-market-trades) #613 perpetualMarkets(params) [Hyperliquid Perpetual Markets](/docs/api-reference/hyperliquid-perpetual-markets) #616 spotMarkets(params) [Hyperliquid Spot Markets](/docs/api-reference/hyperliquid-spot-markets) #617 outcomeMarkets(params) [Hyperliquid Outcome Markets](/docs/api-reference/hyperliquid-outcome-markets) #615 ### Wallets `hb.wallets` profile(wallet, params) [Wallet 360](/docs/api-reference/wallet-360) #581 pnl(wallet, params) [Polymarket PnL](/docs/api-reference/polymarket-pnl) #569 statsAllTime(wallet) [Wallet Stats All Time](/docs/api-reference/wallet-stats-all-time) #586 ### Smart money `hb.smartMoney` positions(params) [Smart Money Positions](/docs/api-reference/smart-money-positions)gated #591 pulse(conditionId, params) [Market Pulse: Summary](/docs/api-reference/market-pulse-summary)gated #593 pulsePositions(conditionId, params) [Market Pulse: Positions](/docs/api-reference/market-pulse-positions)gated #594 ### Leaderboards `hb.leaderboards` polymarketPnl(params) [Polymarket PnL Leaderboard](/docs/api-reference/polymarket-pnl-leaderboard) #579 heisenberg(params) [Heisenberg Leaderboard](/docs/api-reference/heisenberg-leaderboard) #584 sport(params) [Sports Bettor Leaderboard](/docs/api-reference/sports-bettor-leaderboard)gated #595 ### Markets `hb.markets` insights(conditionId, params) [Polymarket Market 360](/docs/api-reference/polymarket-market-360) #575 ### Sports `hb.sports` closingLine(conditionId) [Closing Line](/docs/api-reference/closing-line)gated #602 pnl(wallet, params) [Sport PnL](/docs/api-reference/sport-pnl)gated #601 bettorProfile(wallet, params) [Sport Bettor Profile](/docs/api-reference/sport-bettor-profile)gated #599 hScore(wallet) [Sport H-Score Forecast](/docs/api-reference/sport-h-score-forecast)gated #605 hScoreHistory(wallet, params) [Sport H-Score History](/docs/api-reference/sport-h-score-history)gated #606 marketInsights(params) [Sport Market Insights](/docs/api-reference/sport-market-insights)gated #600 ### Audience `hb.audience` polylink(wallets) [Polylink](/docs/api-reference/polylink)gated #607 ### Social `hb.social` pulse(params) [Social Pulse](/docs/api-reference/social-pulse) #585 ## Related - [Authentication](/docs/getting-started/authentication) — get a token and understand plans. - [API Reference](/docs/api-reference) — every endpoint, params, and response fields. - [WebSockets](/docs/websockets) — the raw stream behind `hb.stream`. - [Work with AI (MCP)](/docs/getting-started/mcp) — no-code access to the same data. - [Pricing & Plans](/docs/getting-started/pricing) — what unlocks the gated endpoints. --- # TypeScript SDK _Source: https://prediction.heisenberg.so/docs/sdk/typescript_ SDK · TypeScript # TypeScript SDK `heisenberg-ai` — a typed, read-only client. Node 18+. Zero required runtime dependencies (streaming uses an optional `ws` package). ## Install npm ``` npm install heisenberg-ai npm install ws # optional, for streaming ``` ## Authenticate Pass a [token](/docs/getting-started/authentication) or set `HEISENBERG_TOKEN`. The token is only sent as a Bearer header and never logged. TypeScript ``` import { Heisenberg } from 'heisenberg-ai'; const hb = new Heisenberg({ token: process.env.HEISENBERG_TOKEN }); ``` ## Venues Every venue exposes the capabilities it supports. Ask with `supports()`; call an unsupported one and you get a clear error. TypeScript ``` const markets = await hb.polymarket.markets({ min_volume: 1000, closed: false }); const book = await hb.polymarket.orderbook({ token_id: '…' }); const kalshi = await hb.kalshi.markets({ status: 'open' }); const hl = await hb.hyperliquid.walletTrades({ address: '0x…' }); hb.polymarket.supports('orderbook'); // true hb.kalshi.supports('orderbook'); // false ``` ## Intelligence TypeScript ``` const profile = await hb.wallets.profile('0xabc…', { window_days: 15 }); // Wallet 360 const pnl = await hb.wallets.pnl('0xabc…', { granularity: '1w' }); const elite = await hb.leaderboards.heisenberg({ sort_by: 'h_score', limit: 10 }); const pulse = await hb.smartMoney.pulse('0xcondition…'); // gated (Sport) const clv = await hb.sports.closingLine('0xcondition…'); // gated (Sport) ``` Anything not wrapped is reachable via `hb.query(agentId, params)`. Discover everything with `hb.catalog()`. Every method maps to an endpoint — see the [method → endpoint reference](/docs/sdk#method-map) for links into the [API reference](/docs/api-reference) (params and response fields for each agent). ## Pagination A `Query` is awaitable (first page) _or_ async-iterable (every row across all pages). TypeScript ``` // one page const page = await hb.polymarket.trades({ condition_id: '0x…' }); console.log(page.results, page.pagination.hasMore); // every row, auto-paginated for await (const trade of hb.polymarket.trades({ condition_id: '0x…' })) { // … } // collect all (use with care on large sets) const all = await hb.polymarket.trades({ condition_id: '0x…' }).all(); ``` ## Streaming TypeScript ``` for await (const trade of hb.stream.trades({ condition_id: '0x…' })) { console.log(trade.price, trade.side); } // reconnects with backoff and re-subscribes automatically on disconnect ``` ## Errors & gated endpoints Sport/audience endpoints need a subscription and throw a typed `PlanError` that preserves the API's message and names the plan. Other failures map to `AuthError`, `RateLimitError`, `ValidationError`, `ApiError` — all carry a `requestId`. TypeScript ``` import { PlanError } from 'heisenberg-ai'; try { await hb.sports.closingLine('0x…'); } catch (e) { if (e instanceof PlanError) { console.log(e.message, '→ unlock:', e.requiredPlan); } else throw e; } // check ahead of time hb.requires(602); // "sport" ``` ## Options TypeScript ``` new Heisenberg({ token, // or HEISENBERG_TOKEN timeoutMs, // default 30000 maxRetries, // default 2 (429/5xx/network) baseUrl, // override the API base fetch, // inject a fetch impl (tests / Node < 18) }); ``` [→ Same, in Python](/docs/sdk/python) --- # Python SDK _Source: https://prediction.heisenberg.so/docs/sdk/python_ SDK · Python # Python SDK `heisenberg` — a typed, read-only client. Python 3.9+. The REST client uses only the standard library; streaming uses an optional extra. ## Install PyPI ``` pip install heisenberg_ai pip install "heisenberg_ai[stream]" # optional, for streaming ``` ## Authenticate Pass a [token](/docs/getting-started/authentication) or set `HEISENBERG_TOKEN`. The token is only sent as a Bearer header and never logged. Python ``` from heisenberg import Heisenberg hb = Heisenberg(token="…") # or HEISENBERG_TOKEN ``` ## Venues Python ``` markets = hb.polymarket.markets({"min_volume": 1000, "closed": False}).page() book = hb.polymarket.orderbook({"token_id": "…"}).page() kalshi = hb.kalshi.markets({"status": "open"}).page() hl = hb.hyperliquid.wallet_trades({"address": "0x…"}).page() hb.polymarket.supports("orderbook") # True hb.kalshi.supports("orderbook") # False ``` ## Intelligence Python ``` profile = hb.wallets.profile("0xabc…", {"window_days": 15}).page() # Wallet 360 pnl = hb.wallets.pnl("0xabc…", {"granularity": "1w"}).page() elite = hb.leaderboards.heisenberg({"sort_by": "h_score", "limit": 10}).page() pulse = hb.smart_money.pulse("0xcondition…").page() # gated (Sport) clv = hb.sports.closing_line("0xcondition…").page() # gated (Sport) ``` Anything not wrapped is reachable via `hb.query(agent_id, params)`. Discover everything with `hb.catalog()`. Every method maps to an endpoint — see the [method → endpoint reference](/docs/sdk#method-map) for links into the [API reference](/docs/api-reference) (params and response fields for each agent). ## Pagination Call `.page()` for one page, or iterate a `Query` to stream every row across all pages. Python ``` # one page page = hb.polymarket.trades({"condition_id": "0x…"}).page() print(page.results, page.pagination["has_more"]) # every row, auto-paginated for trade in hb.polymarket.trades({"condition_id": "0x…"}): ... # collect all (use with care on large sets) rows = hb.polymarket.trades({"condition_id": "0x…"}).all() ``` ## Streaming Python (requires heisenberg\_ai\[stream\]) ``` for trade in hb.stream.trades({"condition_id": "0x…"}): print(trade.get("price"), trade.get("side")) # reconnects with backoff and re-subscribes automatically on disconnect ``` ## Errors & gated endpoints Sport/audience endpoints need a subscription and raise a typed `PlanError` that preserves the API's message and names the plan. Other failures map to `AuthError`, `RateLimitError`, `ValidationError`, `ApiError` — all carry a `request_id`. Python ``` from heisenberg import PlanError try: hb.sports.closing_line("0x…").page() except PlanError as e: print(str(e), "→ unlock:", e.required_plan) # check ahead of time hb.requires(602) # "sport" ``` ## Options Python ``` Heisenberg( token=None, # or HEISENBERG_TOKEN timeout=30.0, # seconds max_retries=2, # 429/5xx/network base_url=None, # override the API base transport=None, # inject a transport (tests) ) ``` [→ Same, in TypeScript](/docs/sdk/typescript) --- # SDK Recipes _Source: https://prediction.heisenberg.so/docs/sdk/recipes_ SDK · Guides # Recipes Common workflows, end to end. Each runs with a token in `HEISENBERG_TOKEN`. TypeScript and Python are shown side by side; the shapes returned are documented in [Response fields](/docs/sdk/responses). ## Scout a wallet before you copy it Pull Wallet 360 for skill/risk metrics, then realized PnL history. Check `sharpe_ratio`, `win_rate`, and the risk flags before trusting a track record. TypeScript ``` const [profile] = (await hb.wallets.profile(wallet, { window_days: 15 })).results; if (!profile) throw new Error('no Wallet 360 data for this wallet'); console.log({ roi: profile.roi, winRate: profile.win_rate, sharpe: profile.sharpe_ratio, // number | null maxDrawdown: profile.max_drawdown, sybilRisk: profile.sybil_risk_flag, // avoid if true riskLevel: profile.risk_level, }); // realized PnL over time const pnl = await hb.wallets.pnl(wallet, { granularity: '1w' }); ``` Python ``` rows = hb.wallets.profile(wallet, {"window_days": 15}).page().results if not rows: raise RuntimeError("no Wallet 360 data for this wallet") p = rows[0] print(p["roi"], p["win_rate"], p["sharpe_ratio"], p["max_drawdown"], p["sybil_risk_flag"], p["risk_level"]) pnl = hb.wallets.pnl(wallet, {"granularity": "1w"}).page() ``` ## Read the smart-money picture on a market Market 360 gives structure and risk; sport Market Pulse (gated) gives sharp-money consensus. Combine them to gauge conviction and liquidity risk before you enter. TypeScript ``` const [m360] = (await hb.markets.insights(conditionId)).results; console.log(m360?.liquidity_tier, m360?.volume_trend, m360?.whale_control_flag); // sharp-money consensus (requires the Sport plan) const pulse = await hb.smartMoney.pulse(conditionId); for (const side of pulse.results) { console.log(side.outcome, side.wallet_count, side.avg_entry_price, side.current_price); } ``` Python ``` m = hb.markets.insights(condition_id).page().results if m: print(m[0]["liquidity_tier"], m[0]["volume_trend"], m[0]["whale_control_flag"]) pulse = hb.smart_money.pulse(condition_id).page() # gated: Sport plan for side in pulse.results: print(side["outcome"], side.get("wallet_count"), side.get("avg_entry_price")) ``` ## Find elite wallets by H-Score Rank wallets by the Heisenberg H-Score, then scout the top few (recipe 1). Remember leaderboard numbers come back as decimal **strings**. TypeScript ``` const board = await hb.leaderboards.heisenberg({ sort_by: 'h_score', limit: 20 }); const top = board.results .filter((r) => Number(r.roi_pct_15d) > 0) // strings -> Number() to compare .slice(0, 5); for (const w of top) console.log(w.leaderboard_rank, w.wallet, w.h_score, w.tier); ``` Python ``` board = hb.leaderboards.heisenberg({"sort_by": "h_score", "limit": 20}).page() top = [r for r in board.results if float(r["roi_pct_15d"]) > 0][:5] for w in top: print(w["leaderboard_rank"], w["wallet"], w["h_score"], w["tier"]) ``` ## Watch live trades and react Stream trades for a market (or wallet) and act on them. The stream reconnects and resubscribes automatically. See [Streaming](/docs/sdk/streaming) for the full filter list. TypeScript ``` for await (const t of hb.stream.trades({ condition_id: conditionId })) { if (t.size >= 1000) console.log('large fill', t.side, t.price, t.proxy_wallet); } ``` Python (needs heisenberg\_ai\[stream\]) ``` for t in hb.stream.trades({"condition_id": condition_id}): if (t.get("size") or 0) >= 1000: print("large fill", t.get("side"), t.get("price"), t.get("proxy_wallet")) ``` ## Handle gated endpoints gracefully Sport/audience endpoints need a subscription. Check access up front, or catch the typed `PlanError`. See [Errors & limits](/docs/sdk/errors). TypeScript ``` import { PlanError } from 'heisenberg-ai'; if (hb.requires(602)) console.log('closingLine needs a plan:', hb.requires(602)); try { const clv = await hb.sports.closingLine(conditionId); } catch (e) { if (e instanceof PlanError) console.log('locked:', e.message, '→', e.requiredPlan); else throw e; } ``` Python ``` from heisenberg import PlanError if hb.requires(602): print("closing_line needs a plan:", hb.requires(602)) try: clv = hb.sports.closing_line(condition_id).page() except PlanError as e: print("locked:", str(e), "→", e.required_plan) ``` --- # SDK Streaming _Source: https://prediction.heisenberg.so/docs/sdk/streaming_ SDK · Guides # Streaming `hb.stream.trades()` delivers live Polymarket trades over a WebSocket. It handles the connection, subscription, and reconnection for you — you just iterate. ## Install the streaming extra Streaming needs a WebSocket dependency (the REST client doesn't). install ``` # TypeScript npm install ws # Python pip install "heisenberg_ai[stream]" ``` ## Subscribe TypeScript ``` for await (const trade of hb.stream.trades({ condition_id: '0x…' })) { console.log(trade.price, trade.side, trade.proxy_wallet); } ``` Python ``` for trade in hb.stream.trades({"condition_id": "0x…"}): print(trade.get("price"), trade.get("side"), trade.get("proxy_wallet")) ``` ## Filters Pass any combination; only trades matching all of them are delivered. Omit a filter to receive everything on that dimension. condition\_id string Trades for one market. slug string Trades for a market by slug. proxy\_wallet string Trades by a specific wallet. outcome string e.g. Yes / No / a team name. side string "BUY" or "SELL". maker string Maker wallet. taker string Taker wallet. ## Trade event fields price number Price per share, 0–1. size number Shares traded. side string "BUY" | "SELL". outcome string Outcome traded. proxy\_wallet string Trader wallet. condition\_id string Market condition id. slug string Market slug. timestamp string ISO 8601 execution time. transaction\_hash string On-chain tx hash. ## Reconnection & reliability - On disconnect the client **reconnects with exponential backoff** and **re-sends your subscription** — the loop keeps yielding across drops. - Control messages (subscription acks, rate-limit notices) are handled internally and not surfaced as trades. - A fatal auth error ends the stream with an `AuthError` rather than reconnecting into a wall. - Cap reconnects with `maxReconnects` (TS) / `max_reconnects`(Python) if you want it to give up after N attempts. ## Stopping TypeScript ``` const stream = hb.stream.trades({ slug: 'some-market' }); for await (const t of stream) { if (done(t)) break; // breaking the loop closes the socket } // or pass an AbortSignal: hb.stream.trades(filters, { signal }) ``` Python ``` for t in hb.stream.trades({"slug": "some-market"}): if done(t): break # breaking closes the socket ``` The same stream is documented as a raw protocol under [WebSockets](/docs/websockets) if you want to connect without the SDK. --- # SDK Response Fields _Source: https://prediction.heisenberg.so/docs/sdk/responses_ SDK · Reference # Response fields The shapes returned by the highest-value methods. These tables are **generated from the API spec**, so they stay in sync when an endpoint changes — click through for full per-field descriptions. **Two SDK conventions.** Decimals on leaderboards and Market 360 arrive as **strings** (parse with `Number()` / `float()`); Wallet 360 risk-adjusted ratios are **null** without enough history. The SDK also decodes JSON columns for you and preserves any extra keys the API adds. ## `hb.polymarket.markets()` [Polymarket Markets — full field descriptions ↗](/docs/api-reference/polymarket-markets) closed boolean closed\_date string condition\_id string end\_date string event\_slug string question string side\_a\_outcome string side\_a\_token\_id string side\_b\_outcome string side\_b\_token\_id string slug string start\_date string volume\_total number winning\_outcome string ## `hb.polymarket.trades()` [Polymarket Trades — full field descriptions ↗](/docs/api-reference/polymarket-trades) condition\_id string id string outcome string price number proxy\_wallet string side string size number slug string timestamp string transaction\_hash string ## `hb.wallets.profile()` [Wallet 360 — full field descriptions ↗](/docs/api-reference/wallet-360) annualized\_return number avg\_position\_size number best\_trade number calculation\_window\_days number calmar\_ratio null category\_diversity\_score number coefficient\_of\_variation number combined\_risk\_score number curve\_smoothness number date string date\_range\_end string date\_range\_start string days\_active number dominant\_market\_id string dominant\_market\_pnl number drawdown\_frequency number edge\_decay null equity\_curve\_pattern string flagged\_metrics string gain\_to\_pain\_ratio number last\_active string losing\_trades number market\_concentration\_ratio number markets\_traded number max\_drawdown number max\_position\_pct number num\_markets\_traded number perfect\_entry\_count number perfect\_exit\_count number perfect\_timing\_flag boolean perfect\_timing\_score number performance\_by\_category string performance\_trend string position\_size\_consistency number position\_size\_volatility\_flag boolean profit\_factor number proxy\_wallet string recovery\_time\_avg number risk\_level string roi number sharpe\_ratio number similar\_wallets\_count number single\_market\_dependence\_flag boolean sortino\_ratio null statistical\_confidence number stddev\_position\_size number suspicious\_timing\_trades number suspicious\_win\_rate\_flag boolean sybil\_risk\_flag boolean sybil\_risk\_score number timing\_anomaly\_flag boolean timing\_hit\_rate number timing\_z\_score number total\_closed\_positions number total\_invested number total\_pnl number total\_timed\_trades number total\_trades number trade\_size\_stdev number trade\_timing\_correlation\_max number ulcer\_index number win\_rate number win\_rate\_last\_30d number win\_rate\_z\_score number winning\_trades number worst\_trade number ## `hb.markets.insights()` [Polymarket Market 360 — full field descriptions ↗](/docs/api-reference/polymarket-market-360) condition\_id string created\_at string current\_volume\_24h string current\_volume\_7d string end\_date string liquidity\_percentile string liquidity\_risk\_flag boolean liquidity\_tier string market\_active boolean market\_closed boolean net\_pnl string no\_avg\_pnl string peak\_hour\_trades number profit\_loss\_ratio string question string slug string snapshot\_time string squeeze\_risk\_flag boolean top10\_wallet\_pct string top1\_wallet\_pct string top3\_wallet\_pct string trade\_concentration\_flag boolean trades\_per\_hour\_avg string unique\_traders\_7d number updated\_at string volume\_collapse\_risk\_flag boolean volume\_ratio\_24h\_to\_7d string volume\_trend string whale\_control\_flag boolean winning\_side string yes\_avg\_pnl string ## `hb.leaderboards.heisenberg()` [Heisenberg Leaderboard — full field descriptions ↗](/docs/api-reference/heisenberg-leaderboard) See the API reference for this endpoint's fields. ## `hb.leaderboards.polymarketPnl()` [Polymarket PnL Leaderboard — full field descriptions ↗](/docs/api-reference/polymarket-pnl-leaderboard) address string markets\_traded number rank number roi string sharpe\_ratio null total\_pnl string total\_trades number total\_volume string win\_rate string In TypeScript these are exported types (`Wallet360Row`, `MarketRow`, …); in Python they are `TypedDict`s. Every endpoint and its complete field list lives in the [API reference](/docs/api-reference). --- # SDK Errors & Limits _Source: https://prediction.heisenberg.so/docs/sdk/errors_ SDK · Reference # Errors & limits Every failure is a typed error subclassing `HeisenbergError`. The API's own message is preserved, and each error carries the fields you need to branch and to get support. ## Error types AuthError 401 Missing or invalid token. PlanError 403 Your plan doesn’t include this endpoint. Carries requiredPlan, endpoint, agentId, code. NotFoundError 404 Unknown agent\_id / endpoint. RateLimitError 429 Too many requests. Carries retryAfter (seconds). ValidationError 400 / 422 Bad request or params. ApiError 5xx Server error. NetworkError — No HTTP response: DNS, connection, timeout, abort. Every error also carries `status`, `code`, `requestId`, and `raw` (the parsed response body) — include `requestId` when contacting support. ## Handling TypeScript ``` import { PlanError, RateLimitError, AuthError } from 'heisenberg-ai'; try { const page = await hb.sports.closingLine(conditionId); } catch (e) { if (e instanceof PlanError) console.log('needs plan:', e.requiredPlan, e.code); else if (e instanceof AuthError) console.log('bad token'); else if (e instanceof RateLimitError) console.log('retry after', e.retryAfter, 's'); else throw e; } ``` Python ``` from heisenberg import PlanError, RateLimitError, AuthError try: page = hb.sports.closing_line(condition_id).page() except PlanError as e: print("needs plan:", e.required_plan, e.code) except RateLimitError as e: print("retry after", e.retry_after, "s") except AuthError: print("bad token") ``` ## Automatic retries The client retries **429**, **5xx**, and transient network errors with exponential backoff (honoring `retry-after`), up to `maxRetries` (TS) / `max_retries` (Python), default **2**. A `RateLimitError` / `ApiError` is only thrown after retries are exhausted. Auth, plan, validation, and not-found errors are **not** retried — they won't succeed on a retry. ## Pagination limit Page size is capped at **200** rows; values above are clamped. Use auto-pagination to read past one page: `for await (…of hb.polymarket.trades(…))` (TS) / `for … in hb.polymarket.trades(…)` (Python), or `.all()`. ## Gated endpoints & quotas Sport and audience endpoints require a subscription; without it they raise a `PlanError`. Check ahead with `hb.requires(agentId)` or `hb.catalog()`. Request quotas depend on your plan — see [Pricing & Plans](/docs/getting-started/pricing). --- # Welcome to Heisenberg AI _Source: https://prediction.heisenberg.so/docs/getting-started_ Getting Started # Welcome to Heisenberg AI The most comprehensive prediction market intelligence API. Unified access to Polymarket, Kalshi, and social signals — through a single endpoint or Claude MCP integration. Sub-300ms latency Seconds-fresh data Zero rate-limit concerns ## Base URL https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized [ Authentication Learn how to authenticate your requests with API keys. ](/docs/getting-started/authentication)[ Request Format Understand the universal request body structure. ](/docs/getting-started/request-format)[ Response Format Learn how responses are structured with pagination. ](/docs/getting-started/response-format)[ API Reference Explore all available endpoints and try them live. ](/docs/api-reference) ## Make Your First Request All endpoints use a single POST endpoint. Pass the `agent_id` to select the data source and `params` to filter results. cURL ```bash curl -X POST \ https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -d '{ "agent_id": 574, "params": { "min_volume": "1000", "closed": "False" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` --- # Authentication _Source: https://prediction.heisenberg.so/docs/getting-started/authentication_ # Authentication All API requests require a Bearer token in the Authorization header. ## Get an API Token 1. 1Sign up at [prediction.heisenberg.so](https://prediction.heisenberg.so) and create an account. 2. 2Navigate to **Dashboard → API Keys** and generate a new key. 3. 3Copy the token — it will only be shown once. ## Using the Token Include your token in the `Authorization` header as a Bearer token: HTTP Header ```http Authorization: Bearer YOUR_API_TOKEN Content-Type: application/json ``` ## Full Example cURL ```bash curl -X POST \ https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -d '{"agent_id": 574, "params": {"min_volume": "1000"}}' ``` Security Never expose your API token in client-side code or public repositories. Use environment variables and server-side requests to keep your token secure. --- # Request Format _Source: https://prediction.heisenberg.so/docs/getting-started/request-format_ # Request Format All Heisenberg AI API endpoints use a single POST URL with a JSON body. The `agent_id` determines which data source to query. ## Body Structure JSON ```json { "agent_id": 574, // Required — selects the endpoint "params": { // Optional — filter parameters "min_volume": "1000", "closed": "False" }, "pagination": { // Optional — control result size "limit": 10, // 1–200, default varies by endpoint "offset": 0 // Skip N results for pagination }, "formatter_config": { // Optional — response formatting "format_type": "raw" // "raw" returns structured JSON } } ``` ## Field Reference Field Type Required Description agent\_id Integer Yes Identifies the data endpoint. See API Reference for all IDs. params Object No Key-value pairs for filtering. All values are strings. Available params vary by endpoint. pagination.limit Integer No Number of results per page (1–200). Defaults vary by endpoint. pagination.offset Integer No Number of results to skip. Use for pagination through large result sets. formatter\_config.format\_type String No Response format. Use `"raw"` for structured JSON. ## Tips - •All `params` values must be strings, even numbers (e.g. `"1000"` not `1000`). - •Omit optional fields entirely rather than passing null — the API ignores unknown fields. - •Use `limit: 200` for bulk retrieval and check `has_more` in the response for pagination. --- # Response Format _Source: https://prediction.heisenberg.so/docs/getting-started/response-format_ # Response Format All endpoints return a consistent JSON structure with metadata, pagination info, and results. ## Response Structure JSON Response ```json { "timestamp": "2026-04-06T12:00:00Z", // Server timestamp "params": { // Echo of your request params "min_volume": "1000", "closed": "False" }, "pagination": { "limit": 10, // Your requested limit "offset": 0, // Your requested offset "has_more": true // More results available? }, "data": { "results": [ // Array of result objects { ... }, { ... } ] }, "request_id": "abc-123-def" // Unique request identifier } ``` ## Field Reference Field Type Description timestamp String (ISO 8601) Server-side timestamp of the response. params Object Echo of the params you sent in the request. pagination.limit Integer Number of results returned in this page. pagination.offset Integer Number of results skipped. pagination.has\_more Boolean If true, more results are available. Increment offset to fetch the next page. data.results Array Array of result objects. Structure varies by endpoint — see individual endpoint docs. request\_id String Unique identifier for debugging. Include in support requests. ## Pagination To paginate through results, check `has_more` in the response and increment `offset` by `limit`: Pagination Example ```json // Page 1 { "pagination": { "limit": 50, "offset": 0 } } // Page 2 (if has_more: true) { "pagination": { "limit": 50, "offset": 50 } } // Page 3 { "pagination": { "limit": 50, "offset": 100 } } ``` ## Timestamp Format All timestamps in responses use **ISO 8601** format in UTC: `2026-04-06T12:00:00Z`. Some endpoints accept Unix timestamps as strings in params — check each endpoint's documentation for details. --- # Error Handling _Source: https://prediction.heisenberg.so/docs/getting-started/errors_ Reference # Error Handling How to interpret error responses and recover gracefully. ## Error Response Format When a request fails, the response body contains a structured error object: Error Response ```json { "error": { "code": "INVALID_PARAMS", "message": "Parameter 'min_volume' must be a string", "request_id": "req_abc123" } } ``` ## HTTP Status Codes Code Meaning What to Do 200 Success Request completed. Parse data.results as usual. 400 Bad Request Check your request body — missing agent\_id, malformed JSON, or invalid param values. All params must be strings. 401 Unauthorized Missing or invalid API token. Verify your Authorization: Bearer header. 403 Forbidden Your token doesn't have access to this endpoint. Check your plan or contact support. 404 Not Found Invalid agent\_id or the endpoint doesn't exist. Check the API Reference for valid IDs. 429 Rate Limited Too many requests. Back off and retry with exponential delay. 500 Server Error Something went wrong on our end. Retry after a brief delay. If persistent, contact support with the request\_id. 503 Unavailable Service temporarily unavailable. Retry in a few seconds. ## Common Mistakes Passing numbers instead of strings in params Wrong`"min_volume": 1000` Correct`"min_volume": "1000"` All param values must be strings, even numeric ones. Missing Authorization header Wrong`curl -X POST ... -d '{"agent_id": 574}'` Correct`curl -X POST ... -H "Authorization: Bearer YOUR_TOKEN" -d '...'` Every request requires the Bearer token header. Using an invalid agent\_id Wrong`"agent_id": 999` Correct`"agent_id": 574` Check the API Reference sidebar for valid endpoint IDs. ## Retry Strategy For `429`, `500`, and `503` responses, use exponential backoff: Python ```python import time, requests def query(body, max_retries=3): for attempt in range(max_retries): resp = requests.post(URL, json=body, headers=HEADERS) if resp.status_code == 200: return resp.json() if resp.status_code in (429, 500, 503): time.sleep(2 ** attempt) # 1s, 2s, 4s continue resp.raise_for_status() # 400/401/403 → fail fast ``` --- # SDKs & Libraries _Source: https://prediction.heisenberg.so/docs/getting-started/sdks_ Reference # SDKs & Libraries Use the official Heisenberg SDK for a fully typed client, or call the single POST endpoint directly with the lightweight wrappers below. ## Official SDK — TypeScript & Python Typed resources, venues, auto-pagination, streaming, and gating built in One client for the whole intelligence API — `hb.polymarket.markets()`, `hb.wallets.profile()`, `hb.smartMoney.pulse()`, `hb.stream.trades()` — generated from a single spec so TypeScript and Python stay identical. Read-only; your token is only ever sent as a Bearer header. [Get started with the SDK](/docs/sdk) ## Roll your own The API is a single POST endpoint — no SDK required. Drop one of these lightweight wrappers into any project to get going fast. ## Python requests or httpx — zero dependencies beyond stdlib heisenberg.py — drop into your project ```python import requests class Heisenberg: URL = "https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized" def __init__(self, token: str): self.headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json" } def query(self, agent_id: int, params: dict = None, limit: int = 10, offset: int = 0): body = { "agent_id": agent_id, "params": params or {}, "pagination": {"limit": limit, "offset": offset}, "formatter_config": {"format_type": "raw"} } resp = requests.post(self.URL, json=body, headers=self.headers) resp.raise_for_status() return resp.json() # Usage h = Heisenberg("YOUR_API_TOKEN") markets = h.query(574, {"min_volume": "1000", "closed": "False"}) print(markets["data"]["results"]) ``` ## JavaScript / TypeScript Fetch API — works in Node.js, Deno, Bun, and browsers heisenberg.ts — drop into your project ```typescript const URL = "https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized"; export async function query( token: string, agentId: number, params: Record = {}, limit = 10, offset = 0 ) { const resp = await fetch(URL, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, body: JSON.stringify({ agent_id: agentId, params, pagination: { limit, offset }, formatter_config: { format_type: "raw" }, }), }); if (!resp.ok) throw new Error(`${resp.status}: ${await resp.text()}`); return resp.json(); } // Usage const data = await query("YOUR_TOKEN", 574, { min_volume: "1000" }); console.log(data.data.results); ``` ## cURL Quick testing from the command line Shell ```bash # Set your token once export HEISENBERG_TOKEN="YOUR_API_TOKEN" # Query any endpoint by changing agent_id and params curl -s -X POST https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ -H "Authorization: Bearer $HEISENBERG_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "agent_id": 574, "params": {"min_volume": "1000"}, "pagination": {"limit": 5, "offset": 0}, "formatter_config": {"format_type": "raw"} }' | python3 -m json.tool ``` ## No Code? Use Claude MCP Skip the code entirely. Connect Heisenberg AI as an MCP server and query prediction markets in natural language directly inside Claude. [Set up Claude MCP →](/docs/getting-started/mcp) ## Community Contributions Building a wrapper, SDK, or integration? We'd love to feature it here. Reach out at [contact@heisenberg.so](mailto:contact@heisenberg.so). --- # Migration Guide _Source: https://prediction.heisenberg.so/docs/getting-started/migration_ Reference # Migration Guide Already integrating with Polymarket or Kalshi directly? Here's how to switch to Heisenberg AI and get unified access, better analytics, and zero rate-limit headaches. ## Why Migrate? ### One endpoint, all platforms Stop maintaining separate integrations for Polymarket, Kalshi, and social data. ### No rate limit management Heisenberg AI handles upstream rate limits. You never get throttled by source APIs. ### Enriched data Get computed metrics (H-Score, Wallet 360, Market 360) that don't exist in source APIs. ### Sub-300ms latency Faster than hitting source APIs directly, with always-fresh cached data. ## From Polymarket API Polymarket Endpoint Heisenberg AI Equivalent agent\_id GET /markets Polymarket Markets 574 GET /trades Polymarket Trades 556 GET /prices/history Polymarket Candlesticks 568 GET /book Polymarket Orderbook 572 (not available) Wallet 360 581 (not available) H-Score Leaderboard 584 (not available) Price Jump Detection 596 (not available) Market 360 575 Before (Polymarket Direct) ```http GET https://clob.polymarket.com/markets ?closed=false &limit=10 Headers: ... ``` After (Heisenberg AI) ```http POST /api/v2/.../parameterized { "agent_id": 574, "params": {"closed": "False"}, "pagination": {"limit": 10} } ``` ## From Kalshi API Kalshi Endpoint Heisenberg AI Equivalent agent\_id GET /markets Kalshi Markets 565 GET /markets/trades Kalshi Trades 573 ## Key Differences to Note Single POST endpoint Heisenberg AI uses one URL for everything. The agent\_id in the body replaces different URL paths. All params are strings Unlike source APIs that accept mixed types, Heisenberg AI params are always string values: "1000" not 1000. Unified pagination Every endpoint uses the same limit/offset/has\_more pattern. No per-endpoint cursor differences. Bearer token auth Single Authorization: Bearer header replaces per-platform auth schemes. --- # Glossary _Source: https://prediction.heisenberg.so/docs/getting-started/glossary_ Reference # Glossary Key terms used across the Heisenberg AI API and prediction market ecosystem. ## Heisenberg AI `agent_id` Integer that identifies which data endpoint to query. Each Heisenberg AI endpoint (Markets, Trades, Wallet 360, etc.) has a unique agent\_id. Passed in the request body. `H-Score` Proprietary 0–100 composite score measuring a wallet's prediction market trading skill. Factors in profitability, accuracy, consistency, risk management, and diversification. `Wallet 360` Comprehensive wallet intelligence profile with 60+ computed metrics covering performance, risk, behavior, and activity patterns. `Market 360` Market quality and health assessment — liquidity depth, volume dynamics, whale concentration, and price stability. `formatter_config` Request body field controlling response format. Use {"format\_type": "raw"} for structured JSON responses. `has_more` Boolean in the pagination response. When true, more results exist beyond the current page. Increment offset by limit to fetch the next page. ## Polymarket `condition_id` Hex string uniquely identifying a market (question) on Polymarket. A market can have multiple outcomes, each with its own token\_id. Example: 0xbcacd5a055f5... `token_id` Large integer identifying a specific outcome token within a Polymarket market. Each side of a binary market (Yes/No) has its own token\_id. Used for trading and price queries. `proxy_wallet` The Polymarket proxy wallet address associated with a user. This is the address that executes trades on-chain, not the user's EOA. ## Trading `PnL` Profit and Loss — the net financial result of a wallet's trading activity. Can be realized (closed positions) or unrealized (open positions). `OHLCV` Open, High, Low, Close, Volume — standard candlestick data format used in price charts. Each candle represents a fixed time period. `resolution` Time bucket size for candlestick data. Options: 1m, 5m, 15m, 1h, 4h, 1d. Smaller resolution = more granular data. ## General `slug` URL-friendly identifier for a market. Example: "will-bitcoin-hit-100k-by-2026". Used for lookups and search queries. `event_slug` Slug identifying the parent event that groups related markets together. One event (e.g., "2024 US Election") can contain many markets. `outcome` A possible result of a prediction market. Binary markets have "Yes"/"No" outcomes. Multi-outcome markets can have many (e.g., candidate names). ## Integration `MCP` Model Context Protocol — an open standard for connecting AI models to external data sources. Heisenberg AI supports MCP for Claude integration. --- # Direct API _Source: https://prediction.heisenberg.so/docs/getting-started/direct-api_ # Direct API Integration Integrate directly into your trading systems, bots, dashboards, or analytical workflows via REST API. ## Base URL All endpoints use a single POST URL. The `agent_id` in the body determines which data you get. https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized ## cURL cURL ```bash curl -X POST \ https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -d '{ "agent_id": 574, "params": { "min_volume": "1000", "closed": "False" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` ## Python Python ```python import requests response = requests.post( "https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized", headers={"Authorization": "Bearer YOUR_API_TOKEN"}, json={ "agent_id": 574, "params": {"closed": "False", "min_volume": "1000"}, "pagination": {"limit": 10, "offset": 0}, "formatter_config": {"format_type": "raw"} } ) data = response.json() print(data["data"]["results"]) ``` ## JavaScript JavaScript ```javascript const response = await fetch("https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized", { method: "POST", headers: { "Authorization": "Bearer YOUR_API_TOKEN", "Content-Type": "application/json" }, body: JSON.stringify({ agent_id: 574, params: { closed: "False", min_volume: "1000" }, pagination: { limit: 10, offset: 0 }, formatter_config: { format_type: "raw" } }) }); const data = await response.json(); console.log(data.data.results); ``` ## Next Steps - •Learn about the [Request Format](/docs/getting-started/request-format) for all available options - •Understand the [Response Format](/docs/getting-started/response-format) and pagination - •Browse the [API Reference](/docs/api-reference) for all endpoints --- # Work with AI (MCP) _Source: https://prediction.heisenberg.so/docs/getting-started/mcp_ Recommended # Work with AI Connect Heisenberg AI to Claude via MCP and query prediction markets in natural language. No code, no API calls — just ask questions and get structured answers instantly. ## Claude Pro / Team / Enterprise claude.ai web interface 1Go to Settings → Integrations → Add MCP server 2Paste the server URL below 3Name it Prediction Market Intelligence 4Authenticate with your API token on first use https://narrative.agent.heisenberg.so/sse ## Claude Desktop Free desktop app 1Open a terminal and run the command below 2Follow the prompts to configure your API token 3Restart Claude Desktop — the server appears in integrations npx heisenberg-mcp ## What You Can Ask “ What are the most traded markets on Polymarket right now? Market Discovery “ Show me the top wallets by profit this week Leaderboards “ Analyze wallet 0x1234... — is this a good trader? Wallet Intelligence “ Are there any sharp price moves on the election market? Anomaly Detection “ Compare Polymarket and Kalshi pricing for the Fed decision Cross-Platform “ What is the social sentiment around this market? Social Intelligence ## Why MCP? ### Zero Code No API calls, no JSON parsing, no authentication flow. Just ask questions. ### Real-Time Claude queries Heisenberg AI live — every answer reflects the latest market state. ### Full Access All endpoints available. Markets, trades, wallets, analytics, social data. --- # Pricing & Plans _Source: https://prediction.heisenberg.so/docs/getting-started/pricing_ Reference # Pricing & Plans Start free, scale as you grow. All plans include sub-300ms latency and seconds-fresh data. ### Explorer Free Get started and explore the API - ✓All public endpoints - ✓MCP integration - ✓Community support ### Growth Contact Us For teams building production systems - ✓Higher rate limits - ✓Priority support - ✓Advanced analytics endpoints ### Enterprise Custom For platforms and institutions - ✓Dedicated infrastructure - ✓Custom data agents - ✓Historical data exports - ✓SLA guarantees - ✓Direct engineering support ## Included in All Plans ✓Sub-300ms API response times ✓Seconds-fresh data across all endpoints ✓Claude MCP integration ✓Interactive API playground ✓Unified endpoint across platforms ✓Structured JSON responses ## Need a Custom Plan? Building something that needs dedicated capacity, custom data agents, or SLA guarantees? Let's talk. [contact@heisenberg.so](mailto:contact@heisenberg.so) --- # Concepts _Source: https://prediction.heisenberg.so/docs/concepts_ Concepts # How Heisenberg AI Works Heisenberg AI is an intelligence execution layer for prediction markets. It connects to live data sources, enriches everything through autonomous data agents, and serves it all through a single, sub-300ms API. ## The Problem - ×Data fragmented across Polymarket, Kalshi, social platforms - ×Each platform has its own API, auth, rate limits, and format - ×No computed analytics — just raw data you have to process yourself - ×Building takes weeks of integration work per platform ## With Heisenberg AI - ✓One endpoint, all platforms, unified format - ✓Sub-300ms latency, seconds-fresh data - ✓Proprietary analytics: H-Score, Wallet 360, Market 360 - ✓Start building in minutes, not weeks ## Architecture Step 1 ### Ingest Autonomous data agents continuously collect from Polymarket, Kalshi, social platforms, and on-chain sources via WebSocket and polling connections. Step 2 ### Normalize Raw data is cleaned, deduplicated, and transformed into a unified schema. Different platform formats become one consistent structure. Step 3 ### Enrich Data agents compute proprietary metrics — H-Scores, wallet profiles, market quality assessments, anomaly detection — on every update cycle. Step 4 ### Serve Enriched intelligence is served through the unified API with sub-300ms latency. Query any metric, any platform, with a single POST call. Core Principle Heisenberg AI is an execution layer, not a static data warehouse. Data agents connect to live sources continuously — so you always get the freshest results, enriched with proprietary intelligence, delivered in under 300 milliseconds. ## Explore Further [ Data Foundation Sources, collection process, and data freshness ](/docs/concepts/data-foundation)[ Intelligence Outputs H-Score, Wallet 360, Market 360, and more ](/docs/concepts/intelligence-outputs)[ Streaming & Reliability Latency, uptime, and infrastructure ](/docs/concepts/streaming)[ H-Score Proprietary trader intelligence scoring ](/docs/concepts/h-score-methodology) --- # H-Score Methodology _Source: https://prediction.heisenberg.so/docs/concepts/h-score-methodology_ Concepts # H-Score The Heisenberg AI Score (H-Score) is a proprietary 0–100 rating that measures a wallet's prediction market trading skill. It's designed to separate consistently skilled traders from those who got lucky once. 0 – 100 Composite score range The H-Score uses a proprietary multi-factor model developed by the Heisenberg AI research team. The methodology, weights, and specific factors are not publicly disclosed. The score is recalculated regularly as new trading data becomes available. ## What It Captures At a high level, the H-Score is designed to reward wallets that demonstrate genuine, repeatable trading skill — not just raw profit. A wallet that made $100K on one lucky bet will score very differently from one that made $100K across 500 well-timed positions. The score accounts for multiple dimensions of trading quality and is specifically tuned for the dynamics of prediction markets — where binary outcomes, time decay, and event-driven volatility create a different landscape than traditional finance. ## Score Tiers Range Tier Description 90–100 Legendary Exceptional. Top fraction of active wallets. 75–89 Elite Strong sustained performance. 60–74 Skilled Above-average with demonstrable edge. 40–59 Developing Mixed results. Some signal present. 20–39 Novice Limited track record. 0–19 Inactive Insufficient activity for scoring. ## Trajectory Each wallet also has a `trajectory` field: `rising` Score trending upward. `stable` Score holding steady. `declining` Score trending downward. ## How to Access H-Scores are available through two endpoints: - •[Heisenberg Leaderboard](/docs/api-reference/heisenberg-leaderboard) — ranked list of top wallets by H-Score - •[Wallet 360](/docs/api-reference/wallet-360) — full wallet profile including H-Score Methodology Details The H-Score methodology is proprietary and not publicly documented. For research partnerships or enterprise-level methodology discussions, contact us at [contact@heisenberg.so](mailto:contact@heisenberg.so). --- # Data Foundation _Source: https://prediction.heisenberg.so/docs/concepts/data-foundation_ # Data Foundation Heisenberg AI continuously collects, cleans, and normalizes data from multiple prediction market platforms and social sources. ## Data Sources ### Polymarket Live Markets, trades, orderbooks, candlesticks, wallet analytics, and PnL data from the largest crypto prediction market. ### Kalshi Live Market catalog and trade history from the US-regulated prediction exchange. ### Social Media Live Social mentions and sentiment from X/Twitter and other platforms, delivered within seconds and filtered for prediction market relevance. ## Collection Process - •Data is collected continuously via WebSocket connections and polling where needed. - •Raw data is cleaned and normalized into a consistent schema across all platforms. - •Heisenberg AI handles rate limits, retries, and reconnections so you don't have to. ## Data Freshness Trades, prices, and market state are available within seconds of the source event. All API responses are served with sub-300ms latency. Computed analytics like H-Scores and wallet profiles are refreshed on a regular cadence. **Why this matters:** Stale data costs money in prediction markets. A 10-second delay on a trade feed can mean missing a price move entirely. Heisenberg AI is built for the speed that trading demands. --- # Intelligence Outputs _Source: https://prediction.heisenberg.so/docs/concepts/intelligence-outputs_ Concepts # Intelligence Outputs Heisenberg AI doesn't just proxy raw data. It transforms market activity into actionable intelligence through proprietary scoring, profiling, and detection systems. **How it works:** Raw data flows through multi-stage data agents that autonomously normalize, enrich, and score every wallet, market, and event across platforms — producing metrics you can't get from source APIs alone. ## H-Score Proprietary Trader Intelligence Score The Heisenberg AI Score is a proprietary 0–100 rating that quantifies how skilled a wallet is at prediction market trading. It uses a multi-factor model specifically tuned for prediction market dynamics — separating consistently skilled traders from one-time winners. Example H-Score Response ```json { "wallet": "0x1a2b...3c4d", "h_score": 87, "tier": "Elite", "trajectory": "rising" } ``` Available via [Heisenberg Leaderboard](/docs/api-reference/heisenberg-leaderboard) and [Wallet 360](/docs/api-reference/wallet-360). ## Wallet 360 Comprehensive Wallet Intelligence Profile A full 360-degree profile of any prediction market wallet with 60+ computed metrics. Think of it as a credit report for traders — covering performance, behavior, risk, and activity patterns. Performance Total PnL, ROI, win rate, average position size, largest win/loss, Sharpe-equivalent ratio Risk Profile Max drawdown, position concentration, loss streak patterns, leverage indicators Behavioral Patterns Trading frequency, time-of-day patterns, market preferences, contrarian vs. momentum tendencies Activity Metrics Active markets, trade count by period, first/last seen, dormancy indicators Available via [Wallet 360](/docs/api-reference/wallet-360) endpoint. ## Market 360 Market Quality & Health Assessment Not all markets are created equal. Market 360 evaluates the health and tradability of individual prediction markets, helping you avoid illiquid or manipulated venues. ### Liquidity Depth Orderbook thickness and bid-ask spread analysis at multiple price levels. ### Volume Dynamics Trading volume trends, acceleration patterns, and organic vs. wash activity signals. ### Whale Concentration Distribution of holdings across wallets — how concentrated is the market? ### Price Stability Volatility metrics, mean reversion tendencies, and manipulation resistance indicators. Available via [Market 360](/docs/api-reference/polymarket-market-360) endpoint. ## Price Jump Detection Automated Anomaly & Momentum Detection Continuous scanning of candlestick data across markets to detect statistically significant price movements as they happen. Configurable sensitivity for different trading strategies. `Resolution` Candle bucket size — 1m, 5m, 15m, 1h, 4h, 1d. Finer resolution catches faster moves. `Threshold` Minimum % change to qualify as a jump. Lower = more signals, higher = fewer but stronger. `Lookback` How far back to scan. 24h for recent activity, 168h for weekly patterns. Example Detection ```json { "jump_time": "2026-04-06T02:00:00Z", "direction": "down", "change_pct": "-16.67", "price_before": "0.1800", "price_after": "0.1500", "volume": "7350.07", "trade_count": 28 } ``` Available via [Price Jumps](/docs/api-reference/polymarket-price-jumps) endpoint. ## Social Pulse Real-Time Social Intelligence Monitors social platforms for prediction market-relevant discussions, filtering noise to surface signals that matter for market analysis and trading decisions. ### Keyword Monitoring Track specific topics, events, or market slugs across social platforms. ### Trend Detection Identify emerging narratives before they move markets. ### Volume Spikes Detect unusual surges in social activity around prediction market events. ### Source Filtering Focus on high-signal accounts and platforms relevant to your markets. Available via [Social Pulse](/docs/api-reference/social-pulse) endpoint. ## How Data Agents Work 1 ### Ingest Raw trades, orderbooks, market metadata, and social data flow in continuously from all connected platforms. 2 ### Normalize Data is cleaned, deduplicated, and transformed into a unified schema across Polymarket, Kalshi, and social sources. 3 ### Enrich Data agents autonomously compute derived metrics — H-Scores, wallet profiles, market quality, anomaly scores — on every update cycle. 4 ### Serve Enriched data is served through the unified API with sub-second latency. Query any metric across any platform with a single call. --- # Streaming & Reliability _Source: https://prediction.heisenberg.so/docs/concepts/streaming_ Concepts # Streaming & Reliability Built for speed and reliability from day one. Heisenberg AI handles the infrastructure complexity so your integrations stay fast, fresh, and always-on. ## Performance <300ms API Latency Median response time across all endpoints, measured at the edge. Seconds Data Freshness Most data available within seconds of the source event. Seconds-fresh by default. 99.9% Uptime Target Redundant infrastructure with automatic failover and 24/7 data agent monitoring. ## Data Freshness by Type Data Type Freshness Source Trades & Prices Within seconds Polymarket, Kalshi Orderbook Snapshots Within seconds Polymarket Market Metadata Within seconds Polymarket, Kalshi Social Mentions Within seconds X/Twitter, Reddit Candlesticks (OHLCV) Per-candle close Computed H-Score & Wallet Profiles Updated every few hours Computed Market 360 Scores Updated every few hours Computed ## Rate Limit Resilience You never interact with source platform APIs directly. Heisenberg AI maintains persistent connections to all data sources, handles rate limits, retries, and reconnections behind the scenes, and serves fresh data through its own endpoint. ### Without Heisenberg AI - ×Manage API keys per platform - ×Handle rate limits and retries - ×Normalize different data formats - ×Maintain WebSocket connections - ×Monitor for API changes and outages ### With Heisenberg AI - ✓One API key, one endpoint - ✓No rate limit concerns - ✓Consistent JSON format across platforms - ✓Seconds-fresh, always-on data - ✓Sub-300ms response times ## MCP Streaming The Claude MCP integration uses Server-Sent Events (SSE) for live streaming. Claude can query prediction market data mid-conversation and receive structured results with sub-second latency — no polling, no delays, no stale context. ## Infrastructure Heisenberg AI runs on redundant, globally distributed infrastructure with automatic failover. Data agents are monitored around the clock with alerting on staleness thresholds. Every response includes a `request_id` for end-to-end traceability. --- # Trading & Execution _Source: https://prediction.heisenberg.so/docs/use-cases/trading-platforms_ Build With Heisenberg AI # Trading & Execution Build prediction market trading tools with live data, wallet intelligence, and market analytics — all from one API. ## Copy-Trading Workflow Mirror top-performing wallets as they trade 1 ### Discover Find top wallets via the PnL Leaderboard or H-Score Leaderboard. PnL Leaderboard · H-Score Leaderboard 2 ### Validate Check consistency and risk profile with Wallet 360 — 60+ metrics per wallet. Wallet 360 3 ### Monitor Track their trades within seconds, filtered by wallet address. Polymarket Trades 4 ### Execute Mirror positions through your execution layer when new activity is detected. ## Market Screening & Selection Find the best markets to trade [ ### Discover Search active markets filtered by volume, status, and category. Markets →](/docs/api-reference/polymarket-markets)[ ### Assess Evaluate market quality — liquidity depth, whale concentration, volume trends. Market 360 →](/docs/api-reference/polymarket-market-360)[ ### Time Detect significant price movements for entry/exit timing. Price Jumps →](/docs/api-reference/polymarket-price-jumps) ## Cross-Exchange Arbitrage Exploit pricing discrepancies between platforms Compare identical events across Polymarket and Kalshi through a single API. No need to manage separate integrations — Heisenberg AI normalizes the data. [ Polymarket Markets Search and filter prediction markets on Polymarket. ](/docs/api-reference/polymarket-markets)[ Kalshi Markets Search the Kalshi regulated market catalog. ](/docs/api-reference/kalshi-markets)[ Candlesticks Price history for tracking divergences over time. ](/docs/api-reference/polymarket-candlesticks)[ Kalshi Trades Historical trade data for timing and volume analysis. ](/docs/api-reference/kalshi-trades) --- # LLM & Agent Pipelines _Source: https://prediction.heisenberg.so/docs/use-cases/ai-agents_ # AI Agents Give your AI agents live prediction market intelligence through Claude MCP or direct API calls. ## Claude MCP Integration The fastest way to add prediction market awareness to an AI agent. Connect Heisenberg AI as an MCP server and Claude can query markets, analyze wallets, and surface opportunities in natural language. **Setup guide:** See [Work with AI](/docs/getting-started/mcp) for step-by-step MCP setup. Example agent prompts: - •"What are the highest-volume open markets on Polymarket?" - •"Analyze wallet 0x1234... — is this a good trader to follow?" - •"Are there any sharp price moves on the US election market in the last hour?" - •"Compare Polymarket and Kalshi odds for the Fed rate decision" ## Autonomous Trading Agents Build agents that autonomously monitor and trade prediction markets: 1. 1**Monitor:** Poll [Social Pulse](/docs/api-reference/social-pulse) for breaking news and [Price Jumps](/docs/api-reference/polymarket-price-jumps) for anomalies. 2. 2**Analyze:** Use [Market 360](/docs/api-reference/polymarket-market-360) and [Orderbook](/docs/api-reference/polymarket-orderbook) to assess market conditions. 3. 3**Validate:** Cross-reference with smart money positions via [Trades](/docs/api-reference/polymarket-trades) to see how top wallets are positioned. 4. 4**Execute:** Place trades based on your agent's strategy and risk parameters. ## RAG & Knowledge Retrieval Use Heisenberg AI as a live data source for Retrieval-Augmented Generation. The structured JSON responses are designed to be easily ingested by LLMs. Pass API results directly into your agent's context window for grounded, fact-based responses about prediction markets. --- # Dashboards & Signals _Source: https://prediction.heisenberg.so/docs/use-cases/analytics-research_ # Analytics & Research Power dashboards, research tools, and analytical platforms with comprehensive prediction market data. ## Intelligence Dashboards Build live monitoring dashboards that combine market activity, wallet analytics, and social signals. - •Market overview with volume, open interest, and price trends via [Markets](/docs/api-reference/polymarket-markets) and [Candlesticks](/docs/api-reference/polymarket-candlesticks). - •Whale tracking and smart money flow using [Trades](/docs/api-reference/polymarket-trades) filtered by wallet. - •Social sentiment overlay from [Social Pulse](/docs/api-reference/social-pulse). ## Wallet Profiling & Ranking Create leaderboards, trader profiles, and performance analytics. - •[Wallet 360](/docs/api-reference/wallet-360) provides 60+ metrics per wallet — performance, risk, behavioral patterns. - •[H-Score Leaderboard](/docs/api-reference/heisenberg-leaderboard) ranks wallets by proprietary trading skill score. - •[PnL Leaderboard](/docs/api-reference/polymarket-pnl-leaderboard) ranks by raw profit across time windows. ## Academic & Quantitative Research Access historical trade data, orderbook snapshots, and market metrics for quantitative analysis. Use pagination to bulk-export datasets. Combine with the [Research Data](/docs/research-data) offering for customized historical datasets and training data. --- # Account _Source: https://prediction.heisenberg.so/docs/dashboard/account_ # Account Manage your Heisenberg AI account, profile settings, and preferences. ## Creating an Account Sign up at [prediction.heisenberg.so](https://prediction.heisenberg.so) with your email. You'll receive a one-time code to verify your address — no password needed. ## Dashboard Access Once signed in, your dashboard gives you access to API key management, usage metrics, and the interactive playground. Navigate to [prediction.heisenberg.so/dashboard](https://prediction.heisenberg.so/dashboard) to get started. --- # Playground _Source: https://prediction.heisenberg.so/docs/dashboard/playground_ # Playground Test any endpoint directly from the browser without writing code. ## How It Works Every endpoint in the [API Reference](/docs/api-reference) has a "Try It" button. Click it to open the interactive playground where you can: - •Edit parameters and see the request body update live. - •Send live requests and inspect the JSON response. - •Adjust pagination (limit, offset) to explore result sets. - •View latency metrics for each request. ## Authentication Required You need to be signed in to send requests from the playground. Your API token is automatically included in the request headers. [Get an API token](/docs/getting-started/authentication) if you don't have one yet. --- # API Reference _Source: https://prediction.heisenberg.so/docs/api-reference_ Introduction # Getting Started Authentication, base URL, and your first API call. All endpoints respond in under 300ms with seconds-fresh data. ## Base URL All Heisenberg AI API requests are made to a single POST endpoint: https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized ## Authentication Every request must include your API key in the `Authorization` header: ```bash curl https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ -H "Authorization: Bearer YOUR_API_KEY" ``` You can generate an API key from your [Heisenberg AI Dashboard](/docs/getting-started/authentication). ⚠Keep your API key secret. Do not expose it in client-side code or public repositories. ## Making Your First Request 1 ### Create an account Sign up at [prediction.heisenberg.so](https://prediction.heisenberg.so) and grab an API key from the dashboard. 2 ### Choose an endpoint Each data source has a unique `agent_id`. Browse the sidebar to find the endpoint you need. 3 ### Send a request Use the base URL with your API key to make your first call: cURL ```bash curl -X POST \ https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "agent_id": 574, "params": { "min_volume": "1000", "closed": "False" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` ## Response Format All endpoints return a consistent structure. See the full [Response Format](/docs/getting-started/response-format) documentation. ```json { "timestamp": "...", "params": { ... }, "pagination": { "limit": 10, "offset": 0, "has_more": false }, "data": { "results": [ ... ] }, "request_id": "..." } ``` --- # WebSockets _Source: https://prediction.heisenberg.so/docs/websockets_ Livev1.1.2 # WebSockets Stream live prediction-market events over a single persistent connection — no polling, no rate-limit juggling. The first live stream delivers **Polymarket trades** as they execute, with server-side filtering by wallet, market, outcome, and more so you only receive the events you care about. Prefer the SDK? The [SDK streaming client](/docs/sdk/streaming) (`hb.stream.trades()`) wraps this protocol — connection, subscription, and reconnection are handled for you. This section documents the raw protocol for building your own client. ## Connection Open a WebSocket connection to the gateway and authenticate with your Heisenberg AI API token as a Bearer credential. Your token is verified at the connection upgrade, so only authenticated clients stream. WebSocket URL ``` wss://ripple.heisenberg.so/ws ``` HTTP Header (sent on the upgrade request) ``` Authorization: Bearer YOUR_API_TOKEN ``` Connect from your backend Stream from a server-side client (Node, Python, Go) and send your token in the `Authorization` header — the standard setup for production streaming. Keep your API token server-side. ## Event Types Every stream is identified by an event type. Today `polymarket.trade` is live, the first of more to come. Access to each type is governed by your plan. Call `GET /event-types` for the catalog you're authorized for — it returns each type's field schema, including a per-field `filterable` flag that tells you exactly which fields you can filter on. cURL ``` curl https://ripple.heisenberg.so/event-types \ -H "Authorization: Bearer YOUR_API_TOKEN" ``` 200 · Response (abridged) ``` [ { "name": "polymarket.trade", "label": "polymarket_trades_realtime", "description": "", "schema": { "fields": [ { "name": "slug", "type": "string", "filterable": true }, { "name": "proxy_wallet", "type": "string", "filterable": true }, { "name": "outcome", "type": "string", "filterable": true }, { "name": "price", "type": "float", "filterable": false } ] } } ] ``` Abridged — `schema.fields` lists all 24 fields of `polymarket.trade`. See [Event messages](/docs/websockets/messages) for the full payload. [Next: Subscribe & filters →](/docs/websockets/subscribe) --- # WebSockets · Subscribe & Filters _Source: https://prediction.heisenberg.so/docs/websockets/subscribe_ WebSockets # Subscribe & filters Open one or many streams in a single frame, and filter server-side so you only receive the events you care about. ## Subscribe Once connected, send a `subscribe` frame. Each frame can open multiple subscriptions at once — pass one entry per stream in the `subscriptions` array. Omit `filters` (or pass `{}`) to receive _every_ event of that type. Subscribe to all trades JSON · client → server ``` { "action": "subscribe", "subscriptions": [ { "type": "polymarket.trade", "filters": {} } ] } ``` Subscribe to one market JSON · client → server ``` { "action": "subscribe", "subscriptions": [ { "type": "polymarket.trade", "filters": { "slug": "sol-updown-15m-1779670800" } } ] } ``` The server replies with a `subscribed` acknowledgement listing the event types it granted and a unique `id` for each subscription. Keep each `id` — you need it to unsubscribe. The `filters` you sent are echoed back when present. JSON · server → client ``` { "action": "subscribed", "types": ["polymarket.trade"], "subscriptions": [ { "id": "cede7755-c0a6-41b8-b316-ca4377dedb5d", "type": "polymarket.trade", "filters": { "slug": "sol-updown-15m-1779670800" } } ] } ``` Control messages vs. events Acknowledgements, errors, and notices carry an `action` field (`subscribed`, `error`, `rate_limit`, …). Data events instead carry a `type` and a `data` object. Branch on whichever field is present. Mixed frames are handled gracefully — the acknowledgement grants every type your plan includes, so the rest of the subscription always goes through. ## Filters Filters are matched server-side with exact equality against the event's top-level data fields, before delivery — so you receive only the events you want. For `polymarket.trade`, the filterable fields are: `proxy_wallet``slug``condition_id``event_slug``outcome``outcome_index``side``asset``maker``taker``transaction_hash``order_hash` These are the fields you can filter on — `GET /event-types` is the authoritative source. To track several wallets or markets independently, open one subscription per target in the same `subscribe` frame. ## Build a subscription Pick your filters and copy the generated `subscribe` frame — or a ready-to-run Node or Python client — straight into your app. FiltersNo filters — all trades proxy\_walletslugcondition\_idoutcomeoutcome\_indexevent\_slugassetsidemakertakertransaction\_hashorder\_hash Add filter JSONNode.jsPython Copy ``` { "action": "subscribe", "subscriptions": [ { "type": "polymarket.trade", "filters": {} } ] } ``` [Next: Messages & lifecycle →](/docs/websockets/messages) --- # WebSockets · Messages & Lifecycle _Source: https://prediction.heisenberg.so/docs/websockets/messages_ WebSockets # Messages & lifecycle The shape of trade events, how to stop a stream, and how the connection stays healthy. ## Event messages Each event is a JSON frame carrying the event `type`, its `source`, the delivery `timestamp`, and a `data` object with the trade. Here is a live `polymarket.trade` event (long hashes abbreviated): JSON · server → client ``` { "type": "polymarket.trade", "source": "polymarket-trade-scraper", "timestamp": "2026-05-27T13:50:00.167247+00:00", "data": { "id": "0x8902f2…498832_0x31ba8c…a5aa09", "side": "BUY", "size": 11, "price": 0.53, "timestamp": "2026-05-27T13:49:52+00:00", "transaction_hash": "0x8902f299…d6d498832", "order_hash": "0x31ba8c8c…454aa5aa09", "block_number": 87514326, "condition_id": "0x9ad19824…2d7f2d9", "asset": "67025362…363793", "title": "Bitcoin Up or Down - May 27, 9:50AM-9:55AM ET", "slug": "btc-updown-5m-1779889800", "event_slug": "btc-updown-5m", "outcome": "Up", "outcome_index": 0, "icon": "https://polymarket-upload.s3…/BTC+fullsize.png", "maker": "0x55338c…d1b8220", "taker": "0x6833c0…1b5cfe1", "proxy_wallet": "0x55338c…d1b8220", "name": null, "pseudonym": null, "bio": null, "profile_image": null, "profile_image_optimized": null } } ``` Filterable fields The fields you can filter on (from `/event-types`). Every event also carries the additional non-filterable fields shown in the payload above. Field Type Description `proxy_wallet` string Trader's proxy wallet `slug` string Market slug `condition_id` string Market condition ID `event_slug` string Parent event slug `outcome` string Outcome traded (e.g. Up, No) `outcome_index` integer Index of the traded outcome `side` string Trade direction — BUY or SELL `asset` string Outcome token (asset) ID `maker` string Maker wallet address `taker` string Taker wallet address `transaction_hash` string On-chain transaction hash `order_hash` string On-chain order hash ## Unsubscribe Stop one or more streams by sending an `unsubscribe` frame with the `subscription_ids` returned when you subscribed. The server confirms with an `unsubscribed` acknowledgement. JSON · client → server ``` { "action": "unsubscribe", "subscription_ids": ["cede7755-c0a6-41b8-b316-ca4377dedb5d"] } ``` JSON · server → client ``` { "action": "unsubscribed", "subscription_ids": ["cede7755-c0a6-41b8-b316-ca4377dedb5d"] } ``` ## Connection lifecycle ### Heartbeat Connections are kept healthy by a built-in ping/pong heartbeat. Most WebSocket libraries respond to pings automatically, so there's nothing to implement — your stream stays alive as long as your client is connected. ### Reconnection Connections are long-lived. For a resilient client, reconnect automatically with exponential backoff and re-send your `subscribe` frames once reconnected — the standard pattern for any streaming integration. A close with code `4001` is simply a cue to reconnect to a fresh upstream feed, and deploys roll out with graceful connection draining so reconnects stay clean. You can confirm gateway health any time with `GET /health` (returns `200 OK`). The [SDK](/docs/sdk/streaming) does all of this for you. [Next: Errors & limits →](/docs/websockets/limits) --- # WebSockets · Errors & Limits _Source: https://prediction.heisenberg.so/docs/websockets/limits_ WebSockets # Errors & limits Streaming allowances by plan, and the in-band messages the gateway sends when something needs your attention. ## Rate limits & quotas Each plan includes streaming allowances sized for production workloads. A few simple practices keep your integration efficient and well within them: - •**Active subscriptions** — a single connection holds many subscriptions at once; your plan sets how many run concurrently. - •**Message rate** — events are delivered at your plan's throughput. If you reach it, the gateway sends a single `rate_limit` notice for that window and keeps your connection open. Filters keep your feed focused and comfortably within budget. - •**Subscribe in one frame** — open all your subscriptions in a single `subscribe` frame. It's the fastest way to start streaming and keeps your client tidy. - •**One connection is all you need** — a single connection carries every subscription, so there's rarely a reason to open more. JSON · server → client ``` { "action": "rate_limit", "message": "message rate limit reached" } ``` Scale up any time Your plan includes a streaming allowance that renews each billing period. Need more throughput or more concurrent subscriptions? Upgrade any time — see [Pricing & Plans](/docs/getting-started/pricing) for what each tier includes. ## Errors & notices The gateway always answers — any protocol issue comes back as a clear, in-band `error` message that names the relevant `types` and a human-readable `message`, so your client knows exactly what to do. For example, requesting a type your plan doesn't include yet: JSON · server → client ``` { "action": "error", "types": ["polymarket.does_not_exist"], "message": "unauthorized: polymarket.does_not_exist" } ``` Filtering on a non-filterable field: JSON · server → client ``` { "action": "error", "types": ["polymarket.trade"], "message": "non-filterable keys for polymarket.trade: not_a_real_field" } ``` Authentication is checked at the connection upgrade with a standard `401`, so only valid tokens stream. [Next: Examples →](/docs/websockets/examples) --- # WebSockets · Examples _Source: https://prediction.heisenberg.so/docs/websockets/examples_ WebSockets # Examples Minimal clients that connect, subscribe to one market, print each trade, and reconnect on `4001`. For a client that handles all of this for you, use the [SDK streaming client](/docs/sdk/streaming). Node.js (ws) JavaScript ``` import WebSocket from 'ws'; function connect() { const ws = new WebSocket('wss://ripple.heisenberg.so/ws', { headers: { Authorization: 'Bearer ' + process.env.HEISENBERG_TOKEN }, }); ws.on('open', () => { ws.send(JSON.stringify({ action: 'subscribe', subscriptions: [ { type: 'polymarket.trade', filters: { slug: 'btc-updown-5m-1779889800' } }, ], })); }); ws.on('message', (raw) => { const msg = JSON.parse(raw.toString()); if (msg.action === 'subscribed') { console.log('subscribed:', msg.subscriptions.map((s) => s.id)); } else if (msg.action === 'error' || msg.action === 'rate_limit') { console.warn(msg.action + ':', msg.message); } else if (msg.type === 'polymarket.trade') { const t = msg.data; console.log(t.side, t.size, '@', t.price, '·', t.slug); } }); // The ws library answers server pings automatically. ws.on('close', (code) => { if (code === 4001) setTimeout(connect, 1000); // upstream interrupted — reconnect + re-subscribe }); } connect(); ``` Python (websockets) Python ``` import asyncio, json, os import websockets async def main(): url = "wss://ripple.heisenberg.so/ws" headers = {"Authorization": f"Bearer {os.environ['HEISENBERG_TOKEN']}"} async with websockets.connect(url, additional_headers=headers) as ws: await ws.send(json.dumps({ "action": "subscribe", "subscriptions": [ {"type": "polymarket.trade", "filters": {"slug": "btc-updown-5m-1779889800"}}, ], })) async for raw in ws: msg = json.loads(raw) if "action" in msg: # subscribed / error / rate_limit print(msg) elif msg.get("type") == "polymarket.trade": t = msg["data"] print(t["side"], t["size"], "@", t["price"], "·", t["slug"]) asyncio.run(main()) ``` ## Need more streams? More event types are on the way. To request early access or a dedicated event type, reach us at [contact@heisenberg.so](mailto:contact@heisenberg.so). --- # Research Data _Source: https://prediction.heisenberg.so/docs/research-data_ # Research Data Deep historical archives and purpose-built training datasets for quantitative research, backtesting strategies, and machine learning on prediction markets. ## Historical Data ### Trade History Full trade-level data across Polymarket and Kalshi — timestamps, prices, volumes, wallet addresses, and direction. ### Orderbook Snapshots Depth-of-book captures at configurable intervals for liquidity analysis and market microstructure research. ### Market Lifecycle Complete market metadata from creation through resolution — outcomes, settlement, open/close dates. ### OHLCV Candlesticks Price and volume data bucketed at 1m, 5m, 15m, 1h, 4h, and 1d resolutions. ### Social Signals Historical social media mentions and sentiment scores tied to prediction market events. ### Wallet Profiles Point-in-time snapshots of wallet analytics, H-Scores, and performance metrics. ## Custom Training Data Purpose-built datasets for training ML models and fine-tuning LLMs on prediction market intelligence. ### Trader Behavior Patterns Labeled datasets of trading strategies, risk profiles, and performance outcomes across thousands of wallets. ### Market Resolution Signals Feature sets correlated with correct predictions — for training forecasting and signal detection models. ### Anomaly Detection Sets Labeled price jumps, wash trading patterns, and unusual activity for classifier training. ### RAG-Ready Knowledge Bases Pre-chunked, structured market data optimized for retrieval-augmented generation workflows. ## Delivery Formats ### JSON / JSONL Recommended Structured records for APIs, data agents, and LLM ingestion. ### CSV / Parquet Tabular format for Pandas, Spark, BigQuery, and analytical tools. ### API Access Paginated endpoints for programmatic bulk retrieval on demand. ## Get Access Research data packages are tailored to your specific use case. Reach out with your requirements and we'll put together a dataset that fits. [contact@heisenberg.so](mailto:contact@heisenberg.so) --- # Polymarket Markets _Source: https://prediction.heisenberg.so/docs/api-reference/polymarket-markets_ Polymarket # Markets Search markets on Polymarket using different filters including market\_slug, min\_volume, and etc. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters min\_volumestring Minimum trading volume filter Example: `"100"` condition\_idstring Ethereum condition ID for the market Example: `"0xeaff81adbcd9dcd88a73a41402cb4a6b87234213a6b3ecaa0441126cde6d5b7f"` market\_slugstring Market identifier or keyword search Example: `"bitcoin-up-or-down-january-17-3pm-et"` event\_slugstring Filter by event slug Example: `"bitcoin-up-or-down-january-17-3pm-et"` end\_date\_minstring Filter markets ending after this timestamp (inclusive) Example: `"1768467703"` end\_date\_maxstring Filter markets ending before this timestamp (inclusive) Example: `"1769213303"` closedstring Market status (false = open, true = closed) Example: `"True"` ## Response Fields Field Type Description `condition_id` String Ethereum condition ID for the market `question` String Market question/title `slug` String URL-friendly market identifier `event_slug` String URL-friendly event identifier `closed` Boolean Market status (false = open, true = closed) `volume_total` Float Total trading volume `start_date` String (ISO 8601) Market start timestamp `end_date` String (ISO 8601) Market end/resolution timestamp `close_date` String (ISO 8601) Market close timestamp `side_a_token_id` String Token ID of the first side of the market `side_b_token_id` String Token ID of the second side of the market `side_a_outcome` String Outcome of the first side of the market `side_b_outcome` String Outcome of the second side of the market `winning_outcome` String Winning outcome of the market ## Tips for Best Results - •Use `closed: "False"` to get only tradeable (open) markets - •Combine `min_volume` with `closed` to find liquid, active markets - •Use partial slugs for broad searches (e.g., "nba" finds all NBA-related markets) - •Increase `limit` to 200 for bulk data retrieval - •Use `offset` for pagination through large result sets - •The `has_more` field indicates if additional pages exist - •Use `end_date_min` and `end_date_max` with Unix timestamps (as strings) to filter by market end dates Markets cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 574, "params": { "min_volume": "100", "condition_id": "0xeaff81adbcd9dcd88a73a41402cb4a6b87234213a6b3ecaa0441126cde6d5b7f", "market_slug": "bitcoin-up-or-down-january-17-3pm-et", "event_slug": "bitcoin-up-or-down-january-17-3pm-et", "end_date_min": "1768467703", "end_date_max": "1769213303", "closed": "True" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "closed": "True", "condition_id": "0xeaff81adbcd9dcd88a73a41402cb4a6b87234213a6b3ecaa0441126cde6d5b7f", "end_date_max": "1769213303", "end_date_min": "1768467703", "event_slug": "bitcoin-up-or-down-january-17-3pm-et", "market_slug": "bitcoin-up-or-down-january-17-3pm-et", "min_volume": "100" }, "pagination": { "limit": 100, "offset": 0, "has_more": false }, "data": { "results": [ { "closed": true, "closed_date": "2026-01-17T22:07:24Z", "condition_id": "0xeaff81adbcd9dcd88a73a41402cb4a6b87234213a6b3ecaa0441126cde6d5b7f", "end_date": "2026-01-17T21:00:00Z", "event_slug": "bitcoin-up-or-down-january-17-3pm-et", "question": "Bitcoin Up or Down - January 17, 3PM ET", "side_a_outcome": "Up", "side_a_token_id": "54962395221233298907357564706944806093710338832907683007646483576474886134345", "side_b_outcome": "Down", "side_b_token_id": "99436386356623686771311452414494038846982778884699006473918967429453507432222", "slug": "bitcoin-up-or-down-january-17-3pm-et", "start_date": "2026-01-15T20:01:06.506385Z", "volume_total": 104456.760687, "winning_outcome": "Up" } ] } } ``` --- # Polymarket Trades _Source: https://prediction.heisenberg.so/docs/api-reference/polymarket-trades_ Polymarket # Trades Returns historical trade data from Polymarket with different filters such as trader's address and market slug. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters proxy\_walletstring Filter by wallet address Example: `"ALL"` condition\_idstring Ethereum condition ID for the market Example: `"ALL"` market\_slugstring Filter trades by specific market Example: `"bitcoin-up-or-down-january-9-10am-et"` start\_timestring Trades after this timestamp (inclusive) Example: `"1767973812"` end\_timestring Trades before this timestamp (inclusive) Example: `"1767973860"` ## Response Fields Field Type Description `id` String Unique trade identifier `condition_id` String Ethereum condition ID for the market `price` Float Price per share (0-1 range) `side` String Trade direction: "BUY" or "SELL" `size` Float Number of shares traded `timestamp` String (ISO 8601) Timestamp of trade execution `transaction_hash` String Ethereum transaction hash `slug` String Market identifier `outcome` String Trade outcome (e.g., "Yes", "No") `proxy_wallet` String Trader's wallet address ## Tips for Best Results - •Use Unix timestamps (as strings) for `start_time` and `end_time` filtering - •Combine `market_slug` and time filters for focused analysis - •Use pagination for large datasets to avoid timeouts - •Transaction hashes can be used to verify trades on-chain - •Combine multiple filters for sophisticated queries Trades cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 556, "params": { "proxy_wallet": "ALL", "condition_id": "ALL", "market_slug": "bitcoin-up-or-down-january-9-10am-et", "start_time": "1767973812", "end_time": "1767973860" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "condition_id": "ALL", "end_time": "1767973860", "market_slug": "bitcoin-up-or-down-january-9-10am-et", "proxy_wallet": "ALL", "start_time": "1767973812", "wallet_proxy": "ALL" }, "pagination": { "limit": 10, "offset": 0, "has_more": true }, "data": { "results": [ { "condition_id": "0x584654c869a3f1868f3ad1248e11ea988f3c4e332002839c6cac0e6db94485ee", "id": "0x19320a9cfc47d70e2ac56c25b3555a34f402484a236267a8c220fa060eba74c7_0x1e30835026c910cd5f676a504ce8c39666917f402dfe93bb46c19adf6b152c13", "outcome": "Down", "price": 0.001, "proxy_wallet": "0x11514fb5ef1e3fe110691243714fcf2182db1fed", "side": "BUY", "size": 225.23, "slug": "bitcoin-up-or-down-january-9-10am-et", "timestamp": "2026-01-09T15:51:00Z", "transaction_hash": "0x19320a9cfc47d70e2ac56c25b3555a34f402484a236267a8c220fa060eba74c7" }, { "condition_id": "0x584654c869a3f1868f3ad1248e11ea988f3c4e332002839c6cac0e6db94485ee", "id": "0x19320a9cfc47d70e2ac56c25b3555a34f402484a236267a8c220fa060eba74c7_0xb07225fa95a2b5dd0f15b3f41f07657d9eb9e928268d4e5ae9fdf7e178049ac7", "outcome": "Down", "price": 0.001, "proxy_wallet": "0x11514fb5ef1e3fe110691243714fcf2182db1fed", "side": "BUY", "size": 14.99, "slug": "bitcoin-up-or-down-january-9-10am-et", "timestamp": "2026-01-09T15:51:00Z", "transaction_hash": "0x19320a9cfc47d70e2ac56c25b3555a34f402484a236267a8c220fa060eba74c7" } ] } } ``` --- # Polymarket Candlesticks _Source: https://prediction.heisenberg.so/docs/api-reference/polymarket-candlesticks_ Polymarket # Candlesticks Retrieves past candlestick data for a token associated with a market given `token_id` across a specified time interval. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters token\_idstring Blockchain token identifier for the specific market outcome Example: `"58639447033085668146701215689433308999613524738987821507545529427932862502961"` intervalstring Interval of the candlestick. Possible values are `1m` `5m` `15m` `1h` `4h` `1d` `1w` . There are range limits for interval and the end\_time will be capped: `1m`: max range 7 days `5m`: max range 15 days `15m`: max range 30 days `1h`: max range 90 days `4h`: max range 180 days `1d`: max range 360 days `1w`: max range 360 days Example: `"1m"` start\_timestring Filter after this timestamp Example: `"1769219100"` end\_timestring Filter before this timestamp Example: `"1769508420"` ## Response Fields Field Type Description `candle_time` String (ISO 8601) Timestamp representing the start time of the candlestick interval `open` String (Decimal) Opening price for the interval `high` String (Decimal) Highest traded price during the interval `low` String (Decimal) Lowest traded price during the interval `close` String (Decimal) Closing price for the interval `mean` String (Decimal) Mean (average) traded price during the interval `volume` String (Decimal) Total traded volume during the interval `trade_count` Integer Number of trades executed during the interval `outcome` String Market outcome this candlestick represents (e.g., `Yes`, `No`) `condition_id` String Ethereum condition ID identifying the underlying market `token_id` String Blockchain token identifier for the specific market outcome `ask_open` String (Decimal) Opening ask price for the interval `ask_high` String (Decimal) Highest ask price during the interval `ask_low` String (Decimal) Lowest ask price during the interval `ask_close` String (Decimal) Closing ask price for the interval `bid_open` String (Decimal) Opening bid price for the interval `bid_high` String (Decimal) Highest bid traded price during the interval `bid_low` String (Decimal) Lowest bid price during the interval `bid_close` String (Decimal) Closing bid price for the interval `spread` String (Decimal) \\ null Bid-ask spread (ask\_close − bid\_close). `null` when either side is unavailable. ## Tips for Best Results - •Limit the duration with proper `start_time` and `end_time`. Use shorter intervals for shorter durations, such as `1m` or `5m` Candlesticks cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 568, "params": { "token_id": "58639447033085668146701215689433308999613524738987821507545529427932862502961", "interval": "1m", "start_time": "1769219100", "end_time": "1769508420" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "end_time": "1770083100", "interval": "4h", "start_time": "1769910300", "token_id": "78633590736077251574794513664747155551297291244492840448622550955320930591622" }, "pagination": { "limit": 200, "offset": 0, "has_more": false }, "data": { "results": [ { "ask_close": "0.5100", "ask_high": "0.9900", "ask_low": "0.5100", "ask_open": "0.9900", "bid_close": "0.5000", "bid_high": "0.5000", "bid_low": "0.0100", "bid_open": "0.0100", "candle_time": "2026-02-01T00:00:00Z", "close": "0.5100", "condition_id": "0x18b1c135d0a40c5894da9412e77311827d9caf16cf4cd6591b247a34730af919", "high": "0.5100", "low": "0.5000", "mean": "0.5033", "open": "0.5000", "outcome": "No", "spread": "0.0100", "token_id": "78633590736077251574794513664747155551297291244492840448622550955320930591622", "trade_count": 6, "volume": "135.97" }, { "ask_close": "0.5100", "ask_high": "0.9900", "ask_low": "0.5100", "ask_open": "0.9900", "bid_close": "0.5000", "bid_high": "0.5000", "bid_low": "0.0100", "bid_open": "0.0100", "candle_time": "2026-02-01T04:00:00Z", "close": "0.5100", "condition_id": "0x18b1c135d0a40c5894da9412e77311827d9caf16cf4cd6591b247a34730af919", "high": "0.5100", "low": "0.5000", "mean": "0.5038", "open": "0.5000", "outcome": "No", "spread": "0.0100", "token_id": "78633590736077251574794513664747155551297291244492840448622550955320930591622", "trade_count": 15, "volume": "1020.08" } ] }, "request_id": "" } ``` --- # Polymarket Price Jumps _Source: https://prediction.heisenberg.so/docs/api-reference/polymarket-price-jumps_ Polymarket # Price Jumps Detect significant price jumps on a Polymarket market by scanning candlestick data bucketed at a chosen resolution. Returns all candle-to-candle moves exceeding the configured threshold, sorted by magnitude. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters token\_idstring Token ID of the specific outcome. Use Polymarket Markets (574) to find it. Example: `"99787107393065498256888522570939526464960671564345515510320748534859284179297"` resolutionstring Candle bucket size. Options: 1m, 5m, 15m, 1h, 4h, 1d Example: `"15m"` min\_change\_pctstring Minimum absolute % price change to qualify as a jump Example: `"10"` lookback\_hoursstring Hours to scan back from now Example: `"24"` ## Response Fields Field Type Description `jump_time` String (ISO 8601) Timestamp of the candle where the jump occurred `condition_id` String Hex condition ID of the market `token_id` String Token ID of the outcome `outcome` String Outcome label `price_before` String (Decimal) Price at the start of the candle `price_after` String (Decimal) Price at the end of the candle `change_pct` String (Decimal) Percentage change (negative = price dropped) `direction` String `up` or `down` `volume` String (Decimal) Volume during the candle `trade_count` Integer Number of trades during the candle Price Jumps cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 596, "params": { "token_id": "99787107393065498256888522570939526464960671564345515510320748534859284179297", "resolution": "15m", "min_change_pct": "10", "lookback_hours": "24" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "lookback_hours": "24", "min_change_pct": "10", "resolution": "15m", "token_id": "99787107393065498256888522570939526464960671564345515510320748534859284179297" }, "pagination": { "limit": 10, "offset": 0, "has_more": false }, "data": { "results": [ { "change_pct": "-16.67", "condition_id": "0xbcacd5a055f5a9ced6f69f122216c073dd6987d08253fc07bbcc168fa5b81d55", "direction": "down", "jump_time": "2026-04-06T02:00:00Z", "outcome": "Yes", "price_after": "0.1500", "price_before": "0.1800", "token_id": "99787107393065498256888522570939526464960671564345515510320748534859284179297", "trade_count": 28, "volume": "7350.07" }, { "change_pct": "14.29", "condition_id": "0xbcacd5a055f5a9ced6f69f122216c073dd6987d08253fc07bbcc168fa5b81d55", "direction": "up", "jump_time": "2026-04-05T19:30:00Z", "outcome": "Yes", "price_after": "0.1600", "price_before": "0.1400", "token_id": "99787107393065498256888522570939526464960671564345515510320748534859284179297", "trade_count": 3, "volume": "264.35" } ] }, "request_id": "" } ``` --- # Polymarket Orderbook _Source: https://prediction.heisenberg.so/docs/api-reference/polymarket-orderbook_ Polymarket # Orderbook Gets past order book snapshots for a specific `token_id` during a chosen time range. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters token\_idstring Token ID of the associated Market. Example: `"69435545313357346912686520645149775930858973121193492847015767460308803044235"` start\_timestring Filter after this timestamp Example: `"1769902905868"` end\_timestring Filter before this timestamp Example: `"1770034843377"` ## Response Fields Field Type Description `timestamp` String (ISO 8601) Timestamp representing the time of the data `token_id` String Blockchain token identifier for the specific market outcome `asks` String (List) asks data `bids` String (List) bids data Orderbook cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 572, "params": { "token_id": "69435545313357346912686520645149775930858973121193492847015767460308803044235", "start_time": "1769902905868", "end_time": "1770034843377" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "end_time": "1770034843377", "start_time": "1769902905868", "token_id": "69435545313357346912686520645149775930858973121193492847015767460308803044235" }, "pagination": { "limit": 200, "offset": 0, "has_more": true }, "data": { "results": [ { "asks": "[{\"size\": \"60\", \"price\": \"0.99\"}, {\"size\": \"723.17\", \"price\": \"0.93\"}, {\"size\": \"12\", \"price\": \"0.91\"}]", "bids": "[{\"size\": \"60\", \"price\": \"0.01\"}, {\"size\": \"25\", \"price\": \"0.02\"}, {\"size\": \"5.63\", \"price\": \"0.03\"}, {\"size\": \"12\", \"price\": \"0.09\"}, {\"size\": \"12\", \"price\": \"0.19\"}, {\"size\": \"200\", \"price\": \"0.28\"}, {\"size\": \"29.48\", \"price\": \"0.29\"}]", "timestamp": "2026-02-02T12:01:20.885Z", "token_id": "69435545313357346912686520645149775930858973121193492847015767460308803044235" }, { "asks": "[{\"size\": \"60\", \"price\": \"0.99\"}, {\"size\": \"5\", \"price\": \"0.98\"}, {\"size\": \"723.17\", \"price\": \"0.93\"}, {\"size\": \"12\", \"price\": \"0.91\"}]", "bids": "[{\"size\": \"60\", \"price\": \"0.01\"}, {\"size\": \"30\", \"price\": \"0.02\"}, {\"size\": \"5.63\", \"price\": \"0.03\"}, {\"size\": \"12\", \"price\": \"0.09\"}, {\"size\": \"12\", \"price\": \"0.19\"}, {\"size\": \"200\", \"price\": \"0.28\"}, {\"size\": \"29.48\", \"price\": \"0.29\"}]", "timestamp": "2026-02-02T10:29:08.324Z", "token_id": "69435545313357346912686520645149775930858973121193492847015767460308803044235" } ] } } ``` --- # Polymarket PnL _Source: https://prediction.heisenberg.so/docs/api-reference/polymarket-pnl_ Polymarket # PnL Retrieves realized profit and loss (PnL) for a given wallet address over a specified time range and aggregation interval. You may optionally filter results to a single market using `condition_id`. Unlike Polymarket’s dashboard, which displays unrealized PnL, this API reports **realized gains only**, calculated from confirmed sell transactions or fully settled (closed) markets. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters granularitystring Aggregation interval. Possible values are `1d` `3d` `1w` `1m` `all` Example: `"1d"` walletstring Wallet Id. Example: `"0x8e433d051bfb5cc6a1f7e5a0452029b7ffb4a3cd"` start\_timestring Filter after this timestamp Example: `"2026-02-10"` end\_timestring Filter before this timestamp Example: `"2026-02-28"` ## Response Fields Field Type Description `date` String (ISO 8601) Date for which the performance metrics are aggregated `proxy_wallet` String Wallet address for which performance is calculated `invested` String (Decimal) Total amount invested during the period `pnl` String (Decimal) Net profit and loss for the period (negative values indicate a loss) `trades` Integer Total number of trades executed during the period `wins` Integer Number of profitable trades `losses` Integer Number of losing trades `win_rate` String (Decimal) Proportion of winning trades (0–1 or percentage, depending on client interpretation) PnL cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 569, "params": { "granularity": "1d", "wallet": "0x8e433d051bfb5cc6a1f7e5a0452029b7ffb4a3cd", "start_time": "2026-02-10", "end_time": "2026-02-28" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "condition_id": "ALL", "end_time": "2026-02-28", "granularity": "1d", "start_time": "2026-02-10", "wallet": "0x8e433d051bfb5cc6a1f7e5a0452029b7ffb4a3cd" }, "pagination": { "limit": 200, "offset": 0, "has_more": true }, "data": { "results": [ { "date": "2026-02-19T00:00:00Z", "invested": "830494.18", "losses": 0, "pnl": "0.00", "proxy_wallet": "0x8e433d051bfb5cc6a1f7e5a0452029b7ffb4a3cd", "trades": 3342, "win_rate": "0.00", "wins": 0 }, { "date": "2026-02-20T00:00:00Z", "invested": "241245.70", "losses": 18, "pnl": "-302209.22", "proxy_wallet": "0x8e433d051bfb5cc6a1f7e5a0452029b7ffb4a3cd", "trades": 406, "win_rate": "0.49", "wins": 2 } ] } } ``` --- # Polymarket PnL Leaderboard _Source: https://prediction.heisenberg.so/docs/api-reference/polymarket-pnl-leaderboard_ Polymarket # PnL Leaderboard **Leaderboard API** POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters wallet\_addressstring Wallet address filter. Use `"ALL"` to return all wallets, or provide a specific address to filter results to that wallet. Example: `"ALL"` leaderboard\_periodstring Leaderboard time window. Allowed values: `1d`, `3d`, `7d`, `30d`. Each period has an independent ranking. Example: `"1d"` ## Response Fields Field Type Description `rank` Integer Leaderboard rank within the selected period `address` String Wallet address `total_pnl` String (Decimal) Total profit and loss for the period (negative values indicate a loss) `roi` String (Decimal) Return on investment `win_rate` String (Decimal) Win percentage (0–1) `sharpe_ratio` String (Decimal) Risk-adjusted performance metric `total_volume` String (Decimal) Total trading volume `markets_traded` Integer Number of unique markets traded `total_trades` Integer Total number of trades executed PnL Leaderboard cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 579, "params": { "wallet_address": "ALL", "leaderboard_period": "1d" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "leaderboard_period": "1d", "max_sharpe_ratio": "-1.0", "max_total_pnl": "-1.0", "max_win_rate": "-1.0", "min_sharpe_ratio": "-1.0", "min_total_pnl": "-1.0", "min_win_rate": "-1.0", "wallet_address": "ALL" }, "pagination": { "limit": 50, "offset": 0, "has_more": true }, "data": { "results": [ { "address": "0x0720803c7cb0d0c5a928787b3b7ea148c6831cdb", "markets_traded": 1, "rank": 1, "roi": "0.414952", "sharpe_ratio": null, "total_pnl": "1494121.7168", "total_trades": 69, "total_volume": "3600711.99", "win_rate": "1.0000" }, { "address": "0xe90bec87d9ef430f27f9dcfe72c34b76967d5da2", "markets_traded": 50, "rank": 2, "roi": "0.355880", "sharpe_ratio": "0.2847", "total_pnl": "1092294.3287", "total_trades": 1829, "total_volume": "3069274.68", "win_rate": "0.6290" } ] } } ``` --- # Wallet Stats All Time _Source: https://prediction.heisenberg.so/docs/api-reference/wallet-stats-all-time_ Polymarket # Wallet Stats All Time **Wallet Stats All Time on Our data (\\~9mo)** POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters wallet\_addressstring Wallet address filter. This is mandetory. Example: `"0x6ac5bb06a9eb05641fd5e82640268b92f3ab4b6e"` ## Response Fields Field Type Description `proxy_wallet` String Proxy wallet address associated with the trading activity `total_trades` Integer Total number of trades executed `avg_trade_size` String (Decimal) Average size of each trade `avg_pnl_per_trade` String (Decimal) Average profit or loss generated per trade `total_invested` String (Decimal) Total capital invested across all trades `total_pnl` String (Decimal) Total profit and loss across all trades (negative values indicate a loss) `roi_pct` String (Decimal) Return on investment expressed as a percentage `last_updated` String (ISO 8601 Timestamp) Timestamp indicating when the metrics were last updated Wallet Stats All Time cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 586, "params": { "wallet_address": "0x6ac5bb06a9eb05641fd5e82640268b92f3ab4b6e" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "wallet_address": "0x6ac5bb06a9eb05641fd5e82640268b92f3ab4b6e" }, "pagination": { "limit": 50, "offset": 0, "has_more": false }, "data": { "results": [ { "avg_pnl_per_trade": "2.26", "avg_trade_size": "122.24", "last_updated": "2026-03-14T00:00:00Z", "proxy_wallet": "0x6ac5bb06a9eb05641fd5e82640268b92f3ab4b6e", "roi_pct": "1.85", "total_invested": "22785473.35", "total_pnl": "420395.44", "total_trades": 186403 } ] } } ``` --- # Heisenberg Leaderboard _Source: https://prediction.heisenberg.so/docs/api-reference/heisenberg-leaderboard_ Polymarket # Heisenberg Leaderboard **Heisenberg Leaderboard API** POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters min\_win\_rate\_15dstring Minimum 15-day win rate (0–1) Example: `"0.45"` max\_win\_rate\_15dstring Maximum 15-day win rate (0–1) Example: `"0.95"` min\_roi\_15dstring Minimum 15-day ROI Example: `"0"` min\_total\_trades\_15dstring Minimum trades in 15 days Example: `"50"` max\_total\_trades\_15dstring Maximum trades in 15 days Example: `"100000"` min\_pnl\_15dstring Minimum realized PnL in USD over 15 days. Default: `"5000"` Example: `"5000"` sort\_bystring Sort metric. Default: `h_score`. Options: `h_score`, `roi`, `pnl`, `win_rate`, `trades`, `sharpe` Example: `"h_score"` Heisenberg Leaderboard cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 584, "params": { "min_win_rate_15d": "0.45", "max_win_rate_15d": "0.95", "min_roi_15d": "0", "min_total_trades_15d": "50", "max_total_trades_15d": "100000", "min_pnl_15d": "5000", "sort_by": "h_score" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` --- # Wallet 360 _Source: https://prediction.heisenberg.so/docs/api-reference/wallet-360_ Polymarket # Wallet 360 **Heisenberg AI Extensive Wallet Profile** POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters proxy\_walletstring Filter by wallet address. Required field. Example: `"0x204f72f35326db932158cba6adff0b9a1da95e14"` window\_daysstring The duration that the metrics are calculated over. Possible values are `"1"`, `"3"`, `"7"`, and `"15"`. Required field. Example: `"3"` Wallet 360 cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 581, "params": { "proxy_wallet": "0x204f72f35326db932158cba6adff0b9a1da95e14", "window_days": "3" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "proxy_wallet": "0x204f72f35326db932158cba6adff0b9a1da95e14", "window_days": "3" }, "pagination": { "limit": 100, "offset": 0, "has_more": true }, "data": { "results": [ { "annualized_return": 4.7138, "avg_position_size": 2379.96, "best_trade": 75126.54, "calculation_window_days": 3, "calmar_ratio": null, "category_diversity_score": 1.6501, "coefficient_of_variation": 3.9035, "combined_risk_score": 10, "curve_smoothness": 0.0292, "date": "2026-03-15T00:00:00Z", "date_range_end": "2026-03-15T00:00:00Z", "date_range_start": "2026-03-13T00:00:00Z", "days_active": 3, "dominant_market_id": "0x42a016b0a4bdf4de840334551b04bda95fcf02e4626c60bb49e3b1f1530067a3", "dominant_market_pnl": -68490.68, "drawdown_frequency": 0, "edge_decay": null, "equity_curve_pattern": "volatile", "flagged_metrics": "{position_size_volatility}", "gain_to_pain_ratio": 100, "last_active": "2026-03-15T23:59:59.999999Z", "losing_trades": 2086, "market_concentration_ratio": 0.029, "markets_traded": 3146, "max_drawdown": 0, "max_position_pct": 0.3048, "num_markets_traded": 3146, "perfect_entry_count": 1204, "perfect_exit_count": 0, "perfect_timing_flag": false, "perfect_timing_score": 0.2258, "performance_by_category": "W3sicG5sIjogMTYxNzE3LjY4LCAidHJhZGVzIjogNjQwMCwgImNhdGVnb3J5IjogIk90aGVyIn0sIHsicG5sIjogNTgzMDguNTgsICJ0cmFkZXMiOiAyODUsICJjYXRlZ29yeSI6ICJXb3JsZCBFdmVudHMifSwgeyJwbmwiOiA0NzI1OS45OSwgInRyYWRlcyI6IDkzNSwgImNhdGVnb3J5IjogIlNwb3J0cyJ9LCB7InBubCI6IDIyNzk5LjEyLCAidHJhZGVzIjogODIsICJjYXRlZ29yeSI6ICJTY2llbmNlICYgVGVjaCJ9XQ==", "performance_trend": "improving", "position_size_consistency": 0, "position_size_volatility_flag": true, "profit_factor": 1.0972, "proxy_wallet": "0x204f72f35326db932158cba6adff0b9a1da95e14", "recovery_time_avg": 0, "risk_level": "LOW", "roi": 3.8743, "sharpe_ratio": 50, "similar_wallets_count": 0, "single_market_dependence_flag": false, "sortino_ratio": null, "statistical_confidence": 0.9966, "stddev_position_size": 4645.09, "suspicious_timing_trades": 0, "suspicious_win_rate_flag": false, "sybil_risk_flag": false, "sybil_risk_score": 0, "timing_anomaly_flag": false, "timing_hit_rate": 0, "timing_z_score": 0.61, "total_closed_positions": 2666, "total_invested": 7487360.92, "total_pnl": 290085.37, "total_timed_trades": 85719, "total_trades": 85719, "trade_size_stdev": 418.9442, "trade_timing_correlation_max": 0, "ulcer_index": 0, "win_rate": 0.522, "win_rate_last_30d": 0.5133, "win_rate_z_score": -5.37, "winning_trades": 2278, "worst_trade": -83113.9 }, { "annualized_return": -8.6915, "avg_position_size": 2045.27, "best_trade": 51771.41, "calculation_window_days": 3, "calmar_ratio": -86.6618, "category_diversity_score": 0.6255, "coefficient_of_variation": 4.0603, "combined_risk_score": 10, "curve_smoothness": 0.1176, "date": "2026-03-14T00:00:00Z", "date_range_end": "2026-03-14T00:00:00Z", "date_range_start": "2026-03-12T00:00:00Z", "days_active": 3, "dominant_market_id": "0x09eb95f347c8ca17d639371297175ed15f397c531e8ef13286382cda2a2595d1", "dominant_market_pnl": -178633.03, "drawdown_frequency": 0.3333, "edge_decay": null, "equity_curve_pattern": "volatile", "flagged_metrics": "{position_size_volatility}", "gain_to_pain_ratio": -0.776, "last_active": "2026-03-14T23:59:59.999999Z", "losing_trades": 1452, "market_concentration_ratio": 0.0507, "markets_traded": 2704, "max_drawdown": 0.1003, "max_position_pct": 0.4194, "num_markets_traded": 2704, "perfect_entry_count": 772, "perfect_exit_count": 0, "perfect_timing_flag": false, "perfect_timing_score": 0.172, "performance_by_category": "W3sicG5sIjogMjI3MzMuMjIsICJ0cmFkZXMiOiA1NiwgImNhdGVnb3J5IjogIlNjaWVuY2UgJiBUZWNoIn0sIHsicG5sIjogMTY5MzcuNDYsICJ0cmFkZXMiOiAyMTMsICJjYXRlZ29yeSI6ICJXb3JsZCBFdmVudHMifSwgeyJwbmwiOiAtODU5Mi43OSwgInRyYWRlcyI6IDUzODMsICJjYXRlZ29yeSI6ICJPdGhlciJ9LCB7InBubCI6IC00MjYxNTQuMzgsICJ0cmFkZXMiOiA4NjMsICJjYXRlZ29yeSI6ICJTcG9ydHMifV0=", "performance_trend": "improving", "position_size_consistency": 0, "position_size_volatility_flag": true, "profit_factor": 0.8539, "proxy_wallet": "0x204f72f35326db932158cba6adff0b9a1da95e14", "recovery_time_avg": 0, "risk_level": "LOW", "roi": -7.1437, "sharpe_ratio": -8.2487, "similar_wallets_count": 0, "single_market_dependence_flag": false, "sortino_ratio": -7.4996, "statistical_confidence": 0.9963, "stddev_position_size": 4447.27, "suspicious_timing_trades": 0, "suspicious_win_rate_flag": false, "sybil_risk_flag": false, "sybil_risk_score": 0, "timing_anomaly_flag": false, "timing_hit_rate": 0, "timing_z_score": 0.53, "total_closed_positions": 2244, "total_invested": 5530399.22, "total_pnl": -395076.48, "total_timed_trades": 64006, "total_trades": 72579, "trade_size_stdev": 350.6233, "trade_timing_correlation_max": 0, "ulcer_index": 5.7904, "win_rate": 0.5131, "win_rate_last_30d": 0.5118, "win_rate_z_score": -5.7, "winning_trades": 1530, "worst_trade": -178633.03 } ] } } ``` --- # Polymarket Market 360 _Source: https://prediction.heisenberg.so/docs/api-reference/polymarket-market-360_ Polymarket # Market 360 **Market Quality & Structure Endpoint** POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters condition\_idstring Ethereum condition ID for the market. This is optional. If you don't pass it, you get insights about all markets ranked by current\_volume\_24h in desc order. Example: `"ALL"` min\_volume\_24hstring Minimum 24-hour trading volume required for a market to be included. Use this to remove low-activity or noise markets. Example: `"0"` min\_liquidity\_percentilestring Minimum liquidity percentile relative to all active markets. Higher values indicate deeper books and better exit quality. Example: `"0"` volume\_trendstring Filters markets by recent activity momentum. Allowed values: `Spiking`, `Normal`, `Declining`, `Dying Interest`, `No Trades`, `ALL`. Example: `"ALL"` min\_top1\_wallet\_pctstring Minimum percentage of total exposure controlled by the largest wallet. Higher values may indicate whale dominance and potential fragility. Example: `"0"` max\_unique\_traders\_7dstring Maximum number of unique traders over the last 7 days. Useful for detecting low-participation or weak-consensus markets. Example: `"0"` Market 360 cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 575, "params": { "condition_id": "ALL", "min_volume_24h": "0", "min_liquidity_percentile": "0", "volume_trend": "ALL", "min_top1_wallet_pct": "0", "max_unique_traders_7d": "0" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "condition_id": "ALL", "max_unique_traders_7d": "0", "min_liquidity_percentile": "0", "min_top1_wallet_pct": "0", "min_volume_24h": "0", "volume_trend": "ALL" }, "pagination": { "limit": 200, "offset": 0, "has_more": true }, "data": { "results": [ { "condition_id": "0x24fb7c2d95c93a68018e6c4a90d88043bb67d32fd1454924cef8ebdd550228f3", "created_at": "2026-02-09T16:53:53.025942Z", "current_volume_24h": "44646247.155082", "current_volume_7d": "116971972.905561", "end_date": "2026-03-31T00:00:00Z", "liquidity_percentile": "100.00", "liquidity_risk_flag": false, "liquidity_tier": "Top 5%", "market_active": true, "market_closed": false, "net_pnl": "102441.064396", "no_avg_pnl": "-13.643443", "peak_hour_trades": 391, "profit_loss_ratio": "2.43", "question": "Will Israel launch a major ground offensive in Lebanon by March 31?", "slug": "will-israel-launch-a-major-ground-offensive-in-lebanon-by-march-31", "snapshot_time": "2026-03-25T18:00:00.010272Z", "squeeze_risk_flag": false, "top10_wallet_pct": "65.45", "top1_wallet_pct": "18.28", "top3_wallet_pct": "36.24", "trade_concentration_flag": false, "trades_per_hour_avg": "213.08", "unique_traders_7d": 4941, "updated_at": "2026-03-25T18:00:00.010272Z", "volume_collapse_risk_flag": false, "volume_ratio_24h_to_7d": "267.18", "volume_trend": "Spiking", "whale_control_flag": false, "winning_side": "Yes", "yes_avg_pnl": "44.593246" } ] }, "request_id": "" } ``` --- # Hyperliquid Wallet Trades _Source: https://prediction.heisenberg.so/docs/api-reference/hyperliquid-wallet-trades_ Hyperliquid # Wallet Trades Returns Hyperliquid trades in which a given address is the buyer or seller. Each row is annotated with the queried address's role (`trade_type`), the `counterparty` on the other side, and the matched `address`. Filter by coin, market type, and time range. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters addressstring Wallet address to match against both buyer and seller. Lower-cased before matching. Required. Example: `"0x5a7581618829f377a16be2338eabdd03fece0eaf"` symbolstring Coin ticker filter. `ALL` returns every coin. Example: `"ALL"` market\_typestring Market type filter: `perp`, `spot`, or `outcome`. `ALL` returns every type. Example: `"ALL"` start\_timestring Trades at or after this time, in seconds. The sentinel `1600000000` disables the lower bound. Example: `"1600000000"` end\_timestring Trades at or before this time, in seconds. The sentinel `2200000000` disables the upper bound. Example: `"2200000000"` ## Response Fields Field Type Description `tid` Integer Trade identifier `symbol` String Coin ticker `side` String Aggressor side: `B` (taker buy) or `A` (taker sell) `price` Number Execution price `size` Number Trade size in base units `trade_time` String (ISO 8601) Execution time `hash` String Transaction hash `buyer` String Buyer address `seller` String Seller address `is_liquidation` Boolean Whether the trade was a liquidation `market_type` String Market type (`perp` / `spot` / `outcome`) `trade_type` String The queried address's role: `buyer` or `seller` `counterparty` String The other party to the trade `address` String The matched (queried) address, lower-cased Wallet Trades cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 612, "params": { "address": "0x5a7581618829f377a16be2338eabdd03fece0eaf", "symbol": "ALL", "market_type": "ALL", "start_time": "1600000000", "end_time": "2200000000" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "address": "0x5a7581618829f377a16be2338eabdd03fece0eaf", "symbol": "ALL", "market_type": "ALL", "start_time": "1600000000", "end_time": "2200000000" }, "pagination": { "limit": 50, "offset": 0, "has_more": false }, "data": { "results": [ { "tid": 563178213904701, "symbol": "BTC", "side": "B", "price": 78170, "size": 0.00217, "trade_time": "2026-05-17T18:53:55.967000Z", "hash": "0xed931b90908e03bdef0c043b9fa8150202f700762b81228f915bc6e34f81dda8", "buyer": "0x5a7581618829f377a16be2338eabdd03fece0eaf", "seller": "0xb668858ff53322d5511651a2cd92391eb5d60ee3", "is_liquidation": false, "market_type": "perp", "trade_type": "buyer", "counterparty": "0xb668858ff53322d5511651a2cd92391eb5d60ee3", "address": "0x5a7581618829f377a16be2338eabdd03fece0eaf" } ] } } ``` --- # Hyperliquid Market Trades _Source: https://prediction.heisenberg.so/docs/api-reference/hyperliquid-market-trades_ Hyperliquid # Market Trades Returns the Hyperliquid trade feed filtered by coin, market type, and optional buyer and/or seller address. Market type is always applied. When `buyer`, `seller`, and `symbol` are all `ALL`, the query returns the most recent 12 hours of trades regardless of `start_time` / `end_time`. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters symbolstring Coin ticker filter. `ALL` returns every coin. Example: `"ETH"` market\_typestring Market type: `perp`, `spot`, or `outcome`. Always applied — there is no `ALL` bypass, so a value of `ALL` matches no rows. Required. Example: `"perp"` buyerstring Buyer address filter. Lower-cased before matching. `ALL` returns every buyer. Example: `"ALL"` sellerstring Seller address filter. Lower-cased before matching. `ALL` returns every seller. Example: `"ALL"` start\_timestring Trades at or after this time, in seconds. The sentinel `1600000000` disables the lower bound. Example: `"1600000000"` end\_timestring Trades at or before this time, in seconds. The sentinel `2200000000` disables the upper bound. Example: `"2200000000"` ## Response Fields Field Type Description `tid` Integer Trade identifier `symbol` String Coin ticker `side` String Aggressor side: `B` (taker buy) or `A` (taker sell) `price` Number Execution price `size` Number Trade size in base units `trade_time` String (ISO 8601) Execution time `hash` String Transaction hash `buyer` String Buyer address `seller` String Seller address `is_liquidation` Boolean Whether the trade was a liquidation `market_type` String Market type (`perp` / `spot` / `outcome`) Market Trades cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 613, "params": { "symbol": "ETH", "market_type": "perp", "buyer": "ALL", "seller": "ALL", "start_time": "1600000000", "end_time": "2200000000" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "symbol": "ETH", "market_type": "perp", "buyer": "ALL", "seller": "ALL", "start_time": "1600000000", "end_time": "2200000000" }, "pagination": { "limit": 50, "offset": 0, "has_more": false }, "data": { "results": [ { "tid": 365738602585856, "symbol": "ETH", "side": "A", "price": 2185.6, "size": 0.05, "trade_time": "2026-05-17T18:53:55.967000Z", "hash": "0x948051c3b082fb2395fa043b9fa8150204f700a94b8619f53848fd166f86d50e", "buyer": "0x31dea2516beee92135b96f464eeec3cf292a13f2", "seller": "0xaf8c393fd40c20accef9fa691d43400ebcfcc9ae", "is_liquidation": false, "market_type": "perp" }, { "tid": 980367930467703, "symbol": "ETH", "side": "A", "price": 2185.6, "size": 0.01, "trade_time": "2026-05-17T18:53:55.967000Z", "hash": "0x948051c3b082fb2395fa043b9fa8150204f700a94b8619f53848fd166f86d50e", "buyer": "0x492322b1fca1ab301a103b716a243b20cb3001aa", "seller": "0xaf8c393fd40c20accef9fa691d43400ebcfcc9ae", "is_liquidation": false, "market_type": "perp" } ] } } ``` --- # Hyperliquid Perpetual Markets _Source: https://prediction.heisenberg.so/docs/api-reference/hyperliquid-perpetual-markets_ Hyperliquid # Perpetual Markets Returns Hyperliquid perpetual market definitions and live context from `hyperliquid.hl_perp_market` — leverage limits, funding, open interest, and current prices. Filter by market name. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters namestring Perpetual market name (coin). `ALL` returns every perpetual market. Example: `"ALL"` ## Response Fields Field Type Description `name` String Perpetual market name (coin) `sz_decimals` Integer Size decimal precision `max_leverage` Integer Maximum allowed leverage `only_isolated` Boolean Whether only isolated margin is permitted `funding` Number Current hourly funding rate `open_interest` Number Open interest, in base units `prev_day_px` Number Mark price 24h ago `day_ntl_vlm` Number 24h notional (USD) volume `premium` Number Current premium `oracle_px` Number Oracle price `mark_px` Number Mark price `mid_px` Number Mid price `dex` String Builder-deployed DEX identifier; empty for the main perp dex Perpetual Markets cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 616, "params": { "name": "ALL" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "name": "ALL" }, "pagination": { "limit": 50, "offset": 0, "has_more": false }, "data": { "results": [ { "name": "0G", "sz_decimals": 0, "max_leverage": 3, "only_isolated": false, "funding": -0.0000346116, "open_interest": 1591008, "prev_day_px": 0.20441, "day_ntl_vlm": 218606.95021, "premium": -0.0002085308, "oracle_px": 0.211, "mark_px": 0.2105, "mid_px": 0.21075, "dex": "" }, { "name": "2Z", "sz_decimals": 0, "max_leverage": 3, "only_isolated": false, "funding": 0.0000125, "open_interest": 12323774, "prev_day_px": 0.065772, "day_ntl_vlm": 309957.282051, "premium": 0, "oracle_px": 0.06664, "mark_px": 0.066594, "mid_px": 0.066641, "dex": "" } ] } } ``` --- # Hyperliquid Spot Markets _Source: https://prediction.heisenberg.so/docs/api-reference/hyperliquid-spot-markets_ Hyperliquid # Spot Markets Returns Hyperliquid spot market definitions and live context from `hyperliquid.hl_spot_market` — token pair, canonical flag, and current prices/volume. Filter by pair identifier. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters coinstring Spot market pair identifier. Canonical pair uses `BASE/QUOTE` (only `PURR/USDC`); others use `@` (e.g. `@107` = HYPE/USDC). `ALL` returns every spot market. Example: `"ALL"` ## Response Fields Field Type Description `coin` String Spot market pair identifier (`BASE/QUOTE` for the canonical pair, otherwise `@`) `index` Integer Spot market index `base_token` String Base token symbol `quote_token` String Quote token symbol `is_canonical` Boolean Whether this is the canonical market for the pair `prev_day_px` Number Mark price 24h ago `mark_px` Number Mark price `mid_px` Number Mid price `day_ntl_vlm` Number 24h notional (USD) volume `day_base_vlm` Number 24h base-token volume Spot Markets cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 617, "params": { "coin": "ALL" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "coin": "@107" }, "pagination": { "limit": 50, "offset": 0, "has_more": false }, "data": { "results": [ { "coin": "@107", "index": 107, "base_token": "HYPE", "quote_token": "USDC", "is_canonical": false, "prev_day_px": 64.717, "mark_px": 65.544, "mid_px": 65.5525, "day_ntl_vlm": 76912970.31807004, "day_base_vlm": 1204106.729999999 } ] } } ``` --- # Hyperliquid Outcome Markets _Source: https://prediction.heisenberg.so/docs/api-reference/hyperliquid-outcome-markets_ Hyperliquid # Outcome Markets Returns Hyperliquid outcome (binary) market definitions from `hyperliquid.hl_outcome_market`. Filter by a coin that appears on either the YES or NO leg of a market. When a `coin` is supplied, each row is annotated with the matched leg (`side`), the matched `coin`, and the opposite leg (`coin_counterparty`). POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters coinstring Coin (asset) that appears as the YES or NO leg of a market. `ALL` returns every outcome market. Example: `"ALL"` ## Response Fields Field Type Description `outcome_id` Integer Outcome market identifier `name` String Market name `description` String Pipe-encoded market metadata (\`class:...\\ underlying:...\\ expiry:...\\ targetPrice:...\\ period:...\`) `underlying` String \\ null Underlying asset (e.g. `BTC`) `expiry` String \\ null Expiry timestamp, `YYYYMMDD-HHMM` `target_price` Number \\ null Target/strike price `period` String \\ null Recurrence period (e.g. `1d`) `market_class` String \\ null Market class (e.g. `priceBinary`) `yes_coin` String Asset representing the YES leg `no_coin` String Asset representing the NO leg `yes_asset_id` Integer Numeric asset id of the YES leg `no_asset_id` Integer Numeric asset id of the NO leg `side` String \\ null Which leg the queried `coin` matched: `yes` or `no`. `null` when `coin` is `ALL`. `coin` String \\ null The matched coin. `null` when `coin` is `ALL`. `coin_counterparty` String \\ null The opposite leg's coin. `null` when `coin` is `ALL`. Outcome Markets cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 615, "params": { "coin": "ALL" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "coin": "#350" }, "pagination": { "limit": 50, "offset": 0, "has_more": false }, "data": { "results": [ { "outcome_id": 35, "name": "Recurring", "description": "class:priceBinary|underlying:BTC|expiry:20260514-0600|targetPrice:80983|period:1d", "underlying": "BTC", "expiry": "20260514-0600", "target_price": 80983, "period": "1d", "market_class": "priceBinary", "yes_coin": "#350", "no_coin": "#351", "yes_asset_id": 100000350, "no_asset_id": 100000351, "side": "yes", "coin": "#350", "coin_counterparty": "#351" } ] } } ``` --- # Kalshi Markets _Source: https://prediction.heisenberg.so/docs/api-reference/kalshi-markets_ Kalshi # Markets Search markets on Kalshi using different filters including ticker, status, volume, and etc. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters tickerstring Value of market ticker. This is an exact match. Example: `"KXSOL15M-26MAR180800-00"` event\_tickerstring event ticker Example: `"KXSOL15M-26MAR180800"` titlestring Market question describing the event and outcome being traded Example: `"SOL price"` statusstring Current market status (e.g., `active`, `finalized`) Example: `"finalized"` close\_time\_minstring Filter markets in which the close time is after this timestamp (inclusive). Example: `"1773589812"` close\_time\_maxstring Filter markets in which the close time is before this timestamp (inclusive). Example: `"1774021812"` ## Response Fields Field Type Description `close_time` String (ISO 8601) Timestamp when the market was closed to trading `created_time` String (ISO 8601) Timestamp when the market was created `event_ticker` String event ticker `expiration_time` String (ISO 8601) Timestamp when the market expires and is no longer valid `last_price` Integer Last traded price of the market `open_time` String (ISO 8601) Timestamp when the market opened for trading `status` String Current market status (e.g., `active`, `finalized`) `ticker` String Ticker for this specific market `title` String Market question describing the event and outcome being traded `volume` Integer Total trading volume for the market `volume_24h` Integer Trading volume in the last 24 hours `result` String Final result (outcome) of this market Markets cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 565, "params": { "ticker": "KXSOL15M-26MAR180800-00", "event_ticker": "KXSOL15M-26MAR180800", "title": "SOL price", "status": "finalized", "close_time_min": "1773589812", "close_time_max": "1774021812" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "close_time_max": "1774021812", "close_time_min": "1773589812", "event_ticker": "KXSOL15M-26MAR180800", "status": "finalized", "ticker": "KXSOL15M-26MAR180800-00", "title": "SOL price" }, "pagination": { "limit": 10, "offset": 0, "has_more": false }, "data": { "results": [ { "close_time": "2026-03-18T12:00:00Z", "created_time": "2026-03-18T00:01:21.613032Z", "event_ticker": "KXSOL15M-26MAR180800", "expiration_time": "2026-03-25T12:00:00Z", "last_price": 0.8, "open_time": "2026-03-18T11:45:00Z", "result": "no", "status": "finalized", "ticker": "KXSOL15M-26MAR180800-00", "title": "SOL price up in next 15 mins?", "volume": 4422, "volume_24h": 4422 } ] } } ``` --- # Kalshi Trades _Source: https://prediction.heisenberg.so/docs/api-reference/kalshi-trades_ Kalshi # Trades Search trades on Kalshi using different filters including ticker and created time. POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters tickerstring Ticker symbol identifying the market outcome traded Example: `"KXSOL15M-26MAR180730-30"` start\_timestring Filter trades in which the created time is after this timestamp (inclusive). Example: `"1773589812"` end\_timestring Filter trades in which the created time is before this timestamp (inclusive). Example: `"1774021812"` ## Response Fields Field Type Description `count` Integer Number of shares/contracts traded in this transaction `created_time` String (ISO 8601) Timestamp when the trade was executed `no_price` Integer Price of the **No** outcome at the time of the trade `taker_side` String Side taken by the taker in the trade (`yes` or `no`) `ticker` String Ticker symbol identifying the market outcome traded `trade_id` String (UUID) Unique identifier for the trade `yes_price` Integer Price of the **Yes** outcome at the time of the trade (typically in cents, 0–100) Trades cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 573, "params": { "ticker": "KXSOL15M-26MAR180730-30", "start_time": "1773589812", "end_time": "1774021812" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ``` 200Example response ``` { "timestamp": "", "params": { "end_time": "1774021812", "start_time": "1773589812", "ticker": "KXSOL15M-26MAR180730-30" }, "pagination": { "limit": 10, "offset": 0, "has_more": true }, "data": { "results": [ { "count": 9, "created_time": "2026-03-18T11:29:25.354888Z", "no_price": 99.9, "taker_side": "yes", "ticker": "KXSOL15M-26MAR180730-30", "trade_id": "cba52037-21c4-6b04-6544-a2be4124d98e", "yes_price": 0.1 }, { "count": 200, "created_time": "2026-03-18T11:29:23.814603Z", "no_price": 99.9, "taker_side": "no", "ticker": "KXSOL15M-26MAR180730-30", "trade_id": "4143238d-eb74-75c4-3607-d1b2ea1f0abc", "yes_price": 0.1 } ] } } ``` --- # Social Pulse _Source: https://prediction.heisenberg.so/docs/api-reference/social-pulse_ Social Intelligence # Social Pulse **Social Pulse** POST/v2/semantic/retrieve/parameterizedTry it ## Query Parameters keywordsstring Filter by keywords Example: `"{NHL,hockey,Stanley Cup}"` hours\_backstring Filter by hours back Example: `"12"` ## Top-Level Fields Field Type Description `timestamp` string Timestamp of the response (may be empty) `params` object Echo of the query parameters used `pagination` object Pagination metadata for the result set `data.results` array List of matching social media posts ## \`pagination\` Object Field Type Description `limit` integer Maximum number of results returned (default: `200`) `offset` integer Offset for paginated results `has_more` boolean Whether additional results are available beyond this page ## \`data.results\[\]\` — Individual Post Object Field Type Description `id` integer Unique identifier of the post `content` string Full text content of the tweet `username` string Twitter/X handle of the author `url` string Direct URL to the post on X (Twitter) `created_on` string (ISO 8601) Timestamp when the post was created `like_count` integer Number of likes on the post `retweet_count` integer Number of retweets `reply_count` integer Number of replies `quote_count` integer Number of quote tweets `tweet_count` integer Total tweet volume associated with the keyword cluster `acceleration` string Rate of growth in social activity for the keyword cluster `author_diversity_pct` string Percentage of unique authors contributing to the trend `pct_last_1h` string Percentage of total activity occurring in the last 1 hour `pct_last_6h` string Percentage of total activity occurring in the last 6 hours Social Pulse cURL ``` curl --request POST \ --url https://narrative.agent.heisenberg.so/api/v2/semantic/retrieve/parameterized \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "agent_id": 585, "params": { "keywords": "{NHL,hockey,Stanley Cup}", "hours_back": "12" }, "pagination": { "limit": 10, "offset": 0 }, "formatter_config": { "format_type": "raw" } }' ```