Real-Time Stock Market Data for OpenCode如何为 OpenCode 接入实时股票市场数据
Build reliable real-time stock data workflows for OpenCode with verified timestamps, market coverage, freshness, and failure handling.
围绕时间戳、市场覆盖、数据时效和故障处理,为 OpenCode 构建可靠的实时股票数据工作流。

What real-time stock data changes for OpenCode实时股票数据能为 OpenCode 带来什么
OpenCode can reason, remember context, schedule work, and invoke tools, but a language model's training data is not a live market feed. A market-data connection closes that freshness gap for research summaries, watchlist checks, volatility alerts, dashboard prototyping, and data-quality investigations.
The key boundary is equally important: this use case provides evidence for analysis; it does not authorize trading. Quotes can be delayed, venue-specific, consolidated, adjusted, or contractually restricted. Treat “real time” as a documented property of a feed and subscription, not a label inferred from a recent-looking number.
OpenCode 可以推理、记忆上下文、安排任务并调用工具,但语言模型的训练数据并不是实时行情源。接入市场数据可以补上新鲜度缺口,用于研究摘要、自选股检查、波动预警、看板原型和数据质量排查。
边界同样重要:本场景只为分析提供证据,并不授权交易。报价可能存在延迟、限定交易场所、采用综合行情、经过复权,或受到合同限制。因此,“实时”应当是数据源与订阅方案明确说明的属性,而不是根据一个看似最新的数字推断出来的标签。
Research and monitoring研究与监控
Fresh snapshots, watchlists, market-state summaries, chart inputs, and explainable alerts.新鲜快照、自选股、市场状态摘要、图表输入以及可解释预警。
Orders and portfolio actions订单与账户操作
Execution needs separate credentials, approvals, risk checks, idempotency, and audit policy.交易执行需要独立凭据、审批、风险检查、幂等机制与审计策略。
Reference architecture: feed → adapter → tool → OpenCode参考架构:数据源 → 适配器 → 工具 → OpenCode
Keep the agent-facing interface stable even when the provider changes. Normalize upstream responses before they reach OpenCode, and preserve the raw provider identity in the result envelope.即使更换服务商,也应保持面向智能体的接口稳定。上游响应进入 OpenCode 前先完成标准化,同时在结果数据包中保留原始服务商身份。
Licensed feed合规数据源
Quotes, trades, bars, status报价、成交、K 线、状态
Adapter适配器
Normalize symbols and time统一代码与时间
Read-only tool只读工具
Validate and bound calls校验并限制调用
OpenCodeOpenCode
Reason over attributed data基于可追溯数据推理
Why not send a WebSocket directly into the model?
A continuous feed is application state, not conversational context. Let a stream consumer handle reconnects, ordering, deduplication, backpressure, and cache updates. OpenCode should request a bounded snapshot or aggregate through a tool. This controls token use and makes calls reproducible.
为什么不把 WebSocket 直接送入模型?
持续数据流属于应用状态,不属于对话上下文。应由流消费者处理重连、排序、去重、背压和缓存更新,再由 OpenCode 通过工具获取有边界的快照或聚合结果。这样既能控制 token 消耗,也便于复现每次调用。
Implementation: connect a market-data tool in six steps实施:用六步连接行情工具
1. Define freshness before choosing a provider
Specify asset class, exchanges, trade or quote data, maximum acceptable age, extended-hours behavior, history depth, and whether results will be displayed or redistributed. Then compare provider documentation and entitlements. A developer plan may expose a different feed from a paid production plan.
2. Build a provider-neutral adapter
Map vendor fields into one typed contract. Normalize symbol conventions, timestamps, currency, session status, corporate-action adjustments, and typed errors. Keep provider-specific fields under an optional metadata object.
3. Expose narrow read tools
Start with operations such as get_quote, get_bars, and get_market_status. Put limits on symbols, date ranges, granularity, and response size. Do not expose arbitrary URLs, arbitrary SQL, or provider administration.
4. Register the MCP server in OpenCode
OpenCode supports local MCP servers over stdio and remote servers over Streamable HTTP. In OpenCode V2, define a unique server name under mcp.servers. Keep the market-data key in an environment variable, not in the prompt or repository. For a remote server that uses an API key, set oauth to false and pass a scoped header. See the official OpenCode MCP server documentation for the current schema.
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"servers": {
"market-data": {
"type": "local",
"command": ["node", "./tools/market-data-mcp.mjs"],
"environment": {
"MARKET_DATA_API_KEY": "{env:MARKET_DATA_API_KEY}"
},
"codemode": true,
"timeout": 10000
}
}
}
}OpenCode connects configured servers automatically unless disabled is true. Keep codemode enabled unless you intentionally want every tool exposed directly, and use OpenCode permissions to deny operations outside the read-only surface. Confirm the connection with opencode2 mcp list.
1. 选择服务商前先定义新鲜度
先明确资产类别、交易所、需要成交还是报价数据、可接受的最大数据年龄、盘前盘后处理方式、历史深度,以及结果是否会被展示或再分发。之后再比较服务商文档与数据权限;开发者方案与付费生产方案可能提供不同的数据源。
2. 构建与服务商无关的适配器
把服务商字段映射为统一的类型化契约,规范股票代码、时间戳、币种、交易时段、公司行为复权规则和类型化错误。服务商特有字段应放入可选的元数据对象。
3. 只暴露范围明确的读取工具
先提供 get_quote、get_bars 和 get_market_status 等操作,并限制股票数量、日期范围、时间粒度和响应大小。不要暴露任意 URL、任意 SQL 或服务商管理接口。
4. 在 OpenCode 中注册 MCP 服务
OpenCode 支持通过 stdio 连接本地 MCP 服务,也支持通过 Streamable HTTP 连接远程服务。在 OpenCode V2 中,应把唯一服务名配置在 mcp.servers 下。行情密钥应保存在环境变量中,不能写入提示词或代码仓库。若远程服务仅使用 API key,请将 oauth 设为 false,并通过受限请求头传递凭据。当前配置结构以 OpenCode 官方 MCP 文档为准。
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"servers": {
"market-data": {
"type": "local",
"command": ["node", "./tools/market-data-mcp.mjs"],
"environment": {
"MARKET_DATA_API_KEY": "{env:MARKET_DATA_API_KEY}"
},
"codemode": true,
"timeout": 10000
}
}
}
}除非 disabled 为 true,OpenCode 会自动连接已配置服务。通常应保留 codemode,并通过权限规则拒绝只读范围之外的操作。最后运行 opencode2 mcp list 检查连接状态。
5. Prompt for evidence, not confidence
Require OpenCode to state symbol, value type, event time, receipt time, provider/feed, session, currency, and delay classification. If data is stale or the market is closed, the answer should say so before interpreting the move.
6. Test degraded states
Use recorded fixtures for deterministic tests, then run an opt-in live smoke test. Exercise rate limiting, provider timeouts, malformed payloads, symbol not found, closed sessions, stale cache, partial batches, and reconnect recovery.
5. 要求证据,而不是自信语气
要求 OpenCode 明确说明股票代码、数值类型、事件时间、接收时间、服务商/数据源、交易时段、币种和延迟分类。如果数据过期或市场休市,应先说明状态,再解释价格变化。
6. 测试降级状态
确定性测试使用录制样例,再执行主动启用的实时冒烟测试。需要覆盖限流、服务商超时、异常数据包、代码不存在、休市、缓存过期、批量结果不完整以及重连恢复。
Design a tool contract OpenCode can reason over设计便于 OpenCode 推理的工具契约
A price without its meaning is unsafe. Return an explicit envelope rather than a bare number.脱离语义的价格并不安全。应返回结构明确的数据包,而不是一个裸数字。
| Field字段 | Purpose作用 | Example meaning示例含义 |
|---|---|---|
symbol | Resolved instrument identity解析后的标的身份 | Ticker plus exchange when ambiguous存在歧义时包含交易所 |
last / bid / ask | Typed price values有明确类型的价格 | Never collapse quote and trade不混淆报价与成交 |
event_time | When the market event occurred市场事件发生时间 | Provider timestamp in UTC服务商 UTC 时间戳 |
received_at | When your adapter received it适配器接收时间 | Supports age and transport checks用于计算数据年龄与传输延迟 |
source | Provider and feed provenance服务商与数据源来源 | Avoids false equivalence避免把不同数据源等同 |
session | Pre, regular, post, or closed盘前、常规、盘后或休市 | Explains apparent inactivity解释看似没有变化的原因 |
freshness | Live, delayed, stale, or unknown实时、延迟、过期或未知 | Computed from explicit policy依据明确策略计算 |
Four high-value OpenCode workflows四个高价值 OpenCode 工作流
Watchlist with market context带市场背景的自选股摘要
Combine fresh snapshots with prior-close bars and explicitly label pre-market data. Schedule the brief, but make “no fresh data” a valid outcome.将新鲜快照与前收盘 K 线结合,并明确标注盘前数据。可以定时生成简报,但“暂无新鲜数据”也应是合法结果。
Explain conflicting prices解释价格冲突
Have OpenCode compare feed, venue, timestamp, quote versus trade, session, and adjustment policy instead of choosing one value blindly.让 OpenCode 比较数据源、场所、时间、报价与成交、交易时段及复权规则,而不是盲目选择一个数值。
Prototype a live dashboard构建实时看板原型
Let OpenCode build against a provider-independent schema, with explicit loading, delayed, stale, disconnected, and closed states.让 OpenCode 基于与服务商无关的 schema 开发,并显式呈现加载、延迟、过期、断线与休市状态。
Read-only threshold alerts只读阈值预警
Evaluate rules in an application service, then let OpenCode explain attributed triggers. Keep execution credentials entirely absent.由应用服务评估规则,再让 OpenCode 解释带来源的触发记录;整个链路不应出现交易凭据。
Use QVeris provider discovery to review available data sources, then verify coverage and licensing in the chosen provider's official documentation. Use QVeris tool discovery to find the narrow read operation your workflow needs.可通过 QVeris 服务商目录检查可用数据源,再到所选服务商的官方文档确认覆盖范围与授权。随后在 QVeris 工具目录中寻找工作流真正需要的精确读取操作。
Production controls: freshness, safety, cost, and rights生产控制:新鲜度、安全、成本与授权
Use two clocks使用两个时钟
Compare provider event time with gateway receipt time. A newly received payload can still contain an old event.比较服务商事件时间与网关接收时间。刚收到的数据包仍可能包含较早的事件。
Keep credentials server-side凭据只留在服务端
Never place API keys in prompts, logs, skills, examples, or version control. Scope and rotate them.不要把 API 密钥放进提示词、日志、skills、示例或版本控制,并应限制范围、定期轮换。
Budget calls deliberately主动控制调用成本
Batch symbols, cache only within a declared TTL, cap history windows, and observe rate-limit headers.批量查询股票,在声明的 TTL 内缓存,限制历史时间窗,并监控限流响应头。
Respect data rights遵守数据授权
Display, storage, derived-data, and redistribution rights differ. Match implementation to the actual agreement.展示、存储、衍生数据和再分发权限各不相同,实施方式必须匹配实际协议。
Release checklist发布检查清单
- Every value includes type, currency, source, event time, receipt time, and session.每个数值都包含类型、币种、来源、事件时间、接收时间与交易时段。
- The tool rejects invalid symbols, non-finite values, reversed windows, and oversized batches.工具拒绝无效代码、非有限数值、颠倒时间窗和过大批次。
- Stale, delayed, disconnected, partial, and closed states are visible.过期、延迟、断线、部分结果和休市状态均清晰可见。
- Market data and order execution use different services, credentials, and approval paths.行情数据与交易执行使用不同服务、凭据和审批路径。
- Recorded fixtures cover normal and degraded behavior without requiring an open market.录制样例覆盖正常与降级行为,核心测试不依赖市场开盘。
Troubleshooting the failures that look like “bad AI”排查那些看起来像“AI 出错”的数据问题
| Symptom现象 | Likely cause可能原因 | Check检查项 |
|---|---|---|
| Price differs from another app价格与另一应用不同 | Different feed, venue, value type, or delay数据源、场所、数值类型或延迟不同 | Compare provenance and timestamps比较来源与时间戳 |
| Data never changes数据一直不变 | Closed session, stale cache, lost stream休市、缓存过期或数据流中断 | Inspect session, TTL, heartbeat检查交易时段、TTL 与心跳 |
| OpenCode cannot see the toolOpenCode 看不到工具 | Server disabled, startup failure, or filter服务被禁用、启动失败或工具过滤 | Review config, stderr, and tool list检查配置、stderr 与工具列表 |
| Calls time out in batches批量调用超时 | Provider limit or oversized request服务商限流或请求过大 | Bound batch size; retry with jitter限制批次并采用带抖动的重试 |
If OpenCode runs several market-data calls in parallel, enable that only for read-only operations and only after checking the adapter for shared-state races. Serialize any workflow that mutates shared state.如果 OpenCode 并行运行多个行情调用,只应对只读操作启用,并先检查适配器是否存在共享状态竞争。任何会修改共享状态的工作流都应串行执行。
Frequently asked questions常见问题
Can OpenCode get real-time stock prices by itself?OpenCode 能自行获取实时股价吗?
Not as an inherent model capability. Connect a licensed data source through a controlled read-only tool, then return timestamps, feed identity, and freshness with each result.这不是模型自带能力。应通过受控的只读工具连接具备授权的数据源,并在每次结果中返回时间戳、数据源身份和新鲜度。
Which OpenCode connection method should I use?应使用哪种 OpenCode 连接方式?
Use a local MCP server when OpenCode should start a trusted process in the workspace over stdio. Use a remote MCP server when the adapter is centrally hosted and reachable through Streamable HTTP. In both cases, keep credentials in environment variables or scoped headers and expose only read operations.如果希望 OpenCode 在工作区内通过 stdio 启动可信进程,请使用本地 MCP 服务;如果适配器由中心化服务托管,并通过 Streamable HTTP 访问,请使用远程 MCP 服务。两种方式都应将凭据保存在环境变量或受限请求头中,并且只暴露读取操作。
Should I expose a live WebSocket directly to OpenCode?是否应把实时 WebSocket 直接暴露给 OpenCode?
Usually no. Maintain streaming state in an application-side consumer and expose bounded snapshots or aggregates. This makes ordering, retries, backpressure, cancellation, and token use manageable.通常不建议。应在应用侧消费者中维护数据流状态,再暴露有边界的快照或聚合结果,从而更好地管理排序、重试、背压、取消与 token 使用。
Can this workflow place trades?这个工作流可以下单吗?
No. This design is intentionally read-only. If execution is added later, isolate it behind separate services, credentials, explicit confirmation, risk controls, idempotency, and audit logs.不可以。本设计有意保持只读。若未来增加交易执行,必须使用独立服务和凭据,并加入明确确认、风险控制、幂等机制与审计日志。
How do I test when markets are closed?市场休市时如何测试?
Replay timestamped fixtures and simulate market-session states. Keep a separate opt-in live smoke test for connectivity; do not make the main test suite depend on an open exchange.回放带时间戳的样例并模拟不同交易时段。可保留一个单独启用的实时连通性冒烟测试,但不要让主测试套件依赖交易所开盘。
Turn a market feed into a tool OpenCode can trust把行情源变成 OpenCode 可以信任的工具
Start with one read-only quote operation, one freshness rule, and one attributed response envelope. Validate it before widening symbols or history.从一个只读报价操作、一条新鲜度规则和一个带来源的响应数据包开始,验证通过后再扩大股票与历史范围。
