Skip to main content
Glama

get_historical_context

Retrieve historical market conditions for a specific date to analyze past regimes, risk scores, and financial metrics for comparison with current data.

Instructions

Look up what market conditions were on a specific date. Returns regime, fear/greed, risk score, BTC price, and TVL from that date. Useful for comparing past conditions to current ones.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dateYesDate in ISO format, e.g. "2026-03-01" or "2025-12-15"

Implementation Reference

  • Main handler function that retrieves and computes historical market/signal context for a given date.
    export async function getHistoricalContext(cache: CacheService, date: string): Promise<HistoricalContextOutput | ErrorOutput> {
      const requestedDate = new Date(date);
      if (isNaN(requestedDate.getTime())) {
        return {
          error: true, error_source: 'get_historical_context',
          agent_guidance: 'Invalid date format. Use ISO format like "2026-03-01" or "2025-12-15".',
          last_known_data: null, data_warnings: ['Invalid date format.'],
        };
      }
    
      const requestedTs = requestedDate.getTime();
      const warnings: string[] = [];
    
      // Step 1: Check signal history for closest match
      const signals = getAllSignals();
      let closestSignal = null;
      let closestDiff = Infinity;
    
      for (const s of signals) {
        const diff = Math.abs(new Date(s.timestamp).getTime() - requestedTs);
        if (diff < closestDiff) {
          closestDiff = diff;
          closestSignal = s;
        }
      }
    
      // If we have a signal within 24 hours, use it
      if (closestSignal && closestDiff < 86400000) {
        const guidance = generateHistoricalGuidance(
          date, closestSignal.regime ?? 'unknown', closestSignal.posture ?? 'unknown',
          closestSignal.risk_score ?? 50, closestSignal.fear_greed ?? null,
        );
    
        return {
          requested_date: date,
          data_source: 'signal_history',
          closest_signal_date: closestSignal.timestamp,
          regime: closestSignal.regime ?? null,
          fear_greed: closestSignal.fear_greed ?? null,
          fear_greed_label: closestSignal.fear_greed !== undefined ? getFgLabel(closestSignal.fear_greed) : null,
          risk_score: closestSignal.risk_score ?? null,
          suggested_posture: closestSignal.posture ?? null,
          btc_price_usd: closestSignal.btc_price_at_signal ?? null,
          total_tvl_usd: null,
          cycle_phase: null,
          agent_guidance: guidance,
          data_warnings: warnings,
        };
      }
    
      // Step 2: Compute from historical data
      try {
        const now = Date.now();
        const daysAgo = Math.ceil((now - requestedTs) / 86400000);
    
        if (daysAgo < 1 || daysAgo > 365) {
          warnings.push('Historical data limited to the past 365 days.');
        }
    
        let btcPrice: number | null = null;
        let fearGreed: number | null = null;
        let tvl: number | null = null;
    
        // BTC price from market chart
        try {
          const chart = await getMarketChart('bitcoin', Math.min(daysAgo + 5, 365));
          const pricePoint = chart.prices.reduce((closest, p) => {
            const diff = Math.abs(p[0] - requestedTs);
            return diff < Math.abs(closest[0] - requestedTs) ? p : closest;
          });
          btcPrice = Math.round(pricePoint[1] * 100) / 100;
        } catch { warnings.push('BTC price data unavailable for this date.'); }
    
        // Fear & Greed (only goes back ~7 days via API)
        try {
          const fgData = await getFearGreed();
          const fgPoint = fgData.data.reduce((closest: typeof fgData.data[0] | null, entry) => {
            const entryTs = parseInt(entry.timestamp) * 1000;
            const diff = Math.abs(entryTs - requestedTs);
            if (!closest) return entry;
            const closestDiff = Math.abs(parseInt(closest.timestamp) * 1000 - requestedTs);
            return diff < closestDiff ? entry : closest;
          }, null);
          if (fgPoint) fearGreed = parseInt(fgPoint.value);
        } catch { warnings.push('Fear & Greed data unavailable for this date.'); }
    
        // TVL from historical
        try {
          const tvlHistory = await getHistoricalTvl();
          const tvlPoint = tvlHistory.reduce((closest, entry) => {
            const diff = Math.abs(entry.date * 1000 - requestedTs);
            return diff < Math.abs(closest.date * 1000 - requestedTs) ? entry : closest;
          });
          tvl = Math.round(tvlPoint.tvl);
        } catch { warnings.push('TVL data unavailable for this date.'); }
    
        const guidance = generateHistoricalGuidance(date, null, null, null, fearGreed);
    
        return {
          requested_date: date,
          data_source: 'computed_from_historical',
          closest_signal_date: closestSignal?.timestamp ?? null,
          regime: null,
          fear_greed: fearGreed,
          fear_greed_label: fearGreed !== null ? getFgLabel(fearGreed) : null,
          risk_score: null,
          suggested_posture: null,
          btc_price_usd: btcPrice,
          total_tvl_usd: tvl,
          cycle_phase: null,
          agent_guidance: guidance,
          data_warnings: warnings,
        };
      } catch {
        return {
          error: true, error_source: 'get_historical_context',
          agent_guidance: 'Historical context temporarily unavailable. Retry shortly.',
          last_known_data: null, data_warnings: ['Historical data sources temporarily unavailable.'],
        };
      }
    }
  • Type definition for the output structure of the tool.
    export interface HistoricalContextOutput {
      requested_date: string;
      data_source: 'signal_history' | 'computed_from_historical';
      closest_signal_date: string | null;
      regime: string | null;
      fear_greed: number | null;
      fear_greed_label: string | null;
      risk_score: number | null;
      suggested_posture: string | null;
      btc_price_usd: number | null;
      total_tvl_usd: number | null;
      cycle_phase: string | null;
      agent_guidance: string;
      data_warnings: string[];
    }
Behavior3/5

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

With no annotations provided, the description must carry the full disclosure burden. It compensates partially by listing the specific fields returned (regime, fear/greed, risk score, BTC price, TVL) which helps since there is no output schema. However, it omits operational details such as how far back historical data extends, whether the lookup is idempotent, or if there are rate limits.

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

Conciseness4/5

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

The description is appropriately brief with three information-dense statements covering purpose, return values, and utility. The structure front-loads the core action and avoids redundancy, though the fragment 'Returns regime...' slightly breaks grammatical flow.

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?

Given the tool's simplicity (one primitive parameter) and lack of output schema, the description adequately compensates by enumerating the returned data fields. However, it could be strengthened by noting date range limitations or data availability constraints that are common considerations for historical lookups.

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?

The input schema has 100% description coverage for its single parameter, documenting the ISO format with examples. The description adds no additional semantic context beyond implying a historical date is required, meeting the baseline expectation for high-coverage schemas.

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

Purpose4/5

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

The description clearly states the tool retrieves historical market conditions using the specific verb 'Look up' combined with the resource 'market conditions'. It effectively distinguishes this from sibling tools by emphasizing the temporal aspect ('on a specific date', 'past conditions') and listing specific historical data points (regime, fear/greed) that suggest a historical snapshot rather than current state.

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 provides the use case 'comparing past conditions to current ones' which implies when the tool is valuable. However, it lacks explicit guidance on when not to use this tool (e.g., for real-time data) and fails to name specific alternatives from the sibling list like get_market_regime or get_temporal_context that might serve similar but distinct purposes.

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/0xHashy/fathom-fyi'

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