Skip to content

OpenMarkets API reference

OpenMarkets publishes 125 MCP tools in the full profile. The installed server is the source of truth for tool names, parameter constraints, and output schemas; export that contract directly instead of relying on a hand-maintained copy:

uv run openmarkets --profile full --export-schema openmarkets-tools.json

Without --profile, schema export describes the 125-tool full default. Use another profile to export a workflow or complete specialist module:

uv run openmarkets --profile research --export-schema research-tools.json

See installation for available profiles and modules.

Research prompts and reference resources

MCP clients can discover reusable workflows with prompts/list and render them with prompts/get. Rendering provides research instructions; it does not fetch market data or execute tools.

Prompt Arguments Availability
company_research Required ticker When get_curated_info is published
portfolio_review Required tickers (comma-separated); optional weights When calculate_portfolio_risk_metrics is published

Prompts suggest only tools published by that server. Portfolio review requests confirmation of weights and sampling assumptions before calculations.

Use resources/list and resources/read to discover and read:

URI Content
openmarkets://reference/providers JSON describing enabled providers and tool source preferences, including a single enabled source; no automatic fallback
openmarkets://reference/data-conventions Markdown covering missing data, dates, price adjustments, indicator warm-up, portfolio assumptions, backtests, and citations

These references perform no provider requests. They complement the tool catalog without exposing duplicate data-fetching interfaces. Resource templates remain unregistered until there is a concrete document-access use case.

Screener and industry discovery

search_screener_matches(query, count, offset) runs a predefined Yahoo screen; query is not free text or a ticker lookup. Examples include day_gainers, most_actives, and undervalued_large_caps. Discover the supported names in the tool's query enum through MCP tools/list or the exported schema. Use count to bound the page size and offset to skip matches; the returned total is the number of matches, not the page size, and live rankings can change between page requests.

Use get_all_industries() to discover canonical industry identifiers, or supply sector="technology" to narrow the list. Pass the returned identifiers, such as semiconductors, to industry tools. This catalog is a local mapping rather than a live ranking. The schema and discovery tools are authoritative.

Transport endpoints

With --transport http, the server exposes:

  • POST /mcp for MCP Streamable HTTP JSON-RPC
  • GET /health for liveness
  • GET /metrics for Prometheus metrics

HTTP operators can set OPENMARKETS_REQUEST_STATE_KEYS to a comma-separated ring of secrets (each at least 32 bytes) when replicas must verify the same multi-round request state. --http-stateless is an explicit compatibility setting for 2025-era Streamable HTTP clients; 2026 clients are sessionless by protocol regardless of this flag. Keep DNS-rebinding protection enabled unless the deployment boundary is a trusted reverse proxy, and configure --http-allowed-hosts for every accepted Host value.

Unknown tool arguments and invalid constrained values are rejected. Provider absence is reported separately from malformed provider data, and tool output follows the exported JSON schemas.

Provider and calculation contracts

get_info(ticker, fields=...) selects public output names such as longName, marketCap, and trailingPE. Omit fields for complete information, or pass [] for an empty selection without a provider request. Unknown names fail validation. Valid fields with missing values remain null. A projection contains only the selected fields inside the existing MCP result envelope.

Provider failures are unsuccessful MCP calls. DataUnavailableError means no usable observation is available, ProviderContractError means the upstream shape or value is malformed, and ProviderUnavailableError means transport, throttling, or temporary upstream failure. Invalid request values and unsupported mathematical inputs raise ValueError. A failed fetch is never returned as an error dictionary inside successful financial data. Legitimately empty optional collections retain their empty-list or nullable results. Unexpected programming errors retain their original exception types in Python callers and server logs. Failed tool calls are not cached.

Aggregate financial, holdings, and analyst tools fail when a component fails. Global-index snapshots explicitly support partial success and report missing_symbols and component_errors. Yield snapshots report missing instruments and mixed observation dates; spreads require matching dates. XBRL observations include duration starts and filing dates, and results declare how the latest value was selected.

The public SEC ticker catalog is shared within a process and refreshed on the first lookup after one hour. Concurrent lookups share a refresh; a failed refresh is reported rather than returning expired metadata as a successful lookup.

Portfolio risk, correlation, allocation, and factor tools accept annualization_factor (252 by default; use 365 for calendar-day observations). Technical volatility exposes the same parameter. Portfolio results include assumptions and observations: the preparation policy, retained coverage, dropped observations, and filled values. Provider dates are not resampled; the policy removes all-missing dates, forward-fills interior gaps, and removes incomplete leading history. Tail statistics describe returns per retained observation, which must not automatically be interpreted as calendar-day risk.

Backtests execute signals at the next observation's close, account for costs and terminal liquidation, and use elapsed calendar time for CAGR when dates exist. The result declares its observation-count fallback and cash/position policy.

Python usage

Construct adapter instances and configure sessions on their constructors:

from curl_cffi.requests import Session
from openmarkets.repositories.stock import YFinanceStockRepository
from openmarkets.services.stock import StockService

# The caller owns and closes an explicitly injected transport.
with Session(impersonate="chrome", timeout=5) as transport:
    repository = YFinanceStockRepository(session=transport)
    service = StockService(repository=repository)
    info = service.get_info("AAPL")

Service repositories are fixed at construction and exposed through read-only repository and (where applicable) wsj_repository properties. To substitute a repository, construct a new service. It gets a new cache identity without clearing other services' entries. Service-level bind_runtime and bind_session methods are replaced by constructor arguments:

from openmarkets.core.runtime import ProviderRuntime
from openmarkets.services.stock import StockService

runtime = ProviderRuntime(timeout=5)
try:
    service = StockService(runtime=runtime)
    info = service.get_info("AAPL")
finally:
    runtime.close()

An injected concrete provider adapter is configured explicitly with the supplied runtime/session during service construction. Do not share it across independent runtimes; construct another provider adapter instead. Injected domain repositories can implement the repository Protocol without a resource-binding interface.

create_mcp() creates independent adapter instances and a ProviderRuntime. Transport lifespans close owned resources; direct callers that do not run a transport must call server.close(). Automatic schema exports close servers they create internally. Standalone repositories without injected transport use the documented shared fallback, released at process exit.

Factor results provide loadings (factor, beta, t_statistic), annualized_intercept_percent, intercept_t_statistic, and r_squared. The intercept is a raw-return quantity, not Jensen alpha.

Yahoo operations are serialized behind a bounded provider gate because yfinance mutates a process-global session during lazy fetches. This protects OpenMarkets operations with different transports but reduces Yahoo parallelism. Independent WSJ, SEC and FRED work remains concurrent. Portfolio calculations release the Yahoo gate after acquisition, before alignment and local computation.

timeout sets runtime-owned transport defaults and is passed explicitly to Yahoo single-symbol and batch history requests. Standalone adapters without a runtime retain provider defaults. It is a request timeout, not a deadline for an entire tool: retries, multiple requests, and local computation can add time. Aggregate calls wait at most max(3 * timeout, 1 second) for submitted work; Yahoo gate acquisition has its own wait bounded by that budget. These waits are separate and do not form a shared end-to-end deadline. Running blocking I/O cannot be forcibly stopped: aggregate deadlines cancel queued work, and shutdown drains active work under transport timeouts.

Shared price and indicator tools

get_history(ticker, period="1y", interval="1d", source=None, extended_hours=False, adjusted=False) handles daily and intraday prices. source can be yahoo or wsj when enabled by --providers; otherwise the preferred enabled source is selected (Yahoo for prices/indicators, WSJ for index snapshots). Unsupported options and disabled sources fail without fallback.

History returns a PriceHistory envelope containing symbol, source, adjustment, period, interval, extended_hours, and data_points. Bars have UTC date values, OHLCV, and optional dividend/split fields. Missing closes remain null observations; no calendar dates, prices, or volumes are invented.

With adjusted=False, Yahoo prices use auto_adjust=False and are reported as yahoo_split_adjusted. adjusted=True requests yahoo_split_dividend_adjusted. WSJ results are labeled wsj_native: no equivalence to Yahoo adjustment policy is assumed. WSJ rejects adjusted=True, period="ytd", and unsupported intervals such as 90m, 5d, and 3mo. The history/technical default now uses native prices; request adjusted Yahoo prices explicitly when total-return adjustments are needed.

get_sma, get_ema, get_rsi, get_macd, and get_bollinger_bands accept the same source, period, interval, extended-hours, and adjustment options. Both sources use local calculations: SMA-seeded EMA, Wilder RSI (flat window=50), SMA-seeded MACD signal, and population-standard-deviation Bollinger Bands. Missing closes restart warm-up; warm-up values are omitted. Results include the actual source, adjustment policy, and calculation conventions. Summary technical tools also support both sources; volatility excludes returns adjacent to missing closes.

get_global_indices(source=...) and get_volatility_vix(source=...) support both sources and report latest observed levels, not guaranteed real-time quotes. Yield curves, sovereign comparisons, FX, and commodity tools retain WSJ adapters. The fertilizer index uses a separate Green Markets adapter.

Migration from provider-prefixed tools

Removed tool Replacement
get_wsj_stock_history get_history(source="wsj")
get_wsj_intraday_bars get_history(source="wsj", period="1d", interval="5m", extended_hours=True)
get_wsj_sma, get_wsj_ema, get_wsj_rsi, get_wsj_macd Corresponding get_sma, get_ema, get_rsi, get_macd with source="wsj"
get_wsj_bollinger_bands get_bollinger_bands(source="wsj")

Use period/interval instead of WSJ timeframe/step strings. get_history formerly returned a bare list; consume its data_points envelope field instead. Indicator values now follow the documented local conventions, rather than WSJ's server-side calculations. Python users should use PriceHistoryRepository and TechnicalIndicatorRepository; the former WSJ-native repository classes are removed. YFinanceTechnicalAnalysisRepository remains a compatibility import for the shared technical repository, preferring Yahoo when enabled.