QVeris
Gemini API + Gemini CLI tutorialGemini API + Gemini CLI 教程

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

Give Gemini current quotes by connecting a licensed market-data source through Gemini API function calling or a Gemini CLI MCP server. Gemini chooses the tool; your application retrieves and validates the data.通过 Gemini API 函数调用或 Gemini CLI MCP Server 连接具备授权的行情源,让 Gemini 获取当前报价。Gemini 负责选择工具,应用负责查询与校验数据。

Short answer:简短答案: Gemini is not a stock feed. Define a read-only quote tool, execute it outside the model, then return the price together with exchange, currency, session, source, delay class, and provider timestamp.Gemini 本身不是股票行情源。你需要定义一个只读报价工具,在模型之外执行查询,并把价格连同交易所、币种、交易时段、来源、延迟类别和数据源时间戳一起返回。
Gemini function calling routes a stock question through a secure tool gateway to current market data
The model requests data; a controlled tool performs the market lookup.模型发起数据请求,受控工具执行行情查询。
Pick the Gemini surface选择 Gemini 接入面

Use function calling in an app, or MCP in Gemini CLI应用使用函数调用,Gemini CLI 使用 MCP

These routes solve different deployment problems. Do not combine them unless the same product genuinely supports both an API application and an interactive developer workflow.两条路径对应不同的部署场景。只有产品同时包含 API 应用和交互式开发工作流时,才需要同时采用。

GEMINI API

Function calling for production applications生产应用使用函数调用

Declare a narrow function such as get_stock_quote. Gemini returns structured arguments; your backend validates the symbol, calls the provider, and sends the function result back for a final answer. Google’s documentation explicitly places function execution in application code, not inside the model.声明一个边界清晰的函数,例如 get_stock_quote。Gemini 返回结构化参数;后端校验股票代码、调用数据源,再把函数结果发回模型生成最终回答。Google 官方流程明确指出,函数由应用代码执行,而不是由模型直接执行。

Open the official Gemini API flow查看 Gemini API 官方流程
GEMINI CLI

MCP for an interactive agent交互式 Agent 使用 MCP

Register a market-data MCP server in Gemini CLI. The CLI discovers its tools and exposes their schemas to Gemini. Keep the server untrusted until you have inspected it, pass secrets through environment variables, and include only read-only tools needed for research.在 Gemini CLI 中注册市场数据 MCP Server。CLI 会发现工具并把 Schema 提供给 Gemini。检查完成前不要授予信任;密钥通过环境变量传入,并且只开放研究需要的只读工具。

Follow the official Gemini CLI MCP tutorial按照 Gemini CLI 官方 MCP 教程配置
Gemini API implementationGemini API 实现

Build the two-turn quote loop构建两轮行情调用循环

The critical Gemini-specific detail is the function-call round trip: the first model response asks for a function; the second receives the verified result. Never let the model invent the execution result.Gemini 接入的关键是函数调用往返:第一轮由模型请求函数,第二轮接收经过校验的结果。绝不能让模型自行编造执行结果。

1Send the user request plus the quote declaration.发送用户问题和报价函数声明。
2Read Gemini’s function name and arguments.读取 Gemini 返回的函数名与参数。
3Validate and execute the provider request server-side.在服务端校验并执行数据源请求。
4Return the function result to Gemini for wording.把函数结果交回 Gemini 组织回答。

A useful function declaration实用的函数声明

{
  "type": "function",
  "name": "get_stock_quote",
  "description": "Get a current read-only stock quote",
  "parameters": {
    "type": "object",
    "properties": {
      "symbol": {"type": "string"},
      "exchange": {"type": "string"}
    },
    "required": ["symbol"]
  }
}

What your executor must decide执行器必须完成的判断

  • Resolve ambiguous symbols before querying.查询前解决股票代码歧义。
  • Reject unsupported exchanges and oversized batches.拒绝不支持的交易所和超大批量请求。
  • Apply provider credentials, timeout, retry, and entitlement rules.执行数据源凭据、超时、重试和授权规则。
  • Return structured errors rather than an empty “success.”返回结构化错误,而不是空白的“成功”结果。
Gemini CLI implementationGemini CLI 实现

Connect a read-only market MCP server连接只读市场数据 MCP Server

Gemini CLI stores MCP definitions in its settings and can verify connections with its MCP commands. For QVeris, start by reading the current server documentation rather than copying an unverified package command from an older page.Gemini CLI 会在设置中保存 MCP 定义,并可通过 MCP 命令验证连接。接入 QVeris 时,应先查看当前 Server 文档,不要从旧页面复制未经验证的软件包命令。

Configuration sequence配置顺序

  1. Create a read-only QVeris or provider credential.创建只读的 QVeris 或数据源凭据。
  2. Add the MCP server using the current documented command, URL, or settings block.按照最新文档,通过命令、URL 或 settings 配置加入 MCP Server。
  3. Run gemini mcp list or /mcp list and confirm it connects.运行 gemini mcp list/mcp list,确认连接成功。
  4. Inspect available tools before allowing a quote call.允许行情调用前先检查可用工具。

A focused verification prompt聚焦的验证提示词

“Find a read-only quote tool for AAPL. Before calling it, show the selected tool and required parameters. Return exchange, currency, session, source, delay status, and provider timestamp. Do not trade.”“查找可查询 AAPL 当前行情的只读工具。调用前先显示所选工具和必需参数。返回交易所、币种、交易时段、来源、延迟状态和数据源时间戳。不要执行交易。”

Check the current QVeris MCP server documentation查看最新 QVeris MCP Server 文档

Data contract数据契约

Return evidence Gemini can preserve返回 Gemini 可以保留的证据

A bare price is not enough for a current-market answer. Normalize the provider payload before it enters the model context.只有价格不足以支撑当前行情回答。数据进入模型上下文前,应先规范化数据源载荷。

Field字段 Why Gemini needs itGemini 为什么需要 Failure to prevent需要避免的问题
symbol + exchange Identifies the instrument unambiguously.明确标的身份。 Answering for the wrong venue.回答了错误市场的标的。
price + currency Preserves value and unit together.同时保留数值与单位。 Assuming every quote is USD.误把所有价格当成美元。
as_of + timezone States when the provider observed the quote.说明数据源观测行情的时间。 Presenting an old value as current.把旧数据说成当前数据。
session Separates regular, pre-market, after-hours, and closed.区分正常交易、盘前、盘后与休市。 Comparing incompatible session values.比较不同时段的不可比价格。
source + delay_status Makes provenance and freshness explicit.明确来源与新鲜度。 Calling delayed data “real time.”把延迟行情称为实时行情。
“Real time” is an entitlement claim.“实时”是一项授权声明。

Confirm the exchange, feed, account plan, endpoint, and display rights. Technical API access alone does not prove that the returned quote is real-time or redistributable. Alpaca’s official documentation is one example of a provider explaining feed and subscription differences.需要核查交易所、Feed、账户套餐、端点与展示权利。能够调用 API,并不代表返回数据一定实时或允许再分发。Alpaca 官方文档就是数据源说明 Feed 与订阅差异的一个例子。 Review an official real-time feed explanation查看官方实时 Feed 说明

Quote modes行情模式

Match the market-data path to the Gemini task让行情路径匹配 Gemini 的具体任务

“Real-time stock market data for Gemini” can describe three very different workloads. Choosing the wrong one either wastes provider calls or gives the model more data than it can use responsibly.“Gemini 实时股票市场数据”可能对应三类完全不同的工作负载。选错模式,要么浪费数据源调用,要么向模型塞入超出其可靠处理范围的数据。

ON-DEMAND SNAPSHOT按需快照

One question, one bounded quote一个问题,一次有限查询

Use a REST-style quote function when a user asks for the current price, day range, volume, or market status of a small number of symbols. This is the default pattern for Gemini chat experiences because the tool result is compact, auditable, and easy to associate with one answer.当用户查询少量股票的当前价格、日内区间、成交量或市场状态时,使用 REST 风格的报价函数。这是 Gemini 对话体验的默认模式,因为工具结果紧凑、可审计,也容易与单次回答对应。

SCHEDULED BRIEF定时简报

Fetch first, summarize second先获取,再总结

For opening, closing, or portfolio briefs, let a scheduler collect an approved symbol set and normalize the results before Gemini sees them. The model should summarize a completed batch—not decide silently to expand one prompt into hundreds of billable requests.对于开盘、收盘或组合简报,应由调度器先查询批准的股票集合并规范化结果,再交给 Gemini。模型负责总结已完成的批次,而不是悄悄把一个提示词扩展为数百次付费请求。

STREAMING ALERT流式告警

Keep ticks outside model context不要把每个 Tick 塞进模型

For WebSocket feeds, a deterministic service should maintain state, calculate thresholds, deduplicate events, and emit only meaningful alerts. Call Gemini after a trigger to explain context or draft a notification. An LLM is not the place to calculate every price change in a high-frequency stream.对于 WebSocket Feed,应由确定性服务维护状态、计算阈值、去重事件,只输出有意义的告警。触发后再调用 Gemini 解释背景或撰写通知。高频数据流中的每次价格变化不应交给 LLM 计算。

Gemini tool lifecycleGemini 工具生命周期

Control every boundary around the model call控制模型调用前后的每一道边界

A reliable integration is a stateful application workflow, not a clever prompt. Each boundary has a different owner and a different failure response.可靠接入是有状态的应用工作流,而不是一段巧妙的 Prompt。每个边界都有不同的责任方和失败处理方式。

01

Classify freshness intent识别实时意图

Distinguish “explain P/E ratio” from “what is the price now?” Current, latest, today, pre-market, after-hours, open, close, and market-status language should make the quote function available. Historical education questions may not need a live call.区分“解释市盈率”和“现在股价是多少”。当前、最新、今天、盘前、盘后、开盘、收盘和市场状态等表达应触发行情函数;历史知识类问题未必需要实时调用。

02

Constrain Gemini’s arguments约束 Gemini 生成的参数

Use enums and narrow descriptions where the market universe is known. Treat Gemini’s function arguments as untrusted input: trim symbols, enforce list limits, resolve venue identifiers, and reject unexpected fields before any provider request.如果已知市场范围,应使用枚举和边界清晰的描述。Gemini 生成的函数参数仍是不可信输入:调用数据源前要清理代码、限制列表数量、解析市场标识并拒绝异常字段。

03

Execute with deterministic policy按确定性策略执行

The backend selects credentials, endpoint, timeout, cache policy, retry count, and fallback. Those decisions should not be delegated to natural-language reasoning. Record which provider and entitlement produced the value.后端决定凭据、端点、超时、缓存、重试次数和降级策略,这些决策不应交给自然语言推理。还要记录具体数据源和授权层级。

04

Return a bounded function result返回有限的函数结果

Send Gemini only the fields needed to answer the question, plus traceability metadata. Keep raw provider payloads in application logs when permitted. Large trade histories, full order books, and redundant fields increase cost and make omissions harder to notice.只把回答所需字段和追踪元数据发给 Gemini。在许可范围内,把原始数据源载荷保存在应用日志中。庞大的成交历史、完整订单簿和冗余字段会增加成本,也更容易掩盖关键缺失。

05

Constrain the final wording约束最终回答

Require the answer to show the resolved instrument, value, currency, timestamp with timezone, session, source, and delay label. If any required evidence is missing, Gemini should say what cannot be verified instead of repairing the gap with model knowledge.要求回答展示已解析标的、数值、币种、带时区时间戳、交易时段、来源和延迟标签。如果关键证据缺失,Gemini 应说明无法验证的部分,而不是用模型知识补齐空白。

06

Store an auditable trace保存可审计轨迹

Link the user request, Gemini function call, validated parameters, provider response ID, retrieval time, final answer, and error state. Redact secrets and sensitive portfolio details. This trace is what lets an operator explain a disputed quote later.关联用户请求、Gemini 函数调用、校验后参数、数据源响应 ID、获取时间、最终回答和错误状态;同时隐藏密钥和敏感持仓信息。这条轨迹使运维人员日后可以解释有争议的行情。

Production controls生产控制

Balance freshness, latency, cost, and rights平衡新鲜度、延迟、成本与数据权利

Control控制项 Implementation pattern实现方式 Decision to document需要记录的决策
Freshness新鲜度 Set a maximum acceptable age per intent and market session.按意图和交易时段设置最大可接受数据年龄。 When may cache be used, and how is cache age disclosed?何时允许使用缓存,怎样披露缓存年龄?
Latency延迟 Use bounded timeouts and one controlled retry for transient failures.设置明确超时,对暂时性故障只进行有限重试。 Does Gemini wait, return partial evidence, or state failure?Gemini 应等待、返回部分证据,还是明确失败?
Cost成本 Cap symbols, deduplicate calls, batch safely, and monitor calls per conversation.限制股票数量、去重调用、安全批处理并监控每次对话的调用数。 Which requests require confirmation before a broad scan?哪些大范围扫描必须先获得确认?
Fallback降级 Normalize alternate providers but preserve their identity and delay class.规范化备用数据源,同时保留其身份与延迟类别。 Which differences make two feeds non-equivalent?哪些差异意味着两个 Feed 不能等同?
Data rights数据权利 Scope use by display, caching, derived output, logging, and redistribution terms.按展示、缓存、衍生输出、日志和再分发条款限制使用。 May the Gemini answer be shown externally or stored?Gemini 的回答能否对外展示或保存?
Failure modes故障模式

Why Gemini gives the wrong “live” stock answerGemini 为什么会给出错误的“实时”股票回答

Most failures happen outside model intelligence: ambiguous identity, incomplete metadata, incorrect entitlement assumptions, or an application that accepts a malformed tool result.多数问题并不是模型智力不足,而是标的身份歧义、元数据缺失、授权假设错误,或应用接受了异常的工具结果。

Gemini answers without a tool callGemini 没调用工具就回答

The function description may not mention current-price intent, or the application may allow a normal text response when a live call is mandatory. Add explicit trigger cases to tests and reject unsupported current-price answers at the application layer.函数描述可能没有覆盖当前价格意图,或者应用在必须实时查询时仍接受普通文本回答。应在测试中加入明确触发用例,并由应用层拒绝没有数据支持的当前价格回答。

The right ticker, wrong market代码正确,市场错误

Ticker strings are not globally unique. Resolve exchange, country, asset type, and share class. When confidence is low, return candidates to Gemini so it can ask the user a precise clarification question.股票代码并非全球唯一。应解析交易所、国家、资产类型和股类。置信度不足时,把候选项返回 Gemini,让它提出明确的澄清问题。

A previous close is labeled live昨收被标成实时价格

Providers may return a valid value even when the market is closed or the account lacks a live feed. Preserve the field’s meaning and session. Never infer freshness merely because the HTTP request completed now.休市或账户没有实时 Feed 时,数据源仍可能返回有效数值。必须保留字段含义与交易时段,不能因为 HTTP 请求刚刚完成就推断数据是实时的。

Provider failure becomes a fluent guess数据源失败后生成了流畅猜测

Convert timeout, rate limit, not-entitled, invalid-symbol, and empty-result states into explicit function errors. The final Gemini instruction should prohibit substituting memory when any current-data request fails.把超时、限流、未授权、无效代码和空结果转换为明确的函数错误。最终 Gemini 指令应禁止在当前数据请求失败时用记忆替代。

Gemini test matrixGemini 测试矩阵

Test tool selection and grounded wording同时测试工具选择与有据可依的表达

Must call the tool必须调用工具

“What is AAPL trading at now?” “Latest TSLA price.” “How did NVDA move after hours?” Verify that Gemini requests a tool instead of answering from memory.“AAPL 现在多少钱?”“TSLA 最新价格。”“NVDA 盘后怎么走?”应验证 Gemini 发起工具调用,而不是凭记忆回答。

Must clarify必须追问

Test duplicate tickers, company names without an exchange, and prompts such as “that stock.” Gemini should ask for the missing identity rather than guess.测试重复代码、缺少交易所的公司名称以及“那只股票”等表达。Gemini 应询问缺失信息,不能猜测。

Must fail honestly必须诚实失败

Simulate timeout, rate limit, missing entitlement, market halt, and a result without a timestamp. The answer must name the limitation and must not manufacture a quote.模拟超时、限流、未授权、停牌和缺少时间戳的结果。回答必须说明限制,不能编造价格。

Acceptance rule验收规则

Pass only when the final Gemini answer preserves the provider’s symbol, exchange, price, currency, timestamp, session, source, and delay status exactly—and labels hypothetical examples as examples.只有最终回答准确保留数据源返回的股票代码、交易所、价格、币种、时间戳、交易时段、来源与延迟状态,并明确标注假设示例时,才算通过。

Launch checklist上线检查

Prove the Gemini stock-data loop in staging在预发布环境证明 Gemini 行情闭环可靠

A successful demo with one liquid U.S. ticker is not a release test. Use a compact, repeatable suite that covers identity, market time, provider behavior, and the model’s final wording.用一只高流动性美股完成演示并不等于可以上线。应使用精简、可重复的测试集,覆盖标的身份、市场时间、数据源行为与模型最终表达。

Before release上线前

  • Run regular-session, pre-market, after-hours, weekend, holiday, and halted-symbol cases.测试正常交易、盘前、盘后、周末、节假日和停牌标的。
  • Verify duplicate tickers across exchanges and invalid or delisted symbols.验证跨交易所重名代码、无效代码和退市标的。
  • Force timeout, rate-limit, not-entitled, partial, and stale-cache responses.强制触发超时、限流、未授权、部分结果和过期缓存。
  • Compare English and Chinese prompts that express the same current-price intent.比较表达相同实时价格意图的中英文提示词。

After release上线后

  • Track tool-selection rate for prompts labeled as current-data requests.跟踪被标注为当前数据请求的提示词工具选择率。
  • Measure provider latency separately from Gemini generation latency.分别测量数据源延迟和 Gemini 生成延迟。
  • Count missing timestamp, source, session, and delay fields before results reach users.在结果到达用户前统计缺少时间戳、来源、时段和延迟字段的情况。
  • Re-run acceptance tests after changing the model, tool description, provider, schema, or cache policy.更换模型、工具描述、数据源、Schema 或缓存策略后重新执行验收测试。
Release gate:上线门槛: every supported market has a documented freshness definition; every successful quote is traceable; every tested provider failure produces an honest, non-numeric answer.每个支持市场都有明确的新鲜度定义;每条成功行情都可追踪;每种已测试的数据源故障都能得到诚实且不编造数字的回答。
Decision guide决策指南

Choose the smallest integration that fits选择满足需求的最小接入方案

Building a website or app?正在构建网站或应用?

Use Gemini API function calling. Your backend controls credentials, execution, caching, and logging.使用 Gemini API 函数调用,由后端控制凭据、执行、缓存和日志。

Working inside Gemini CLI?在 Gemini CLI 中工作?

Use a reviewed MCP server and expose only the quote tools required by the workflow.使用经过检查的 MCP Server,并且只开放工作流需要的行情工具。

Need continuous ticks?需要连续 Tick?

Keep WebSocket ingestion outside Gemini. Aggregate the stream and call the model only for selected events or summaries.把 WebSocket 摄取留在 Gemini 之外。先聚合数据流,只在选定事件或摘要场景调用模型。

FAQ常见问题

Real-time stock market data for GeminiGemini 实时股票市场数据常见问题

Does Gemini have built-in real-time stock prices?Gemini 内置实时股票价格吗?

Do not treat Gemini itself as a licensed market-data feed. For a verifiable current quote, connect an external provider through function calling or MCP and disclose its source and timestamp.不要把 Gemini 本身当作具备授权的行情 Feed。若需要可验证的当前报价,应通过函数调用或 MCP 连接外部数据源,并披露来源和时间戳。

Should I use Gemini function calling or MCP?应该使用 Gemini 函数调用还是 MCP?

Use function calling when you own an application backend. Use MCP when Gemini CLI or another MCP-capable client needs to discover and call the market tool interactively.如果你控制应用后端,使用函数调用;如果 Gemini CLI 或其他 MCP 客户端需要交互式发现和调用行情工具,则使用 MCP。

Can Gemini consume WebSocket stock data directly?Gemini 可以直接消费 WebSocket 股票数据吗?

A production system should ingest, filter, and aggregate the stream outside the model. Send Gemini a bounded snapshot or event payload rather than every tick.生产系统应在模型之外摄取、过滤和聚合数据流,再向 Gemini 发送有限的快照或事件载荷,而不是每个 Tick。

Can Gemini place a trade after reading a quote?Gemini 读取行情后可以下单吗?

Keep this guide’s quote tool read-only. Trading requires a separate action tool, stronger authentication, deterministic risk checks, idempotency, audit logs, and explicit human confirmation.本指南中的报价工具应保持只读。交易需要独立动作工具、更强认证、确定性风险检查、幂等控制、审计日志和明确的人工确认。

Next step下一步

Test one timestamped quote in Gemini先在 Gemini 中测试一条带时间戳的行情

Start with one symbol and a read-only tool. Confirm the selected capability, inspect its parameters, and reject any response that lacks source or freshness metadata.从一个股票代码和一个只读工具开始。确认所选能力、检查参数,并拒绝任何缺少来源或新鲜度元数据的结果。