Recursive Epistemic Market Microstructure MCP Server

by apifyforge

168 downloads
Not rated
GitHub Website

About

Recursive epistemic market microstructure analysis is now available as an MCP server your AI agent can call directly.

Details

Author
apifyforge
Downloads
168
Categories
Finance

- Soros reflexivity detection with three regime classifications
- Minority game simulation with phase transition detection
- Kyle (1985) insider model with probability of informed trading
- Rough volatility estimation (Hurst exponent) via log‑variogram regression
- Entropic optimal transport for regime transition probabilities
- Sharp regression discontinuity for regulatory impact estimation

Setting up with Highlight

This MCP is not yet compatible with Highlight’s one-click setup. However, you can still use it with Highlight by following these steps:

  1. Download and install Highlight from highlightai.com/download
  2. Navigate to the plugins tab and select "Add Custom Plugin"
  3. Configure the plugin with the settings below
    Plugin Name Recursive Epistemic Market Microstructure MCP Server
    Command (node, npx, python, etc.)

    Please refer to the README for specific instructions on how to obtain API keys or other required environment variables.

  4. Enable "Start Automatically" if you want the plugin to start when Highlight launches

From the repository

Add the server URL (https://recursive-epistemic-market-mcp.apify.actor/mcp) to your MCP‑compatible client (Claude Desktop, Cursor, Windsurf) with your Apify API token as the Authorization: Bearer YOUR_TOKEN header. Your AI agent then calls any of the 8 tools – for example β€œdetect reflexive dynamics for AAPL” – and receives structured JSON results.

Claude Desktop / Cursor

Paste into your MCP client config file to install this server.

{
    "mcpServers": {
        "recursive epistemic market microstructure mcp server": {
            "recursive-epistemic-market-mcp": {
                "url": "https://ryanclinton--recursive-epistemic-market-mcp.apify.actor/mcp"
            }
        }
    }
}

McpServers

{
    "recursive-epistemic-market-mcp": {
        "url": "https://ryanclinton--recursive-epistemic-market-mcp.apify.actor/mcp"
    }
}

Recursive Epistemic Market Microstructure MCP Server

> View on ApifyForge | Use on Apify Store

---

Quick Start

Add to your MCP client (Claude Desktop, Cursor, Windsurf):

{
  "mcpServers": {
    "recursive-epistemic-market-mcp": {
      "url": "https://ryanclinton--recursive-epistemic-market-mcp.apify.actor/mcp"
    }
  }
}

---

Recursive epistemic market microstructure analysis is now available as an MCP server your AI agent can call directly. This server exposes 8 tools that apply advanced mathematical finance models β€” Soros reflexivity fixed-point iteration, Harsanyi type space belief hierarchies, minority game spin glass phase transitions, rough volatility (fBm with H<0.5), entropic optimal transport, regression discontinuity for regulatory impact, and the Kyle continuous insider trading model β€” each calibrated from 16 live public data sources spanning SEC filings, FDIC bank records, congressional stock trades, FRED macro indicators, and exchange rate history.

Connect once via the MCP protocol and your AI agent gains structured, quantitative market microstructure intelligence without managing data pipelines, API integrations, or financial math implementations. Every tool is pay-per-call with no subscription required.

What data can you access?

| Data Point | Source | Example |
|---|---|---|
| πŸ“Š SEC 10-K, 10-Q, 8-K filings and analysis | SEC EDGAR Analyzer | Earnings quality scores, risk flag counts |
| πŸ“„ SEC filing full text and metadata | SEC EDGAR Filing Search | Form type, filing date, CIK, accession number |
| πŸ‘€ Executive insider stock transactions | SEC Insider Trading (Form 4) | 50,000 shares sold by CFO at $142.30 |
| 🏦 US bank financial statements | FDIC Bank Data | Total assets, Tier 1 capital, loan loss reserves |
| πŸ›οΈ Congressional stock trading disclosures | Congressional Stock Tracker | Representative name, ticker, trade date, amount range |
| πŸ“ˆ Stock prices, quotes, and financials | Finnhub | AAPL last: $185.42, P/E: 28.6, beta: 1.24 |
| πŸͺ™ Cryptocurrency prices and market cap | CoinGecko | BTC $67,240, 24h vol $38.4B, market cap $1.32T |
| πŸ’± Current foreign exchange rates | Exchange Rate Tracker | USD/EUR: 0.9214, USD/JPY: 149.82 |
| πŸ“‰ Historical exchange rate time series | Exchange Rate History | 365-day USD/EUR daily close series |
| πŸ›οΈ US economic indicators (GDP, CPI, rates) | FRED | Fed Funds rate: 5.33%, CPI YoY: 3.1% |
| πŸ‘· Employment and inflation statistics | BLS | Unemployment: 3.7%, wage growth: 4.1% |
| πŸ“‹ Federal rules and regulations | Federal Register | Dodd-Frank amendment, effective date, CFR citation |
| 🏒 Global corporate registrations | OpenCorporates | Jurisdiction, incorporation date, officers |
| ⚠️ Consumer financial complaints | CFPB | Product type, issue, company response, resolution |
| πŸ‡ͺπŸ‡Ί ECB reference exchange rates | ECB Rates | EUR/USD reference, date, change from prior day |
| πŸ“œ Congressional bill introductions and status | Congress Bill Tracker | Bill number, sponsor, committee, latest action |

Why use this MCP server for market microstructure analysis?

Building quantitative market microstructure intelligence from scratch means integrating 16 separate APIs, implementing fixed-point iteration algorithms, calibrating Hurst exponent estimators, and coding Sinkhorn divergence solvers β€” weeks of work before writing a single line of domain analysis. Commercial alternatives like Bloomberg Terminal charge $24,000/year; even lighter tools like Refinitiv or FactSet run $1,000+/month, with no AI-native interface.

This MCP server plugs directly into Claude, Cursor, or any MCP-compatible AI client. Your agent issues a single tool call and receives structured JSON with regime classifications, fixed-point prices, informed trading probabilities, and volatility roughness scores β€” all derived from live data across 16 sources processed in parallel.

- Always-on availability β€” runs in Apify Standby mode, ready for requests within milliseconds
- Parallel data fetching β€” up to 16 actors called simultaneously per tool invocation, reducing latency
- Structured JSON output β€” every tool returns typed, consistently-formatted output your agent can reason over directly
- Pay-per-call pricing β€” $0.10 per tool call, no subscription, no minimum commitment
- Spending limits β€” set a per-run cap in Apify to prevent runaway agent loops from accumulating cost
- API and webhook access β€” trigger from any HTTP client, Zapier, Make, or LLM orchestration framework

Features

- Soros reflexivity detection β€” models price as p(t+1) = f(p(t), E[p(t+1)|p(t)]) and finds the fixed point p via Picard iteration, computing a reflexivity gap that measures divergence between market price and rational equilibrium
- Three reflexivity regimes β€” classifies markets into CONVERGENT (gap shrinking), DIVERGENT (bubble/crash dynamics), or OSCILLATING (cyclical feedback)
- Harsanyi type space construction β€” builds K-depth belief hierarchies via projective limit truncation, computing Bayesian Nash equilibrium strategies and a common knowledge gap score across all identified market participants
- Minority game simulation β€” El Farol / Minority Game with N agents (51-501, odd), S random strategies per agent, and phase transition detection at alpha = P/N where P = 2^M; spin glass order parameter measures strategy crowding
- Two minority game regimes β€” identifies whether the market is below the critical alpha (herding, high volatility, inefficient) or above it (efficient, low excess volatility, strategy diversity)
- Kyle (1985) continuous insider model β€” computes price impact lambda = sigma_v / (2
sigma_u), information revelation rate via backward induction, expected insider profit, market maker loss, and Probability of Informed Trading (PIN = alphadelta / (alphadelta + 2epsilon))
- Three informedness regimes β€” LOW_INFO, MODERATE_INFO, HIGH_INFO based on PIN and signal-to-noise ratio
- Rough volatility estimation β€” Hurst exponent from log-variogram regression: V(delta) ~ C
delta^(2H), with volatility model sigma(t) = sigma_0exp(etaW_H(t) - eta^2t^(2H)/2)
- Three roughness regimes β€” SMOOTH (H>0.5), ROUGH (0.15<H<0.5), ULTRA_ROUGH (H<0.15), with implied skew from rough Bergomi model
- Entropic optimal transport β€” Sinkhorn divergence between BULL, BEAR, VOLATILE, and STABLE regime distributions; builds Gibbs kernel K_ij = exp(-C_ij/epsilon) and iterates u <- a/(Kv), v <- b/(K^Tu) to convergence
- Regime transition probabilities β€” Sinkhorn divergence S_eps removes entropic bias and produces calibrated transition probability estimates between regimes
- Sharp regression discontinuity β€” tau = lim_{x->c+} E[Y|X=x] - lim_{x->c-} E[Y|X=x] for regulatory impact, using local linear regression with Imbens-Kalyanaraman optimal bandwidth and McCrary density test for running variable manipulation
- Full recursive epistemic forecast β€” forecast_fixed_point_price orchestrates all four core algorithms (reflexivity + belief hierarchy + rough volatility + Kyle model) in a single call across 16 actors for a unified multi-factor price forecast
- 16 live data sources β€” SEC EDGAR (analysis + filings), SEC Insider Trading, FDIC, Congressional Stock, Finnhub, CoinGecko, Exchange Rates (current + historical), FRED, BLS, Federal Register, OpenCorporates, CFPB, ECB Rates, Congress Bills

Use cases for recursive epistemic market microstructure analysis

Quantitative hedge fund research

Quantitative researchers use detect_reflexive_dynamics to identify when expectations are driving prices away from fundamental value, and assess_rough_volatility to obtain Hurst exponents for options pricing with rough Bergomi rather than Black-Scholes. Both tools pull live FRED macro data, Finnhub quotes, and SEC filings in parallel, so the output is calibrated to current market conditions, not historical backtests.

Market surveillance and compliance

Regulators and compliance teams use analyze_insider_topology to screen for elevated Probability of Informed Trading (PIN) and large price impact lambda values across SEC Form 4 filings, congressional stock trades, and EDGAR filings. Assets flagged with HIGH_INFO regime classification warrant deeper review. The tool's Kyle model outputs β€” insider profit estimates and market maker loss β€” provide quantitative anchors for enforcement referrals.

AI agent financial reasoning

AI agents built with Claude, GPT-4, or open-source models can call these tools directly through the MCP protocol to ground financial analysis in live data and rigorous models. Instead of hallucinating market dynamics from training data, the agent calls compute_belief_hierarchy and receives structured type space outputs describing actual participant belief divergence, or calls simulate_minority_game to get a current herding/efficiency classification before generating investment commentary.

Macro research and policy analysis

Economists and policy analysts use evaluate_regulatory_impact to estimate the causal effect of specific Federal Register regulations on market outcomes. The sharp RD estimator with Imbens-Kalyanaraman optimal bandwidth and McCrary density test for manipulation ensures methodologically sound causal inference from public data β€” at a fraction of the cost of proprietary econometric datasets.

Volatility trading and options desks

Options traders use assess_rough_volatility to classify equity and FX assets by roughness regime. Assets in ULTRA_ROUGH territory (H < 0.15) require rough Bergomi or similar models for accurate implied vol surface calibration. The tool returns per-asset Hurst exponents, vol-of-vol estimates, and rough Bergomi implied skew inputs across stocks, crypto, and FX β€” all from a single MCP tool call.

Regime change and crisis early warning

Risk managers use compute_entropic_transport to monitor the Sinkhorn divergence between the current market regime distribution and alternative states (BULL, BEAR, VOLATILE, STABLE). When transition probabilities to VOLATILE or BEAR regimes spike, it provides a quantitative early warning signal grounded in optimal transport theory rather than simple threshold rules.

How to connect this MCP server to your AI client

1. Get your Apify API token β€” sign up at apify.com, go to Settings > Integrations, and copy your API token.
2. Add the server URL to your AI client β€” the MCP endpoint is https://recursive-epistemic-market-mcp.apify.actor/mcp. Paste this into your client's MCP server configuration (see examples below).
3. Authenticate the connection β€” pass your Apify token as the Authorization: Bearer YOUR_TOKEN header, or use the token query parameter where your client requires it.
4. Start calling tools β€” ask your AI assistant to "detect reflexive dynamics for AAPL technology stocks" or "run a minority game simulation for the current S&P 500 market", and it will invoke the corresponding tool automatically.

Claude Desktop

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "recursive-epistemic-market": {
      "url": "https://recursive-epistemic-market-mcp.apify.actor/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_APIFY_TOKEN"
      }
    }
  }
}

Cursor

Add to your Cursor MCP settings (.cursor/mcp.json):

{
  "mcpServers": {
    "recursive-epistemic-market": {
      "url": "https://recursive-epistemic-market-mcp.apify.actor/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_APIFY_TOKEN"
      }
    }
  }
}

Other MCP clients

Any client implementing the MCP specification (Windsurf, Cline, LangChain MCP adapter, LlamaIndex tool wrappers) can connect using the url configuration above. The server uses stateless Streamable HTTP transport β€” no session management required.

MCP tools reference

| Tool | Price | Actors called | Description |
|------|-------|---------------|-------------|
| detect_reflexive_dynamics | $0.10 | 8 | Soros reflexivity fixed-point iteration. Classifies markets: CONVERGENT, DIVERGENT, OSCILLATING. |
| compute_belief_hierarchy | $0.10 | 6 | Harsanyi type spaces, K-depth belief hierarchy, Bayesian Nash equilibrium, common knowledge gap. |
| simulate_minority_game | $0.10 | 4 | El Farol minority game phase transition. Spin glass order parameter, herding detection, efficiency regime. |
| analyze_insider_topology | $0.10 | 7 | Kyle (1985) model. Price impact lambda, PIN, information revelation rate, insider profit estimate. |
| assess_rough_volatility | $0.10 | 6 | Fractional Brownian motion Hurst exponent, rough Bergomi implied skew, SMOOTH/ROUGH/ULTRA_ROUGH regime. |
| compute_entropic_transport | $0.10 | 6 | Sinkhorn divergence between BULL/BEAR/VOLATILE/STABLE regimes. Transition probability matrix. |
| evaluate_regulatory_impact | $0.10 | 7 | Sharp regression discontinuity with IK optimal bandwidth and McCrary density test. |
| forecast_fixed_point_price | $0.10 | 16 | Full recursive epistemic forecast combining all four core algorithms. Most comprehensive tool. |

Tool input parameters

| Parameter | Type | Tool(s) | Default | Description |
|-----------|------|---------|---------|-------------|
| query | string | All tools | β€” | Market query, company, ticker, or sector (e.g. "AAPL MSFT technology stocks") |
| sector | string | detect_reflexive_dynamics, evaluate_regulatory_impact | β€” | Sector to narrow the analysis (e.g. "technology", "finance") |
| hierarchy_depth | number | compute_belief_hierarchy | 5 | Depth of Harsanyi belief hierarchy (1-10) |
| num_agents | number | simulate_minority_game | 101 | Number of minority game agents (odd integer, 51-501) |
| memory_length | number | simulate_minority_game | 6 | Memory length M; generates P = 2^M possible histories (3-10) |
| num_rounds | number | simulate_minority_game | 200 | Simulation rounds (50-1000) |
| epsilon | number | compute_entropic_transport | 0.1 | Sinkhorn entropic regularization parameter (0.01-1.0; lower = more precise, slower) |

Input examples

Detect reflexive dynamics in the banking sector:

{
"query": "JPMorgan Goldman Sachs banking",
"sector": "finance"
}

Simulate minority game with custom parameters:

{
"query": "S&P 500 US equities",
"num_agents": 201,
"memory_length": 8,
"num_rounds": 500
}

Full recursive epistemic forecast (all algorithms, 16 actors):

{
"query": "NVDA AMD semiconductor AI chips"
}

Regulatory impact of Dodd-Frank on banks:

{
"query": "Dodd-Frank capital requirements",
"sector": "banking"
}

Input tips

- Use specific queries for sharper results β€” "AAPL MSFT technology stocks" produces more calibrated output than "stocks". Include tickers alongside company names for better Finnhub matching.
- Start with detect_reflexive_dynamics or assess_rough_volatility β€” these are the fastest tools to interpret and give a clear regime classification before diving into the more complex multi-algorithm outputs.
- Use forecast_fixed_point_price for comprehensive analysis β€” it calls all four core algorithms across 16 actors in a single invocation, so the cost is the same $0.10 as any individual tool.
- Tune epsilon for Sinkhorn convergence β€” values between 0.05 and 0.2 balance precision and stability. Very low epsilon (0.01) can cause numerical instability; very high (1.0) blurs regime boundaries.
- Odd agent counts for minority game β€” the minority game requires an odd number of agents so ties cannot occur. The default 101 is appropriate for most analyses; increase to 501 for smoother phase transition detection.

Output example

detect_reflexive_dynamics β€” NVDA semiconductor query:

{
  "systemReflexivity": 0.73,
  "dominantRegime": "DIVERGENT",
  "assetCount": 6,
  "states": [
    {
      "ticker": "NVDA",
      "fixedPoint": 892.40,
      "reflexivityGap": 0.18,
      "feedbackStrength": 0.81,
      "regime": "DIVERGENT",
      "convergenceIterations": 47
    },
    {
      "ticker": "AMD",
      "fixedPoint": 168.30,
      "reflexivityGap": 0.09,
      "feedbackStrength": 0.54,
      "regime": "CONVERGENT",
      "convergenceIterations": 12
    },
    {
      "ticker": "INTC",
      "fixedPoint": 34.10,
      "reflexivityGap": 0.04,
      "feedbackStrength": 0.29,
      "regime": "CONVERGENT",
      "convergenceIterations": 8
    }
  ]
}

analyze_insider_topology β€” banking query:

{
  "systemInformedness": 0.62,
  "averageLambda": 0.041,
  "dominantRegime": "MODERATE_INFO",
  "assetCount": 4,
  "assets": [
    {
      "ticker": "JPM",
      "lambda": 0.058,
      "informedTradingProbability": 0.71,
      "insiderProfit": 184200,
      "priceEfficiency": 0.44,
      "signalToNoise": 2.31,
      "regime": "HIGH_INFO"
    },
    {
      "ticker": "GS",
      "lambda": 0.033,
      "informedTradingProbability": 0.48,
      "insiderProfit": 92800,
      "priceEfficiency": 0.67,
      "signalToNoise": 1.12,
      "regime": "MODERATE_INFO"
    }
  ]
}

simulate_minority_game β€” S&P 500 query:

{
  "alpha": 0.64,
  "phaseTransitionPoint": 0.34,
  "regime": "ASYMMETRIC",
  "volatilityRatio": 0.82,
  "informationContent": 0.71,
  "crowdingMeasure": 0.29,
  "topAgents": [
    { "agentId": 42, "strategy": 1, "score": 147 },
    { "agentId": 78, "strategy": 0, "score": 139 }
  ],
  "recentAttendance": [48, 53, 45, 51, 49, 55, 47, 52, 50, 48]
}

forecast_fixed_point_price β€” full recursive epistemic forecast:

{
  "systemForecast": {
    "forecastHorizon": "30d",
    "consensusDirection": "BULLISH",
    "confidenceScore": 0.61,
    "epistemicUncertainty": 0.38
  },
  "reflexivitySummary": {
    "systemReflexivity": 0.68,
    "dominantRegime": "DIVERGENT"
  },
  "beliefSummary": {
    "commonKnowledgeGap": 0.44,
    "agentCount": 12,
    "hierarchyDepth": 5
  },
  "volatilitySummary": {
    "systemRoughness": 0.19,
    "dominantRegime": "ROUGH"
  },
  "insiderSummary": {
    "systemInformedness": 0.57,
    "averageLambda": 0.036,
    "dominantRegime": "MODERATE_INFO"
  },
  "forecasts": [
    {
      "ticker": "NVDA",
      "fixedPointPrice": 892.40,
      "beliefAdjustedPrice": 871.20,
      "volAdjustedRange": [834.10, 910.50],
      "insiderAdjustment": -0.023,
      "compositeConfidence": 0.58
    }
  ]
}

Output fields

| Field | Type | Description |
|-------|------|-------------|
| systemReflexivity | number | System-wide reflexivity score 0-1; higher = stronger feedback loops |
| dominantRegime | string | Majority regime across analyzed assets |
| states[].ticker | string | Asset identifier |
| states[].fixedPoint | number | Fixed-point price p
where p = f(p, E[p\|p]) |
| states[].reflexivityGap | number | Normalized distance between market price and rational equilibrium |
| states[].feedbackStrength | number | Magnitude of price-expectation feedback (0-1) |
| states[].regime | string | CONVERGENT, DIVERGENT, or OSCILLATING |
| states[].convergenceIterations | number | Picard iterations to reach fixed point (or max 100 if non-convergent) |
| commonKnowledgeGap | number | Average divergence in higher-order beliefs across agent types |
| bayesianNashEquilibrium[].strategy | number | Optimal strategy for each agent type under BNE |
| types[].privateValue | number | Agent-specific fundamental value estimate |
| types[].rationalityBound | number | Level-k rationality bound (0=naive, 1=fully rational) |
| alpha | number | Minority game complexity ratio P/N |
| phaseTransitionPoint | number | Critical alpha_c below which herding dominates |
| crowdingMeasure | number | Spin glass order parameter; higher = more crowded strategies |
| volatilityRatio | number | Excess volatility relative to efficient market benchmark |
| assets[].hurstExponent | number | Hurst exponent H; <0.5 = rough, =0.5 = standard BM, >0.5 = trending |
| assets[].roughnessIndex | number | Normalized roughness score 0-1 |
| assets[].volOfVol | number | Volatility of volatility (vol clustering measure) |
| assets[].skewImplied | number | Implied skew from rough Bergomi model |
| assets[].lambda | number | Kyle price impact coefficient ($/share per unit order flow) |
| assets[].informedTradingProbability | number | PIN β€” Probability of Informed Trading (0-1) |
| assets[].insiderProfit | number | Estimated expected insider profit per trading window ($) |
| assets[].priceEfficiency | number | Price efficiency score 0-1; lower = more mispricing |
| comparisons[].sinkhornDivergence | number | Sinkhorn divergence S_eps between two regime distributions |
| comparisons[].transitionProbability | number | Estimated probability of transitioning between the two regimes |
| estimates[].treatmentEffect | number | RD causal estimate tau of regulatory impact |
| estimates[].tStatistic | number | t-statistic for treatment effect significance test |
| estimates[].significant | boolean | True if |t| > 1.96 (95% confidence) |
| estimates[].mcCraryDensityTest | number | McCrary test statistic for running variable manipulation |
| forecasts[].fixedPointPrice | number | Reflexivity-adjusted fixed-point price forecast |
| forecasts[].compositeConfidence | number | Combined confidence score from all four algorithms (0-1) |

How much does it cost to use this MCP server?

This MCP server uses pay-per-event pricing β€” you pay $0.10 per tool call. Platform compute costs are included. All 8 tools cost the same $0.10 regardless of how many actors they invoke in the background.

| Scenario | Tool calls | Cost per call | Total cost |
|----------|-----------|---------------|------------|
| Quick test β€” single reflexivity check | 1 | $0.10 | $0.10 |
| Single-stock deep dive (all 8 tools) | 8 | $0.10 | $0.80 |
| Daily sector scan (10 queries/day) | 10 | $0.10 | $1.00/day |
| Weekly research workflow (50 calls) | 50 | $0.10 | $5.00 |
| Active quant research (500 calls/month) | 500 | $0.10 | $50.00/month |

You can set a maximum spending limit per run to control costs. The server stops charging when your budget is reached.

Apify's free tier includes $5 of monthly platform credits β€” enough for 50 tool calls per month at no cost. Compare this to Bloomberg Terminal at $2,000/month or Refinitiv Eikon at $1,200/month. Most users running daily research workflows spend $5-50/month with no subscription commitment.

Using the MCP server via API

Python

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")

No reviews yet β€” be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.