QVeris
Guides 指南 / Real-time stock data for Grok 为 Grok 接入实时股票数据
Grok function-calling guide Grok 函数调用指南

How to Add Real-Time Stock Market Data to Grok 如何为 Grok 接入实时股票市场数据

This guide shows developers how to provide real-time stock market data for Grok through a controlled tool-calling workflow. 本指南面向开发者,介绍如何通过受控的工具调用工作流,为 Grok 提供实时股票市场数据。 Give Grok a narrow, read-only market tool that returns not just a price, but the evidence needed to interpret it: value type, source, feed, session, timestamp, and freshness. 为 Grok 提供一个边界清晰的只读行情工具。它不仅返回价格,还返回解释价格所需的数值类型、来源、Feed、交易时段、时间戳和新鲜度。

Direct answer: 直接答案: Use xAI function calling to let Grok request a current quote. Your server validates the ticker, calls an entitled market-data provider, normalizes the result, and sends structured evidence back to Grok. The model never owns the provider key and never invents a missing quote. 使用 xAI 的函数调用让 Grok 请求当前行情。服务端负责校验代码、调用具备授权的数据源、标准化结果,再把结构化证据返回 Grok。模型不接触数据源密钥,也不补造缺失行情。
Architecture showing licensed market data passing through a secure server-side adapter into a Grok tool-call loop and a verified answer
The control loop keeps credentials, entitlements, normalization, and validation outside the model. 控制闭环把凭证、数据授权、标准化和校验留在模型之外。
Start with the contract 先定义契约

“Real-time” is a claim your system must prove “实时”是系统必须证明的声明

A fast response is not automatically a current quote. Before writing code, define the maximum acceptable age, covered venues, market session, price type, and fallback behavior for each user intent. 响应快不等于行情新。编码前应先按用户意图定义最大可接受数据年龄、覆盖交易场所、交易时段、价格类型和降级行为。

VALUE

Name the number 说清数值类型

Last trade, bid, ask, midpoint, and bar close answer different questions. Never flatten them into a generic “price.” 最新成交、买价、卖价、中间价和 K 线收盘价回答的是不同问题,不能统称为“股价”。

TIME

Carry two clocks 保留两套时间

Keep the provider event time and your retrieval time. Their difference exposes transport, cache, and processing delay. 同时保留数据源事件时间和系统获取时间,两者之差能暴露传输、缓存与处理延迟。

COVERAGE

State the feed 明确 Feed 覆盖

A single-venue feed and a consolidated SIP feed are both useful, but they are not equivalent views of the U.S. market. 单一交易所 Feed 与 SIP 综合行情都很有用,但它们不是等价的美股市场视图。

STATUS

Expose the session 披露交易时段

Regular, pre-market, after-hours, closed, and halted states change how a value should be described. 正常交易、盘前、盘后、休市和停牌状态都会改变数值的解释方式。

Reference control loop 参考控制闭环

How Grok gets real-time stock market data Grok 如何获取实时股票市场数据

Grok does not need direct access to provider credentials. It needs a clearly described function that your application executes whenever a question requires a current stock quote. Grok 不需要直接接触数据源凭证。它需要一个描述清晰的函数;当问题需要当前股票行情时,由你的应用执行该函数。

01 · INTENT

Resolve the request 解析请求

Identify symbol, exchange, value type, and whether “now” truly matters. 识别代码、交易所、数值类型,以及用户是否确实要求“当前”。

02 · CALL

Grok requests data Grok 请求数据

A JSON schema limits arguments and gives the model one read-only operation. JSON Schema 限制参数,并只向模型开放一个只读操作。

03 · EXECUTE

Server calls provider 服务端调用数据源

Validate input, apply entitlement policy, retrieve data, and keep secrets private. 校验输入、执行授权策略、获取数据,并保护密钥。

04 · VERIFY

Normalize evidence 标准化证据

Return stable fields and calculate freshness from real timestamps. 返回稳定字段,并依据真实时间戳计算数据新鲜度。

05 · ANSWER

Grok explains Grok 解释结果

The answer cites source, time, session, and limitations beside the value. 回答在数值旁说明来源、时间、时段和限制。

Implementation 实现方式

Add real-time stock quotes to Grok in five steps 五步为 Grok 接入实时股票行情

xAI documents custom function calling as a loop: define the tool, let Grok request it, execute it locally, return a function result, then ask the model to continue. Start with snapshots because they are bounded, testable, and match most conversational questions. xAI 官方文档把自定义函数调用描述为一个闭环:定义工具、由 Grok 发起调用、本地执行、返回函数结果,再让模型继续回答。建议先从快照开始,因为它边界明确、易测试,也适合多数对话查询。

STEP 1

Choose the quote evidence确定行情证据

Decide whether Grok should cite a last trade, bid, ask, or bar. Select a provider and feed whose entitlement, venue coverage, and delay match that claim.先确定 Grok 要引用最新成交、买价、卖价还是 K 线,再选择授权、交易场所覆盖与延迟水平符合要求的数据源和 Feed。

STEP 2

Define the Grok tool定义 Grok 工具

Expose a narrow get_stock_quote function with symbol, exchange, and value type. Describe exactly when Grok must call it.提供边界清晰的 get_stock_quote 函数,参数包括代码、交易所与数值类型,并明确 Grok 必须在何时调用。

STEP 3

Execute on the server在服务端执行

Validate arguments, read the provider key from a secret store, call the quote API, and reject ambiguous or unsupported instruments.校验参数,从密钥存储读取数据源凭证,调用行情 API,并拒绝有歧义或不受支持的标的。

STEP 4

Return structured freshness返回结构化新鲜度

Send Grok the value plus currency, event time, retrieval time, session, feed, source, and delay status as JSON.以 JSON 向 Grok 返回数值、币种、事件时间、获取时间、交易时段、Feed、来源和延迟状态。

STEP 5

Force evidence-aware wording要求证据化表达

Instruct Grok to name the value type and timestamp, disclose closed or delayed markets, and refuse to guess when the tool fails.要求 Grok 说明数值类型和时间戳,在休市或延迟时明确披露,并在工具失败时拒绝猜测。

Tool response contract 工具返回契约

  • Canonical symbol and exchange 规范化代码与交易所
  • Value, value type, and currency 数值、数值类型与币种
  • Provider event time and retrieved time 数据源事件时间与获取时间
  • Session, feed, source, and delay status 交易时段、Feed、来源和延迟状态
  • Explicit error instead of partial invention 明确报错,不用编造补齐

The official xAI function-calling guide confirms that your application executes custom functions and returns their results to the model. xAI 的函数调用官方指南明确说明:自定义函数由你的应用执行,再把结果返回模型。

tools = [{
  "type": "function",
  "name": "get_stock_quote",
  "description": "Get a current read-only stock quote",
  "parameters": {
    "type": "object",
    "properties": {
      "symbol": {"type": "string"},
      "exchange": {"type": "string"},
      "value_type": {
        "type": "string",
        "enum": ["last_trade", "bid", "ask"]
      }
    },
    "required": ["symbol", "value_type"]
  }
}]

response = client.responses.create(
  model=MODEL,
  input=[{"role":"user", "content": user_prompt}],
  tools=tools,
  tool_choice="auto"
)

# Execute requested calls on your server.
# Validate args; call your entitled provider.
quote = get_stock_quote(**args)

response = client.responses.create(
  model=MODEL,
  previous_response_id=response.id,
  tools=tools,
  input=[{
    "type": "function_call_output",
    "call_id": call_id,
    "output": json.dumps(quote)
  }]
)

What a trustworthy Grok stock answer looks like可信的 Grok 股票行情回答应包含什么

Illustrative format: “XYZ last traded at 123.45 USD at 14:32:08 America/New_York during the regular session. Source: Example Provider, Example Feed. Retrieved at 14:32:09. Freshness status: within the configured threshold.”示意格式:“XYZ 最新成交价为 123.45 USD,成交时间为 America/New_York 14:32:08,处于正常交易时段。来源:示例数据源、示例 Feed;系统获取时间为 14:32:09;新鲜度状态:符合当前阈值。”

These values are fictional and demonstrate response structure only. Production values must come from the tool result.以上数值均为虚构,仅用于展示回答结构;生产环境中的数值必须来自工具返回结果。

Illustrative code: use a currently supported Grok model from xAI documentation and your provider's official SDK or HTTP API. Do not copy credentials into prompts or client-side code. 示意代码:请根据 xAI 当前文档选用受支持的 Grok 模型,并使用数据源官方 SDK 或 HTTP API。不要把凭证写入提示词或客户端代码。

Snapshot or stream? 快照还是数据流?

Match transport to the decision—not to the word “live” 按决策选择传输方式,而不是看到“实时”就上流式

User need 用户需求 Best pattern 推荐模式 What Grok receives Grok 接收内容 Main control 关键控制
“What is the current quote?” “当前行情是多少?” REST/latest snapshot REST / 最新快照 One bounded evidence object 一个有边界的证据对象 Maximum age and session 最大数据年龄与交易时段
Watch a threshold 监控阈值 WebSocket → rule engine WebSocket → 规则引擎 Only the triggered event 仅发送触发事件 Deduplication and cooldown 去重与冷却时间
Summarize an intraday move 总结日内走势 Validated interval bars 已校验的周期 K 线 Compact series plus metadata 紧凑序列与元数据 Partial-bar and timezone labels 未完成 K 线与时区标记
Compare historical performance 比较历史表现 Historical API 历史数据 API Requested range only 仅返回请求区间 Adjustment and missing sessions 复权与缺失交易日

Alpaca's official documentation says streaming is better suited than polling historical endpoints for the latest data and distinguishes IEX, SIP, delayed SIP, and other feeds. Review its real-time stock WebSocket documentation and market-data FAQ before claiming coverage or recency. Alpaca 官方文档指出,若要获取最新数据,流式方式通常比轮询历史端点更合适;文档也区分了 IEX、SIP、延迟 SIP 等 Feed。在声明覆盖范围或新鲜度前,请核对其实时股票 WebSocket 文档行情 FAQ

Production guardrails 生产防护

Make wrong answers harder than honest failures 让诚实失败比错误回答更容易发生

Keep it read-only 保持只读

Separate quotes from orders. A request for analysis must never become permission to trade. 把行情查询与下单分离。分析请求绝不等于交易授权。

Bound symbols and calls 限制代码和调用量

Cap batch size, normalize ticker syntax, reject ambiguous listings, and rate-limit by user and workspace. 限制批量规模、规范代码格式、拒绝歧义标的,并按用户和工作区限流。

Protect credentials 保护凭证

Store provider keys server-side, redact headers from logs, scope access, and rotate secrets. 数据源密钥只保存在服务端;日志隐藏请求头,并限制权限、定期轮换。

Fail closed on freshness 新鲜度不明时保守失败

If timestamps, feed identity, or delay state are missing, Grok should say the quote cannot be verified as current. 若缺少时间戳、Feed 身份或延迟状态,Grok 应说明无法验证行情是否为当前数据。

Control fallbacks 控制降级数据源

A fallback with narrower coverage or greater delay must be labeled; never present providers as interchangeable. 备用源若覆盖更窄或延迟更高,必须显式标注,不能假装数据源完全等价。

Minimize private context 减少私密上下文

Do not send portfolios, account IDs, or strategy text when the provider only needs a ticker. 若数据源只需要股票代码,就不要发送持仓、账户 ID 或策略文本。

Release test 上线测试

Test the evidence path, not just HTTP 200 测试完整证据链,不要只看 HTTP 200

Market cases 市场场景

  • Regular, pre-market, after-hours, weekend, and holiday 正常交易、盘前、盘后、周末和节假日
  • Halted, inactive, renamed, and ambiguous symbols 停牌、失效、更名和有歧义的代码
  • IEX versus consolidated-feed expectations IEX 与综合 Feed 的预期差异
  • Trade, quote, and incomplete bar interpretation 成交、Quote 与未完成 K 线的解释

System cases 系统场景

  • Timeout, rate limit, entitlement error, and empty result 超时、限流、授权错误和空结果
  • Malformed tool arguments and oversized symbol lists 异常工具参数和超大代码列表
  • Provider timestamp older than the freshness contract 数据源时间戳超过新鲜度阈值
  • Equivalent English and Chinese market questions 含义等价的中英文行情问题

Acceptance rule 验收规则

Every successful answer preserves symbol, exchange, value type, currency, source, feed, session, and time. Every failed retrieval produces a clear limitation—never a remembered or invented price. 每个成功回答都要保留代码、交易所、数值类型、币种、来源、Feed、交易时段和时间;每次获取失败都要明确说明限制,绝不能使用记忆价格或编造价格。

FAQ 常见问题

Real-time stock data for Grok: practical answers Grok 实时股票数据:实用问答

Does Grok include a licensed real-time stock feed? Grok 是否自带授权的实时股票行情?

Do not assume model knowledge or web search is a licensed real-time quote feed. For verifiable prices, connect an entitled provider through a custom function and return the source, timestamp, session, and delay status. 不要把模型知识或网页搜索视为获得授权的实时行情 Feed。若要给出可验证价格,应通过自定义函数连接具备数据授权的服务商,并返回来源、时间戳、交易时段和延迟状态。

Should Grok receive every WebSocket tick? 是否应该把每个 WebSocket Tick 都发送给 Grok?

No. Ingest the stream in application code, maintain a bounded current state, and give Grok a snapshot or event summary only when it calls the tool. 不应该。流数据应由应用代码接收并维护为边界明确的当前状态;只有在 Grok 调用工具时,才返回快照或事件摘要。

What should a Grok quote tool return? Grok 行情工具应该返回哪些字段?

Return the resolved instrument, value type, price, currency, provider timestamp, retrieval time, market session, feed, source, and explicit freshness status. 应返回已解析标的、数值类型、价格、币种、数据源时间戳、系统获取时间、交易时段、Feed、来源和明确的新鲜度状态。

Can the same tool place trades? 同一个工具能否同时下单?

Keep market-data retrieval read-only. Trading should use a separate, tightly authorized action with explicit confirmation, deterministic risk checks, idempotency, and an audit trail. 行情获取应保持只读。交易必须使用独立且严格授权的操作,并包含明确确认、确定性风险检查、幂等控制和审计记录。

Build a verifiable path 构建可验证链路

Give Grok current data without giving up control 让 Grok 获取当前数据,同时保留系统控制权

Start with one read-only quote tool, one explicit freshness contract, and one test set that rewards honest failure. Use QVeris to inspect data tools and test the agent workflow before production. 从一个只读行情工具、一份明确的新鲜度契约和一套鼓励诚实失败的测试集开始。上线前,可用 QVeris 检查数据工具并测试 Agent 工作流。