Skip to main content
Glama
demwick

Polymarket Agent Mcp

analysis.price_history

Retrieve historical OHLC price data for any market token with configurable time intervals from 1 hour to 1 month. Includes sparkline visualization to analyze price trends.

Instructions

Fetch historical OHLC price data for a market token over a configurable time window (1h to 1m). Returns price points with a sparkline visualization showing the price trend. Pro feature.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
token_idYesMarket token ID to fetch price history for
intervalNoTime window: 1h, 6h, 1d, 1w, or 1m1d

Implementation Reference

  • src/index.ts:337-342 (registration)
    Registration of the 'analysis.price_history' tool with the MCP server using getPriceHistorySchema and handleGetPriceHistory.
    server.tool(
      "analysis.price_history",
      "Fetch historical OHLC price data for a market token over a configurable time window (1h to 1m). Returns price points with a sparkline visualization showing the price trend. Pro feature.",
      getPriceHistorySchema.shape,
      safe("markets.price_history", async (input) => ({ content: [{ type: "text" as const, text: await handleGetPriceHistory(getPriceHistorySchema.parse(input)) }] }))
    );
  • Input schema for the price history tool: takes token_id (string) and optional interval (1h, 6h, 1d, 1w, 1m) with default '1d'.
    export const getPriceHistorySchema = z.object({
      token_id: z.string().describe("Market token ID to fetch price history for"),
      interval: z.enum(["1h", "6h", "1d", "1w", "1m"]).optional().default("1d").describe("Time window: 1h, 6h, 1d, 1w, or 1m"),
    });
  • Handler function that fetches price history, formats output with metrics table, recent prices, and a sparkline trend visualization.
    export async function handleGetPriceHistory(input: z.infer<typeof getPriceHistorySchema>): Promise<string> {
      const isPro = await checkLicense(); if (!isPro) return requirePro("get_price_history");
      const history = await getPriceHistory(input.token_id, input.interval as Interval);
    
      if (history.points.length === 0) {
        return `No price history available for this token (interval: ${input.interval}). The market may be too new or inactive.`;
      }
    
      const arrow = history.change >= 0 ? "+" : "";
      let output = `## Price History (${input.interval})\n\n`;
      output += `| Metric | Value |\n|--------|-------|\n`;
      output += `| Open | $${history.open.toFixed(4)} |\n`;
      output += `| Close | $${history.close.toFixed(4)} |\n`;
      output += `| High | $${history.high.toFixed(4)} |\n`;
      output += `| Low | $${history.low.toFixed(4)} |\n`;
      output += `| Change | ${arrow}$${history.change.toFixed(4)} (${arrow}${history.changePct.toFixed(1)}%) |\n`;
      output += `| Data Points | ${history.points.length} |\n`;
    
      // Show recent price points (last 10)
      const recent = history.points.slice(-10);
      if (recent.length > 0) {
        output += `\n### Recent Prices\n\n`;
        output += `| Time | Price |\n|------|-------|\n`;
        for (const p of recent) {
          const time = p.timestamp.slice(11, 16);
          output += `| ${time} | $${p.price.toFixed(4)} |\n`;
        }
      }
    
      // Sparkline summary
      const sampled = samplePoints(history.points, 20);
      if (sampled.length >= 2) {
        const min = Math.min(...sampled.map((p) => p.price));
        const max = Math.max(...sampled.map((p) => p.price));
        const range = max - min || 1;
        const bars = sampled.map((p) => {
          const level = Math.round(((p.price - min) / range) * 7);
          return ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"][level];
        }).join("");
        output += `\n**Trend:** ${bars}\n`;
      }
    
      return output;
    }
  • Helper function samplePoints that downsamples price points for the sparkline display.
    function samplePoints(points: { price: number }[], count: number): { price: number }[] {
      if (points.length <= count) return points;
      const step = (points.length - 1) / (count - 1);
      return Array.from({ length: count }, (_, i) => points[Math.round(i * step)]);
    }
  • Core service function that fetches historical OHLC price data from the Polymarket CLOB API, computes high/low/open/close/change metrics.
    export async function getPriceHistory(
      tokenId: string,
      interval: Interval = "1d",
      fidelity: number = 60
    ): Promise<PriceHistory> {
      const startTs = Math.floor(Date.now() / 1000) - INTERVAL_SECONDS[interval];
      const url = `${CLOB_API_BASE}/prices-history?market=${tokenId}&startTs=${startTs}&fidelity=${fidelity}`;
    
      log("info", `Fetching price history: ${tokenId} interval=${interval}`);
    
      try {
        const res = await fetchWithRetry(url, { retries: 1, timeoutMs: 8_000 });
        if (!res.ok) {
          log("warn", `Price history API returned ${res.status} for ${tokenId}`);
          return emptyHistory(tokenId, interval);
        }
    
        const data = await res.json();
        const history = data.history ?? [];
    
        if (history.length === 0) return emptyHistory(tokenId, interval);
    
        const points: PricePoint[] = history.map((h: any) => ({
          timestamp: new Date(h.t * 1000).toISOString(),
          price: parseFloat(h.p),
        }));
    
        const prices = points.map((p) => p.price);
        const open = prices[0];
        const close = prices[prices.length - 1];
        const high = Math.max(...prices);
        const low = Math.min(...prices);
        const change = close - open;
        const changePct = open > 0 ? (change / open) * 100 : 0;
    
        return { tokenId, interval, points, high, low, open, close, change, changePct };
      } catch (err) {
        log("error", `Failed to fetch price history for ${tokenId}: ${err}`);
        return emptyHistory(tokenId, interval);
      }
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description must cover behavioral traits. It states that the tool returns price points and a sparkline visualization, and it notes it's a Pro feature. However, it does not disclose data freshness, rate limits, or whether the operation is read-only (though implied). There is no contradiction with any annotation as none exist.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences: the first clearly defines the action and parameters, and the second adds output details and access note. Every sentence serves a purpose with no redundancy or fluff.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

There is no output schema, so the description compensates by mentioning 'price points with a sparkline visualization'. This is sufficient for a simple data retrieval tool. Given the tool's low complexity and the richness of sibling tools, it is adequately complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% as both parameters have descriptions. The description adds context that the data is OHLC and includes a sparkline, but it largely paraphrases the schema's enum values and token_id description. With full schema coverage, the description adds marginal value beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb ('Fetch') and clearly identifies the resource ('historical OHLC price data for a market token'). It also specifies the configurable time window and mentions output details, distinguishing it from related tools like markets.price (current price) or analysis.compare.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description mentions the configurable time window and valid intervals, giving context on when to use it. However, it does not explicitly state when not to use it nor provides alternatives among the many sibling tools. The 'Pro feature' note implies access limitations but lacks usage guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/demwick/polymarket-agent-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server