=============== LIBRARY RULES =============== From library maintainers: - Always include the X-API-Key header for authenticated endpoints - WebSocket auth must happen within 5 seconds via message, not query string - API keys are prefixed with rm_ - Each market has UP and DOWN tokens with separate orderbooks - Snapshots include both eventTimestamp and captureTimestamp for latency measurement ### Install WebSocket Dependencies Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Commands to install the necessary WebSocket library for Node.js environments. Includes options for npm and pnpm package managers. ```bash npm install ws # or: pnpm add ws # Types: npm install -D @types/ws ``` -------------------------------- ### Install Resolved Markets CLI Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/cli.md Installs the Resolved Markets CLI globally using npm. This command requires Node.js and npm to be installed on your system. ```bash npm install -g resolved-markets-cli ``` -------------------------------- ### GET /v1/markets/live Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Lists all currently active markets available on the platform. ```APIDOC ## GET /v1/markets/live ### Description Retrieves a list of all live markets, including their condition IDs, slugs, and associated token structures. ### Method GET ### Endpoint https://api.resolvedmarkets.com/v1/markets/live ### Response #### Success Response (200) - **markets** (array) - List of active market objects. #### Response Example { "markets": [ { "conditionId": "0x123", "slug": "example-market", "question": "Will it rain?", "category": "weather", "tokens": [{"tokenId": "1", "side": "UP"}] } ] } ``` -------------------------------- ### Install Resolved Markets MCP Server Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Command to globally install the Resolved Markets MCP server package via npm for use in AI desktop applications. ```bash npm install -g @resolvedmarkets/mcp-server ``` -------------------------------- ### GET /v1/markets/live Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Retrieves a list of all currently active markets. ```APIDOC ## GET /v1/markets/live ### Description Fetches a list of all live markets available for trading. ### Method GET ### Endpoint /v1/markets/live ### Response #### Success Response (200) - **markets** (array) - List of market objects #### Response Example { "markets": [ { "conditionId": "123", "slug": "btc-price-up" } ] } ``` -------------------------------- ### GET /v1/markets/live Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Retrieves a list of currently active markets available on the platform. ```APIDOC ## GET /v1/markets/live ### Description Fetches a list of all live markets, including their condition IDs, slugs, and descriptive questions. ### Method GET ### Endpoint /v1/markets/live ### Parameters #### Headers - **X-API-Key** (string) - Required - Your API access key ### Response #### Success Response (200) - **markets** (array) - List of market objects #### Response Example { "markets": [ { "conditionId": "0x123...", "slug": "btc-price-prediction", "question": "Will BTC reach $70k?", "category": "crypto" } ] } ``` -------------------------------- ### List Active Markets with cURL Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/getting-started.md This example shows how to retrieve a list of currently active markets using the ResolvedMarkets API. It requires authentication via the X-API-Key header. ```bash curl -H "X-API-Key: rm_your_key" https://api.resolvedmarkets.com/v1/markets/live ``` ```bash curl -H "X-API-Key: rm_your_key" \n "https://api.resolvedmarkets.com/v1/markets/live?category=crypto" ``` -------------------------------- ### Get Live Weather Markets Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/use-cases.md Fetches live markets categorized under 'weather'. This is the first step in analyzing weather prediction markets. ```APIDOC ## GET /v1/markets/live?category=weather ### Description Retrieves a list of live markets that belong to the 'weather' category. ### Method GET ### Endpoint /v1/markets/live ### Query Parameters - **category** (string) - Required - Filters markets by category. Use 'weather' for weather-related markets. ### Response #### Success Response (200) - **markets** (array) - A list of live weather market objects. - **id** (string) - The unique identifier for the market. - **title** (string) - The title of the market. - **category** (string) - The category the market belongs to. - **last_price** (number) - The last traded price for the market. #### Response Example { "markets": [ { "id": "market_123", "title": "Will NYC temperature exceed 90F this week?", "category": "weather", "last_price": 0.65 } ] } ``` -------------------------------- ### GET /v1/markets/live Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/api-reference.md Retrieves a list of currently active markets, with optional filtering by category and subcategory. ```APIDOC ## GET /v1/markets/live ### Description List active markets. Supports filtering by category and subcategory. ### Method GET ### Endpoint /v1/markets/live ### Parameters #### Query Parameters - **category** (string) - Optional. Filter by market category (e.g., `crypto`, `equities`, `social`, `sports`, `economics`, `weather`). - **subcategory** (string) - Optional. Filter by market subcategory (e.g., `BTC`, `SPX`, `Elon`, `NBA`, `FOMC`, `NYC`). ### Request Example None ### Response #### Success Response (200) - An array of market objects, each containing: - **conditionId** (string) - The unique identifier for the market condition. - **category** (string) - The category of the market. - **subcategory** (string) - The subcategory of the market. - **label** (string) - A descriptive label for the market. - **timeframe** (string) - The timeframe of the market (e.g., "weekly"). - **tokenIds** (array of strings) - Identifiers for associated tokens. - **outcomes** (array of strings) - Possible outcomes for the market (e.g., ["Yes", "No"]). - **slug** (string) - A URL-friendly slug for the market. - **expired** (boolean) - Indicates if the market has expired. - **expiresIn** (number) - Time in milliseconds until the market expires. #### Response Example ```json [ { "conditionId": "0x1234...", "category": "social", "subcategory": "Elon", "label": "260-279", "timeframe": "weekly", "tokenIds": ["abc...", "def..."], "outcomes": ["Yes", "No"], "slug": "elon-musk-of-tweets-march-20-march-27", "expired": false, "expiresIn": 172800000 } ] ``` ``` -------------------------------- ### MCP Server Integration Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Configuration guide for connecting the Resolved Markets MCP server to AI-powered IDEs and desktop assistants. ```APIDOC ## MCP Server Configuration ### Description Connects the Resolved Markets MCP server to allow AI assistants to query live market data, orderbooks, and historical snapshots. ### Configuration Format Add the following to your MCP configuration file (e.g., claude_desktop_config.json or .cursor/mcp.json): ```json { "mcpServers": { "resolved-markets": { "command": "npx", "args": ["-y", "@resolvedmarkets/mcp-server"], "env": { "HF_API_URL": "https://api.resolvedmarkets.com", "HF_API_KEY": "rm_your_key" } } } } ``` ### Available Tools - `list_markets`: List active markets. - `get_orderbook`: Get live orderbook for a market. - `get_snapshot`: Get historical snapshot at a specific timestamp. - `query_snapshots`: Query historical snapshots with filters. - `get_market_summary`: Get aggregated market statistics. - `get_system_stats`: Get platform health and stats. ``` -------------------------------- ### Stream Real-time Data via WebSocket Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/getting-started.md This example shows how to connect to the ResolvedMarkets WebSocket API to stream real-time data. It includes authentication and subscription messages. ```json { "type": "auth", "apiKey": "rm_your_key" } { "type": "subscribe", "crypto": "BTC" } ``` -------------------------------- ### Get Available Tiers and Credit Packs Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/api-reference.md Lists the available subscription tiers and credit packs, along with their associated pricing information. ```HTTP GET /v1/payments/packs ``` -------------------------------- ### GET /v1/markets/live Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Fetches a list of all currently active markets. This endpoint supports Incremental Static Regeneration (ISR) for efficient data fetching. ```APIDOC ## GET /v1/markets/live ### Description Retrieves a list of all active markets available on the platform. ### Method GET ### Endpoint https://api.resolvedmarkets.com/v1/markets/live ### Parameters #### Request Headers - **X-API-Key** (string) - Required - Your unique API authentication key. ### Request Example GET /v1/markets/live Headers: { "X-API-Key": "your_api_key" } ### Response #### Success Response (200) - **markets** (array) - List of market objects containing conditionId, slug, question, and category. #### Response Example { "markets": [ { "conditionId": "123", "slug": "market-slug", "question": "Will it rain?", "category": "Weather" } ] } ``` -------------------------------- ### GET /v1/public-stats Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Retrieves real-time platform statistics including snapshot counts, active markets, and current cryptocurrency prices. ```APIDOC ## GET /v1/public-stats ### Description Fetches the current platform health, snapshot counts, and latest crypto price data. ### Method GET ### Endpoint https://api.resolvedmarkets.com/v1/public-stats ### Parameters None ### Request Example GET https://api.resolvedmarkets.com/v1/public-stats ### Response #### Success Response (200) - **snapshotCount** (number) - Total number of snapshots recorded. - **activeMarkets** (number) - Count of currently active prediction markets. - **cryptoPrices** (object) - Map of cryptocurrency symbols to their current price. #### Response Example { "snapshotCount": 15420, "activeMarkets": 42, "cryptoPrices": { "BTC": 65000, "ETH": 3500 } } ``` -------------------------------- ### Get Market Orderbook with cURL Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/getting-started.md This snippet demonstrates how to fetch the orderbook for a specific market using its condition ID. Authentication with an API key is required. ```bash curl -H "X-API-Key: rm_your_key" https://api.resolvedmarkets.com/v1/markets/{conditionId}/orderbook ``` -------------------------------- ### GET /health - API Health Check Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/api-reference.md Checks the health status of the Resolved Markets API and its underlying infrastructure components like ClickHouse, Redis, and the WebSocket services. Returns a status indicating if the API is 'healthy', 'starting', or 'degraded'. ```json { "status": "healthy", "clickhouse": true, "redis": true, "ws_clob": true, "ws_trade": true, "pipeline_ready": true, "uptime": 123456 } ``` -------------------------------- ### Simulate Market Making Strategy with Python Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/use-cases.md This script demonstrates how to backtest a market-making strategy by fetching historical orderbook snapshots. It calculates bid/ask quotes, tracks inventory risk, and simulates order fills based on market movements. ```python import requests from dataclasses import dataclass, field API_URL = "https://api.resolvedmarkets.com" API_KEY = "rm_your_key" HEADERS = {"X-API-Key": API_KEY} @dataclass class MarketMakerSim: spread_target: float = 0.02 order_size: float = 100.0 inventory: float = 0.0 pnl: float = 0.0 fills: list = field(default_factory=list) def quote(self, mid_price: float) -> tuple[float, float]: half = self.spread_target / 2 skew = -0.001 * self.inventory bid = mid_price - half + skew ask = mid_price + half + skew return round(bid, 4), round(ask, 4) def check_fills(self, my_bid: float, my_ask: float, snapshot: dict): best_ask = snapshot["bestAsk"] best_bid = snapshot["bestBid"] if best_ask <= my_bid: self.inventory += self.order_size self.pnl -= my_bid * self.order_size self.fills.append(("BUY", my_bid, snapshot["eventTimestamp"])) if best_bid >= my_ask: self.inventory -= self.order_size self.pnl += my_ask * self.order_size self.fills.append(("SELL", my_ask, snapshot["eventTimestamp"])) def fetch_snapshots(market_id: str, from_ts: str, to_ts: str, token_side: str = "UP"): offset = 0 limit = 1000 while True: resp = requests.get( f"{API_URL}/v1/markets/{market_id}/snapshots", headers=HEADERS, params={ "from": from_ts, "to": to_ts, "tokenSide": token_side, "limit": limit, "offset": offset, }, ) data = resp.json() snapshots = data["snapshots"] if not snapshots: break yield from snapshots offset += limit if offset >= data["total"]: break def run_backtest(market_id: str, from_ts: str, to_ts: str): sim = MarketMakerSim(spread_target=0.02) for snap in fetch_snapshots(market_id, from_ts, to_ts): mid = snap["midPrice"] my_bid, my_ask = sim.quote(mid) sim.check_fills(my_bid, my_ask, snap) print(f"Total fills: {len(sim.fills)}") print(f"Final inventory: {sim.inventory}") print(f"PnL: {sim.pnl:.4f}") run_backtest("0x1234abcd...", "2026-03-24T10:00:00Z", "2026-03-24T11:00:00Z") ``` -------------------------------- ### Initialize Arbitrage Detection Client Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/use-cases.md This Python snippet sets up the base configuration for polling market data from the API. It establishes the headers and environment variables required to fetch active market prices for arbitrage analysis. ```python import requests import time from datetime import datetime API_URL = "https://api.resolvedmarkets.com" API_KEY = "rm_your_key" HEADERS = {"X-API-Key": API_KEY} ``` -------------------------------- ### Get BTC Market Orderbook and Spread (cURL, JavaScript, Python) Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/cookbook.md Fetches the live orderbook for a specified BTC market and calculates the bid-ask spread. Requires a market ID and API key. Outputs the best bid, best ask, and the calculated spread. ```bash curl -s -H "X-API-Key: rm_your_key" \ "https://api.resolvedmarkets.com/v1/markets/YOUR_MARKET_ID/orderbook" | \ jq '.tokens[0] | {bestBid, bestAsk, spread: (.bestAsk - .bestBid)}' ``` ```javascript const res = await fetch( "https://api.resolvedmarkets.com/v1/markets/YOUR_MARKET_ID/orderbook", { headers: { "X-API-Key": "rm_your_key" } } ); const data = await res.json(); const token = data.tokens[0]; const spread = token.bestAsk - token.bestBid; console.log(`Best Bid: ${token.bestBid}, Best Ask: ${token.bestAsk}, Spread: ${spread.toFixed(4)}`); ``` ```python import requests res = requests.get( "https://api.resolvedmarkets.com/v1/markets/YOUR_MARKET_ID/orderbook", headers={"X-API-Key": "rm_your_key"}, ) data = res.json() token = data["tokens"][0] spread = token["bestAsk"] - token["bestBid"] print(f"Best Bid: {token['bestBid']}, Best Ask: {token['bestAsk']}, Spread: {spread:.4f}") ``` -------------------------------- ### GET /v1/markets/history/recent Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/cookbook.md Retrieves a paginated list of historical markets. ```APIDOC ## GET /v1/markets/history/recent ### Description Retrieve recent historical markets using pagination parameters. ### Method GET ### Endpoint https://api.resolvedmarkets.com/v1/markets/history/recent ### Parameters #### Query Parameters - **limit** (integer) - Optional - Number of records to return (default 50). - **offset** (integer) - Optional - Number of records to skip. ### Response #### Success Response (200) - **array** (list) - A list of market objects. #### Response Example [ { "id": "1", "name": "Market A" }, { "id": "2", "name": "Market B" } ] ``` -------------------------------- ### GET /v1/exchange/orderbook Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/api-reference.md Retrieves the live orderbook for perpetual futures from Hyperliquid. ```APIDOC ## GET /v1/exchange/orderbook ### Description Live orderbook from Hyperliquid perpetual futures. ### Method GET ### Endpoint /v1/exchange/orderbook ### Parameters #### Query Parameters - **exchange** (string) - Required - Must be `hyperliquid_perp`. - **symbol** (string) - Required - The symbol of the cryptocurrency (e.g., `BTC`, `ETH`, `SOL`, or `XRP`). ### Request Example `GET /v1/exchange/orderbook?exchange=hyperliquid_perp&symbol=BTC` ### Response #### Success Response (200) - **exchange** (string) - The name of the exchange. - **symbol** (string) - The trading symbol. - **timestamp** (string) - The timestamp of the orderbook data. - **best_bid** (number) - The best bid price. - **best_ask** (number) - The best ask price. - **mid_price** (number) - The mid-price. - **spread** (number) - The spread between best bid and ask. - **bid_depth_total** (number) - Total bid depth. - **ask_depth_total** (number) - Total ask depth. - **bids** (array of arrays) - List of bid orders [price, size]. - **asks** (array of arrays) - List of ask orders [price, size]. #### Response Example ```json { "exchange": "hyperliquid_perp", "symbol": "BTC", "timestamp": "2026-03-27 14:30:00.123", "best_bid": 87420.50, "best_ask": 87421.00, "mid_price": 87420.75, "spread": 0.50, "bid_depth_total": 4250000, "ask_depth_total": 3890000, "bids": [[87420.5, 1.2], [87420.0, 0.8]], "asks": [[87421.0, 0.5], [87421.5, 1.1]] } ``` ``` -------------------------------- ### MCP Server Configuration Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/mcp-server.md Environment variables and configuration for setting up the MCP server. ```APIDOC ## MCP Server Configuration ### Description Configuration details for the MCP server, including environment variables and Claude Desktop setup. ### Environment Variables | Env Var | Default | Description | |---|---|---| | `HF_API_URL` | `http://localhost:3001` | Backend API URL | | `HF_API_KEY` | — | API key for authentication | | `MCP_TRANSPORT` | `stdio` | Transport: `stdio` or `http` | | `MCP_PORT` | `3002` | Port for HTTP transport | ### Claude Desktop Configuration Add the following to your Claude Desktop MCP config: ```json { "mcpServers": { "resolved-markets": { "command": "npx", "args": ["-y", "@resolvedmarkets/mcp-server"], "env": { "HF_API_URL": "https://api.resolvedmarkets.com", "HF_API_KEY": "rm_your_key" } } } } ``` ``` -------------------------------- ### MCP Server Resources Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/mcp-server.md URIs for accessing live market data and prices. ```APIDOC ## MCP Server Resources ### Description Provides URIs for accessing live market data and latest prices through the MCP server. ### Resources | URI | Description | |---|---| | `markets://live` | All currently active markets | | `prices://latest` | Latest crypto prices | ``` -------------------------------- ### GET /v1/exchange/snapshots Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/api-reference.md Retrieves historical exchange orderbook snapshots with 1-second sampling. ```APIDOC ## GET /v1/exchange/snapshots ### Description Retrieves historical exchange orderbook snapshots. Note that this is a lightweight endpoint and does not include full bid/ask arrays. ### Method GET ### Endpoint /v1/exchange/snapshots ### Parameters #### Query Parameters - **exchange** (string) - Required - The exchange name (e.g., hyperliquid_perp) - **symbol** (string) - Required - The trading symbol (e.g., BTC, ETH, SOL, XRP) - **from** (string) - Optional - Start timestamp (defaults to last 24h) - **to** (string) - Optional - End timestamp - **limit** (number) - Optional - Max rows (default 500, max 5000) ### Response #### Success Response (200) - **data** (array) - List of snapshot records ``` -------------------------------- ### Fetch Weather Markets and Track Prices with Python Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/use-cases.md This Python script demonstrates how to fetch live weather-category markets from the Resolved Markets API and track the evolution of market prices over time using snapshots. It sets up API request headers and base URL for subsequent data retrieval. ```python import requests import pandas as pd from datetime import datetime, timedelta API_URL = "https://api.resolvedmarkets.com" API_KEY = "rm_your_key" HEADERS = {"X-API-Key": API_KEY} ``` -------------------------------- ### Implement REST Client in Go Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md A structured Go client for interacting with Resolved Markets REST API. It provides methods to fetch live markets, orderbooks, and market summaries with built-in authentication headers. ```bash go get github.com/gorilla/websocket ``` ```go package resolvedmarkets import ( "encoding/json" "fmt" "io" "net/http" "time" ) type Client struct { BaseURL string APIKey string HTTPClient *http.Client } func NewClient(apiKey string) *Client { return &Client{ BaseURL: "https://api.resolvedmarkets.com", APIKey: apiKey, HTTPClient: &http.Client{ Timeout: 10 * time.Second, }, } } func (c *Client) doGet(path string, result interface{}) error { req, err := http.NewRequest("GET", c.BaseURL+path, nil) if err != nil { return err } req.Header.Set("X-API-Key", c.APIKey) req.Header.Set("Content-Type", "application/json") resp, err := c.HTTPClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) return fmt.Errorf("API %d: %s", resp.StatusCode, string(body)) } return json.NewDecoder(resp.Body).Decode(result) } ``` -------------------------------- ### GET /v1/markets/by-slug/:slug/orderbook Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/api-reference.md Retrieves the live orderbook for a market identified by its slug. ```APIDOC ## GET /v1/markets/by-slug/:slug/orderbook ### Description Live orderbook for a market by slug. Same response as `/v1/markets/:id/orderbook`. ### Method GET ### Endpoint /v1/markets/by-slug/:slug/orderbook ### Parameters #### Path Parameters - **slug** (string) - Required - The URL slug of the market. ### Request Example `GET /v1/markets/by-slug/elon-musk-of-tweets-march-20-march-27/orderbook` ### Response #### Success Response (200) - Orderbook details for the specified market (see `/v1/markets/:id/orderbook` for structure). #### Response Example ```json { "marketId": "0x1234...", "crypto": "BTC", "timeframe": "5m", "cryptoPrice": 87420.50, "up": { "bestBid": 0.52, "bestAsk": 0.53, "midPrice": 0.525, "spread": 0.01, "bids": [{"price": 0.52, "size": 1500}], "asks": [{"price": 0.53, "size": 800}] }, "down": { "..." : "..." } } ``` ``` -------------------------------- ### Consume Resolved Markets API in Go Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Demonstrates how to initialize the Resolved Markets client to perform REST API calls to list markets and fetch orderbooks, alongside initiating a WebSocket stream. ```go package main import ( "fmt" "log" "os" rm "your-module/resolvedmarkets" ) func main() { client := rm.NewClient(os.Getenv("RM_API_KEY")) markets, err := client.ListMarkets() if err != nil { log.Fatal(err) } for _, m := range markets { book, _ := client.GetOrderbook(m.ConditionID) fmt.Printf("%s: spread=%.4f\n", m.Slug, book.UP.Spread) } rm.StreamOrderbook(os.Getenv("RM_API_KEY"), []string{"BTC", "ETH"}, func(s rm.Snapshot) { fmt.Printf("%s %s: mid=%.4f spread=%.4f\n", s.Crypto, s.TokenSide, s.MidPrice, s.Spread) }) } ``` -------------------------------- ### GET /v1/markets/{market_id}/orderbook Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md Retrieves the current orderbook for a specific market. ```APIDOC ## GET /v1/markets/{market_id}/orderbook ### Description Returns the current bid/ask depth for a specific market ID. ### Method GET ### Endpoint /v1/markets/{market_id}/orderbook ### Parameters #### Path Parameters - **market_id** (string) - Required - The unique identifier for the market ### Response #### Success Response (200) - **UP** (object) - Orderbook data for the UP side - **DOWN** (object) - Orderbook data for the DOWN side ``` -------------------------------- ### GET /v1/markets/live Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/cookbook.md Retrieves a list of all currently active prediction markets filtered by category. ```APIDOC ## GET /v1/markets/live ### Description Retrieve every currently active crypto prediction market. ### Method GET ### Endpoint https://api.resolvedmarkets.com/v1/markets/live ### Parameters #### Query Parameters - **category** (string) - Optional - Filter markets by category (e.g., 'crypto'). ### Request Example curl -H "X-API-Key: rm_your_key" https://api.resolvedmarkets.com/v1/markets/live?category=crypto ### Response #### Success Response (200) - **markets** (array) - List of active market objects. #### Response Example [ { "slug": "btc-price-2024", "question": "Will BTC reach 100k?" } ] ``` -------------------------------- ### REST Client (Go) Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/sdks.md This Go client library provides methods to interact with the Resolved Markets REST API. It includes functions for initializing the client, listing live markets, retrieving order book data for a specific market, and fetching market summaries. The client handles HTTP requests, authentication, and response decoding. ```APIDOC ## REST Client (Go) ### Description This Go package provides a client for interacting with the Resolved Markets REST API. It allows you to list markets, get order book details, and retrieve market summaries. The client handles authentication using an API key and manages HTTP requests. ### Dependencies ```bash go get github.com/gorilla/websocket ``` ### Client Initialization ```go client := resolvedmarkets.NewClient("YOUR_API_KEY") ``` ### Methods #### ListMarkets() Retrieves a list of all live markets. - **Returns**: `[]Market`, `error` #### GetOrderbook(marketID string) Fetches the order book for a specific market. - **Parameters**: - **marketID** (string) - The unique identifier for the market. - **Returns**: `*MarketOrderbook`, `error` #### GetMarketSummary(marketID string) Retrieves a summary of a specific market. - **Parameters**: - **marketID** (string) - The unique identifier for the market. - **Returns**: `map[string]interface{}`, `error` ### Data Structures #### Market Represents a market. - **ConditionID** (string) - **Slug** (string) - **Question** (string) - **Category** (string) #### OrderLevel Represents a level in the order book. - **Price** (float64) - **Size** (float64) #### Orderbook Represents one side of the order book (bids or asks). - **TokenID** (string) - **TokenSide** (string) - **Bids** ([]OrderLevel) - **Asks** ([]OrderLevel) - **BestBid** (float64) - **BestAsk** (float64) - **MidPrice** (float64) - **Spread** (float64) #### MarketOrderbook Contains order book details for both UP and DOWN sides of a market. - **MarketID** (string) - **UP** (Orderbook) - **DOWN** (Orderbook) ### Request Example (Get Orderbook) ```go book, err := client.GetOrderbook("some_market_id") if err != nil { // Handle error } // Process book data ``` ### Response Example (Orderbook) ```json { "marketId": "example_market_id", "UP": { "tokenId": "BTC-UP", "tokenSide": "UP", "bids": [ {"price": 50000.00, "size": 1.5}, {"price": 49999.00, "size": 2.0} ], "asks": [ {"price": 50010.25, "size": 1.0}, {"price": 50020.50, "size": 1.8} ], "bestBid": 50000.00, "bestAsk": 50010.25, "midPrice": 50005.125, "spread": 10.25 }, "DOWN": { "tokenId": "BTC-DOWN", "tokenSide": "DOWN", "bids": [ {"price": -50000.00, "size": 1.5}, {"price": -49999.00, "size": 2.0} ], "asks": [ {"price": -50010.25, "size": 1.0}, {"price": -50020.50, "size": 1.8} ], "bestBid": -50010.25, "bestAsk": -50000.00, "midPrice": -50005.125, "spread": 10.25 } } ``` ``` -------------------------------- ### Establish WebSocket Connection and Subscribe to Market Data Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/websocket.md This snippet demonstrates how to connect to the WebSocket endpoint, perform authentication within the 5-second window, and subscribe to a specific cryptocurrency market to receive orderbook snapshots. ```javascript const ws = new WebSocket("wss://api.resolvedmarkets.com/ws/orderbook"); ws.onopen = () => { ws.send(JSON.stringify({ type: "auth", apiKey: "rm_your_key" })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "auth" && msg.status === "ok") { ws.send(JSON.stringify({ type: "subscribe", crypto: "BTC" })); } else if (msg.type === "snapshot") { console.log(`${msg.crypto} ${msg.tokenSide}: mid=${msg.midPrice} spread=${msg.spread}`); } }; ``` ```python import asyncio import json import websockets async def stream(): async with websockets.connect("wss://api.resolvedmarkets.com/ws/orderbook") as ws: await ws.send(json.dumps({"type": "auth", "apiKey": "rm_your_key"})) auth = json.loads(await ws.recv()) assert auth["status"] == "ok" await ws.send(json.dumps({"type": "subscribe", "crypto": "BTC"})) async for message in ws: data = json.loads(message) if data["type"] == "snapshot": print(f"{data['crypto']} {data['tokenSide']}: {data['midPrice']}") asyncio.run(stream()) ``` -------------------------------- ### GET /v1/markets/:id/orderbook Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/api-reference.md Retrieves the live orderbook for a specific market using its conditionId. ```APIDOC ## GET /v1/markets/:id/orderbook ### Description Live orderbook for a market by conditionId. Returns both UP/DOWN (or Yes/No) token books. ### Method GET ### Endpoint /v1/markets/:id/orderbook ### Parameters #### Path Parameters - **id** (string) - Required - The `conditionId` of the market. ### Request Example `GET /v1/markets/0x1234.../orderbook` ### Response #### Success Response (200) - **marketId** (string) - The ID of the market. - **crypto** (string) - Associated cryptocurrency symbol (if applicable). - **timeframe** (string) - The timeframe of the market. - **cryptoPrice** (number) - The current price of the associated cryptocurrency. - **up** (object) - Orderbook details for the "UP" outcome. - **bestBid** (number) - The highest bid price. - **bestAsk** (number) - The lowest ask price. - **midPrice** (number) - The mid-price between best bid and ask. - **spread** (number) - The difference between best ask and best bid. - **bids** (array of arrays) - List of bid orders [price, size]. - **asks** (array of arrays) - List of ask orders [price, size]. - **down** (object) - Orderbook details for the "DOWN" outcome (same structure as `up`). #### Response Example ```json { "marketId": "0x1234...", "crypto": "BTC", "timeframe": "5m", "cryptoPrice": 87420.50, "up": { "bestBid": 0.52, "bestAsk": 0.53, "midPrice": 0.525, "spread": 0.01, "bids": [{"price": 0.52, "size": 1500}], "asks": [{"price": 0.53, "size": 800}] }, "down": { "..." : "..." } } ``` ``` -------------------------------- ### Get Orderbook Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/getting-started.md Fetch the order book for a specific market identified by its condition ID. ```APIDOC ## GET /v1/markets/{conditionId}/orderbook ### Description Retrieves the order book for a specific market. ### Method GET ### Endpoint /v1/markets/{conditionId}/orderbook ### Parameters #### Path Parameters - **conditionId** (string) - Required - The unique identifier for the market's condition. ### Request Example ```bash curl -H "X-API-Key: rm_your_key" \ https://api.resolvedmarkets.com/v1/markets/{conditionId}/orderbook ``` ### Response #### Success Response (200) - **orderbook** (object) - Contains the order book details (bids and asks). #### Response Example ```json { "orderbook": { "bids": [ { "price": 100.50, "size": 10 } ], "asks": [ { "price": 101.00, "size": 5 } ] } } ``` ``` -------------------------------- ### GET /v1/markets/{conditionId}/orderbook Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/cookbook.md Retrieves the orderbook for a specific market to analyze liquidity and spreads. ```APIDOC ## GET /v1/markets/{conditionId}/orderbook ### Description Get the current orderbook for a market to calculate bid-ask spreads. ### Method GET ### Endpoint https://api.resolvedmarkets.com/v1/markets/{conditionId}/orderbook ### Parameters #### Path Parameters - **conditionId** (string) - Required - The unique ID of the market. ### Response #### Success Response (200) - **tokens** (array) - List of tokens with bestBid and bestAsk prices. #### Response Example { "tokens": [ { "tokenSide": "yes", "bestBid": 0.5, "bestAsk": 0.52 } ] } ``` -------------------------------- ### Export and Analyze Market Snapshots with Python Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/use-cases.md This script demonstrates how to paginate through the market snapshots API, flatten the JSON response into a pandas DataFrame, and perform basic statistical analysis on spread dynamics and latency. It also includes methods to export the processed data to Parquet and CSV formats for external research tools. ```python import requests import pandas as pd from datetime import datetime, timedelta API_URL = "https://api.resolvedmarkets.com" API_KEY = "rm_your_key" HEADERS = {"X-API-Key": API_KEY} def export_snapshots( market_id: str, from_ts: str, to_ts: str, token_side: str = "UP", ) -> pd.DataFrame: """Download all snapshots for a market and return as a DataFrame.""" all_snapshots = [] offset = 0 limit = 1000 while True: resp = requests.get( f"{API_URL}/v1/markets/{market_id}/snapshots", headers=HEADERS, params={ "from": from_ts, "to": to_ts, "tokenSide": token_side, "limit": limit, "offset": offset, }, ) resp.raise_for_status() data = resp.json() snapshots = data["snapshots"] if not snapshots: break all_snapshots.extend(snapshots) print(f" Fetched {len(all_snapshots)} / {data['total']} snapshots") offset += limit if offset >= data["total"]: break if not all_snapshots: return pd.DataFrame() rows = [] for snap in all_snapshots: rows.append({ "event_timestamp": snap["eventTimestamp"], "capture_timestamp": snap["captureTimestamp"], "token_side": snap["tokenSide"], "best_bid": snap["bestBid"], "best_ask": snap["bestAsk"], "mid_price": snap["midPrice"], "spread": snap["spread"], "total_bid_depth": snap["totalBidDepth"], "total_ask_depth": snap["totalAskDepth"], "sequence_number": snap["sequenceNumber"], "bid_levels": len(snap["bids"]), "ask_levels": len(snap["asks"]), "bid_1_price": snap["bids"][0]["price"] if snap["bids"] else None, "bid_1_size": snap["bids"][0]["size"] if snap["bids"] else None, "ask_1_price": snap["asks"][0]["price"] if snap["asks"] else None, "ask_1_size": snap["asks"][0]["size"] if snap["asks"] else None, }) df = pd.DataFrame(rows) df["event_timestamp"] = pd.to_datetime(df["event_timestamp"]) df["capture_timestamp"] = pd.to_datetime(df["capture_timestamp"]) df["capture_latency_ms"] = ( df["capture_timestamp"] - df["event_timestamp"] ).dt.total_seconds() * 1000 return df def analyze_spread_dynamics(df: pd.DataFrame): """Basic spread analysis for a research paper.""" print("=== Spread Dynamics ===") print(f"Observations: {len(df):,}") print(f"Time range: {df['event_timestamp'].min()} to {df['event_timestamp'].max()}") print(f"Mean spread: {df['spread'].mean():.6f}") print(f"Median spread: {df['spread'].median():.6f}") print(f"Std dev: {df['spread'].std():.6f}") print(f"Min: {df['spread'].min():.6f}, Max: {df['spread'].max():.6f}") df["hour"] = df["event_timestamp"].dt.hour hourly = df.groupby("hour")["spread"].mean() print("\nMean spread by hour (UTC):") for hour, spread in hourly.items(): print(f" {hour:02d}:00 - {spread:.6f}") print(f"\nCapture latency (ms): mean={df['capture_latency_ms'].mean():.1f}, " f"p99={df['capture_latency_ms'].quantile(0.99):.1f}") market_id = "0x1234abcd..." df = export_snapshots(market_id, "2026-03-23T00:00:00Z", "2026-03-24T00:00:00Z") if not df.empty: analyze_spread_dynamics(df) df.to_parquet("btc_up_snapshots_20260323.parquet", index=False) df_sampled = df.set_index("event_timestamp").resample("1s").first().dropna().reset_index() df_sampled.to_csv("btc_up_snapshots_1s_20260323.csv", index=False) ``` -------------------------------- ### GET /v1/markets/history Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/api-reference.md Retrieves historical market data with support for pagination and filtering by various criteria. ```APIDOC ## GET /v1/markets/history ### Description Full historical markets with pagination. ### Method GET ### Endpoint /v1/markets/history ### Parameters #### Query Parameters - **category** (string) - Optional. Filter by market category. - **subcategory** (string) - Optional. Filter by market subcategory. - **crypto** (string) - Optional. Legacy filter for cryptocurrencies (e.g., `BTC`, `ETH`, `SOL`, `XRP`). - **timeframe** (string) - Optional. Filter by market timeframe. ### Request Example None ### Response #### Success Response (200) - An array of historical market data objects. #### Response Example (Response structure similar to `/v1/markets/live` but with historical data) ```json [ { "conditionId": "0x1234...", "category": "social", "subcategory": "Elon", "label": "260-279", "timeframe": "weekly", "tokenIds": ["abc...", "def..."], "outcomes": ["Yes", "No"], "slug": "elon-musk-of-tweets-march-20-march-27", "expired": false, "expiresIn": 172800000, "resolvedTime": 1700000000 } ] ``` ``` -------------------------------- ### GET /v1/public-stats Source: https://github.com/elcara-hq/resolvedmarkets-docs/blob/main/docs/api-reference.md Retrieves platform-wide statistics, including snapshot counts and active market information. ```APIDOC ## GET /v1/public-stats ### Description Platform statistics. ### Method GET ### Endpoint /v1/public-stats ### Parameters None ### Request Example None ### Response #### Success Response (200) - **snapshot_count** (number) - Total number of snapshots available. - **active_markets** (number) - Number of currently active markets. - **prices** (object) - Current prices for select cryptocurrencies. - **BTC** (number) - Current price of Bitcoin. - **ETH** (number) - Current price of Ethereum. - **SOL** (number) - Current price of Solana. - **XRP** (number) - Current price of Ripple. #### Response Example ```json { "snapshot_count": 50234567, "active_markets": 142, "prices": { "BTC": 87420.50, "ETH": 3421.80, "SOL": 187.25, "XRP": 2.34 } } ``` ```