QVeris
DeepSeek implementation guideDeepSeek 实施指南

Real-Time Stock Market Data for DeepSeekDeepSeek 实时股票市场数据接入

Give DeepSeek a narrow quote function, execute it outside the model, and return a source-aware data envelope that makes stale or unverifiable answers impossible to pass silently.为 DeepSeek 提供边界清晰的行情函数,在模型外执行查询,并返回带来源与新鲜度的数据封装,让过期或无法验证的答案不能悄然通过。

Short answer:简要答案: DeepSeek can decide when to call a stock-data tool, but your application must supply and execute that tool. The market-data provider—not model memory—is the source of the price.DeepSeek 可以决定何时调用行情工具,但工具能力与执行过程必须由你的应用提供。价格的事实来源是外部行情服务,而不是模型记忆。
DeepSeek request routed through a secure tool gateway to external market data and returned as a verified answer
The model requests data; deterministic application code validates, retrieves, and labels it.模型负责请求数据;确定性的应用代码负责校验、获取和标注数据。
Prerequisites准备工作

What you need before the first DeepSeek quote第一次让 DeepSeek 查询行情前需要准备什么

Keep the model credential and market-data credential on the server. The browser or mobile client should call your backend, never either vendor directly with embedded secrets.DeepSeek 密钥和行情服务密钥都应保存在服务端。浏览器或移动客户端只能调用你的后端,不能携带密钥直接访问任何服务商。

Runtime and credentials运行环境与凭据

  • Python 3.10+ and a virtual environmentPython 3.10+ 与虚拟环境
  • A DeepSeek API key stored as DEEPSEEK_API_KEY通过 DEEPSEEK_API_KEY 保存 DeepSeek API key
  • An entitled, documented market-data source or a QVeris account具备授权与文档的行情源,或 QVeris 账户
  • A server-side secret manager for production生产环境使用服务端密钥管理器

Install the minimal client安装最小客户端

python -m venv .venv
# activate .venv for your shell
python -m pip install openai httpx

The DeepSeek API is compatible with the OpenAI client pattern used below. httpx is only for the example provider adapter; use the official SDK if your chosen feed requires one.下文通过 OpenAI 客户端兼容方式调用 DeepSeek API。httpx 仅用于示例行情适配器;如果所选数据源要求官方 SDK,应以其文档为准。

Start with the contract先明确契约

“Real time” is a policy, not a prompt adjective“实时”是一项策略,不是提示词里的形容词

A request completed now can still return a delayed quote, a previous close, or an old cache entry. Before writing code, decide which instruments, sessions, feeds, delay classes, and maximum ages are acceptable for each user experience.刚完成的 HTTP 请求仍可能返回延迟行情、前收盘价或旧缓存。写代码前,应先明确每种用户场景允许哪些标的、交易时段、数据源、延迟等级和最大数据年龄。

FRESHNESS

Set an age threshold设定数据年龄阈值

Compare the provider’s event timestamp with retrieval time. Do not infer freshness from request completion. A watchlist may tolerate a short cache; a user asking “now” may require a stricter rule.比较行情事件时间与获取时间,不能根据请求刚结束就推断数据新鲜。观察列表可以接受短暂缓存,而用户询问“现在”时可能需要更严格的规则。

IDENTITY

Resolve more than a ticker不能只解析股票代码

A symbol may be ambiguous across venues. Resolve exchange, asset class, country, and share class. If confidence is insufficient, return candidates and let DeepSeek ask a focused clarification.同一代码可能对应不同市场。应解析交易所、资产类别、国家和股类;置信度不足时返回候选项,让 DeepSeek 精确追问。

ENTITLEMENT

Preserve the feed label保留数据授权标签

Provider plans and exchange rights determine what “live” means. Carry the provider, feed, session, and delay status through the tool result instead of letting the model invent a label.服务套餐与交易所授权决定“实时”的实际含义。工具结果应保留服务商、Feed、交易时段和延迟状态,不能让模型自行生成标签。

Responsibility map职责地图

Keep DeepSeek away from credentials and raw streams让 DeepSeek 远离密钥与原始数据流

01

Intent意图

DeepSeek detects a current-data request and proposes structured arguments.DeepSeek 识别当前数据意图并生成结构化参数。

02

Guard防护

Your backend validates symbols, fields, limits, and user policy.后端校验标的、字段、数量限制与用户策略。

03

Retrieve获取

A server-side adapter selects and calls the entitled market feed.服务端适配器选择并调用已授权行情源。

04

Normalize标准化

The adapter returns stable fields plus timestamps and error state.适配器返回稳定字段、时间戳与错误状态。

05

Explain解释

DeepSeek summarizes only the supplied evidence and names its limits.DeepSeek 只基于返回证据总结,并说明限制。

Continuous ticks stay outside the LLM连续 Tick 应留在大模型之外

If the application consumes a WebSocket feed, ingest and aggregate it in a normal streaming service. Send DeepSeek a bounded snapshot or selected event. Token-by-token generation is not a market-data transport.如果应用消费 WebSocket 行情,应由普通流处理服务完成摄取与聚合,再向 DeepSeek 发送有限快照或筛选后的事件。逐 Token 生成不是行情传输机制。

Quote envelope行情封装

Return evidence, not just a number返回证据,而不只是一个数字

A bare price is difficult to verify. Use one normalized envelope for success, stale data, ambiguous instruments, missing entitlement, timeout, and provider failure.单独一个价格很难验证。应使用统一封装表达成功、过期、标的歧义、未授权、超时和服务商故障。

Required semantics必备语义

  • Resolved symbol, venue, asset type, and currency已解析代码、市场、资产类型和币种
  • Price meaning: trade, bid, ask, midpoint, or close价格含义:成交、买价、卖价、中间价或收盘价
  • Provider event time and application retrieval time数据源事件时间和应用获取时间
  • Market session, source, feed, and delay class交易时段、来源、Feed 与延迟等级
  • Machine-readable status and error code机器可读状态与错误码
{
  "status": "ok",
  "instrument": {"symbol": "EXAMPLE", "exchange": "VENUE"},
  "quote": {"value": "provider_value", "field": "last_trade",
            "currency": "USD"},
  "freshness": {
    "provider_time": "ISO-8601",
    "retrieved_at": "ISO-8601",
    "session": "regular",
    "delay": "provider_label"
  },
  "source": {"provider": "provider_name",
             "feed": "entitled_feed"}
}

Illustrative schema only: field names and meanings must be mapped to the selected provider’s official documentation.以上仅为示意 Schema;字段名称与含义必须按所选服务商的官方文档映射。

Python implementationPython 实现

Force the tool when freshness is non-negotiable新鲜度不可妥协时,强制调用工具

DeepSeek’s official API exposes function tools. The model returns function arguments; your code executes the function and sends its result back. DeepSeek’s documentation explicitly notes that the model does not execute the function itself.DeepSeek 官方 API 支持函数工具。模型返回函数参数,由你的代码执行函数并把结果送回;官方文档明确指出,具体函数并不是由模型自行执行。

import json
from openai import OpenAI

client = OpenAI(api_key=DEEPSEEK_API_KEY,
                base_url="https://api.deepseek.com")

tools = [{
  "type": "function",
  "function": {
    "name": "get_current_stock_quote",
    "description": "Get a current, read-only stock quote.",
    "parameters": {
      "type": "object",
      "properties": {
        "symbol": {"type": "string"},
        "exchange": {"type": "string"}
      },
      "required": ["symbol"],
      "additionalProperties": False
    }
  }
}]

messages = [
  {"role": "system", "content":
   "For current market facts, use the quote tool. Never substitute memory. "
   "State source, provider timestamp, session, and delay status."},
  {"role": "user", "content": user_question}
]

first = client.chat.completions.create(
  model="deepseek-v4-pro",
  messages=messages, tools=tools,
  tool_choice="required"
).choices[0].message

args = json.loads(first.tool_calls[0].function.arguments)
quote = execute_validated_quote(args)  # your server-side code
messages += [first, {
  "role": "tool",
  "tool_call_id": first.tool_calls[0].id,
  "content": json.dumps(quote)
}]

answer = client.chat.completions.create(
  model="deepseek-v4-pro", messages=messages, tools=tools
).choices[0].message.content

Validate generated arguments校验模型生成的参数

Treat arguments as untrusted input. Parse JSON, reject unexpected keys, normalize case, cap list lengths, resolve venue ambiguity, and apply authorization before contacting a provider. The API reference warns that generated arguments may be invalid or contain hallucinated parameters.把参数视为不可信输入:解析 JSON、拒绝未知字段、统一大小写、限制列表长度、处理交易所歧义,并在访问服务商前执行授权。官方 API 参考也提醒,生成参数可能无效或包含虚构字段。

Use auto selectively有选择地使用 auto

Use auto when the same assistant handles stable educational questions and current-data questions. At the application layer, classify hard freshness intent and require the tool for those requests.同一助手同时处理稳定知识和当前数据时,可以使用 auto。但应用层应识别强实时意图并强制调用工具。

+
Replace the placeholder替换占位函数

A provider adapter with validation and freshness checks带参数校验与新鲜度检查的行情适配器

The endpoint and response fields below are intentionally generic. Map them to the official documentation and entitlement of the provider you actually select; do not copy field names blindly.下面的端点和返回字段刻意保持通用。请按实际选择的数据源官方文档与授权范围完成映射,不要直接照抄字段名。

import os, re
from datetime import datetime, timezone
import httpx

SYMBOL = re.compile(r"^[A-Z][A-Z0-9.-]{0,14}$")

def execute_validated_quote(arguments):
    symbol = str(arguments.get("symbol", "")).strip().upper()
    exchange = str(arguments.get("exchange", "")).strip().upper() or None
    if not SYMBOL.fullmatch(symbol):
        return {"status": "error", "code": "invalid_symbol"}

    response = httpx.get(
        os.environ["MARKET_DATA_URL"],
        params={"symbol": symbol, "exchange": exchange},
        headers={"Authorization": "Bearer " + os.environ["MARKET_DATA_API_KEY"]},
        timeout=4.0
    )
    response.raise_for_status()
    raw = response.json()

    provider_time = datetime.fromisoformat(
        raw["timestamp"].replace("Z", "+00:00")
    )
    retrieved_at = datetime.now(timezone.utc)
    age_seconds = (retrieved_at - provider_time).total_seconds()
    if age_seconds < 0 or age_seconds > MAX_QUOTE_AGE_SECONDS:
        return {"status": "error", "code": "stale_quote",
                "provider_time": provider_time.isoformat()}

    return {
        "status": "ok",
        "instrument": {"symbol": raw["symbol"],
                       "exchange": raw["exchange"]},
        "quote": {"value": raw["price"],
                  "field": raw["price_type"],
                  "currency": raw["currency"]},
        "freshness": {"provider_time": provider_time.isoformat(),
                      "retrieved_at": retrieved_at.isoformat(),
                      "session": raw["session"],
                      "delay": raw["delay_label"]},
        "source": {"provider": raw["provider"],
                   "feed": raw["feed"]}
    }

Example: successful grounded answer示例:有数据依据的成功回答

User asks for the current quote. DeepSeek requests the function. The backend returns an ok envelope. The final answer states the resolved symbol and exchange, price meaning, currency, provider time, session, source, and delay label.用户询问当前行情,DeepSeek 请求函数,后端返回 ok 封装。最终回答展示已解析代码与交易所、价格含义、币种、数据源时间、交易时段、来源和延迟标签。

Example: honest failure示例:诚实失败

If the adapter returns stale_quote, not_entitled, or timeout, DeepSeek says that a current price could not be verified and retains any available timestamp. It does not output a remembered price.如果适配器返回 stale_quotenot_entitledtimeout,DeepSeek 应说明当前价格无法验证,并保留可用时间信息,不能输出记忆中的价格。

Read DeepSeek’s official Tool Calls guide阅读 DeepSeek 官方 Tool Calls 指南 · Check the current Chat Completion schema查看当前 Chat Completion Schema

QVeris patternQVeris 模式

Discover the capability before you hard-code the provider先发现能力,再决定是否绑定服务商

When your DeepSeek application needs more than one fixed endpoint, QVeris can serve as the capability layer: discover a market-data function, inspect its input and provider metadata, then call it from your backend. DeepSeek sees one narrow application function; credentials and provider selection remain server-side.当 DeepSeek 应用不只需要一个固定端点时,可把 QVeris 作为能力层:先发现行情能力,检查输入结构和服务商元数据,再由后端调用。DeepSeek 只看到一个边界清晰的应用函数,密钥与服务商选择仍留在服务端。

DISCOVER

Search by outcome按结果搜索

Describe the need—such as a current quote with source and timestamp—rather than assuming a provider.描述所需结果,例如带来源与时间戳的当前行情,而不是预先假定服务商。

INSPECT

Review before execution执行前检查

Confirm the schema, provider notes, expected output, cost signals, and freshness semantics.确认 Schema、服务商说明、预期输出、成本信息和新鲜度语义。

CALL

Execute from the backend从后端执行

Validate arguments, call the inspected capability, normalize the result, and preserve trace IDs.校验参数、调用已检查的能力、标准化结果并保留追踪 ID。

Production controls生产控制

Design for the ugly market states为复杂市场状态而设计

+
Freshness budget新鲜度预算

Choose latency, cache, and cost as one decision把延迟、缓存与成本作为一个整体决策

There is no universal cache duration for real-time stock market data. Define a maximum age per route, then confirm the provider entitlement can meet it. The values below are policy examples, not exchange or provider guarantees.实时股票市场数据没有通用缓存时长。应按路由定义最大数据年龄,再确认数据授权是否能够满足。下表是策略示例,不是交易所或服务商保证。

Experience使用场景 Retrieval pattern获取模式 Trade-off to document需要记录的权衡
One current quote单次当前行情 Request a fresh snapshot; cache only within the declared maximum age.请求新鲜快照,仅在声明的最大数据年龄内缓存。 Provider latency and one billable retrieval per cache miss.服务商延迟,以及每次缓存未命中的查询成本。
Multi-symbol watchlist多标的观察列表 Prefer a documented batch or snapshot endpoint; cap symbols.优先使用有文档的批量或快照端点,并限制标的数量。 Lower call overhead, but the oldest item may determine freshness.降低调用开销,但最旧条目可能决定整体新鲜度。
Continuous monitoring持续监控 Ingest WebSocket events outside DeepSeek; summarize selected events.在 DeepSeek 外摄取 WebSocket 事件,只总结筛选后的事件。 Stream infrastructure cost versus fewer model calls and bounded context.流处理基础设施成本,与更少模型调用及有限上下文之间的权衡。
Educational question知识解释问题 Skip the live tool unless the answer depends on a current fact.除非答案依赖当前事实,否则不调用实时工具。 Lowest cost and latency without pretending stable knowledge is live data.在不把稳定知识伪装成实时数据的前提下降低成本和延迟。
Risk风险 Deterministic control确定性控制 What DeepSeek should sayDeepSeek 应如何表达
Market closed市场休市 Return session status and identify last trade versus previous close.返回市场状态,并区分最近成交与前收盘。 Name the session and as-of time.说明交易时段和数据时间。
Stale cache缓存过期 Compare provider time with a route-specific maximum age.将数据源时间与路由最大年龄比较。 Say a current quote could not be verified.说明当前行情无法验证。
Ambiguous symbol代码歧义 Resolve venue and identity; return candidates.解析市场与身份;返回候选项。 Ask one precise clarification.提出一个明确追问。
Not entitled未获授权 Surface the provider error; do not silently downgrade.暴露服务商错误,不静默降级。 State that the feed cannot meet the requested freshness.说明 Feed 无法满足新鲜度要求。
Timeout or rate limit超时或限流 Use bounded retries, circuit breaking, and explicit errors.使用有限重试、熔断与明确错误。 Fail honestly; never substitute memory.诚实失败,不能用记忆替代。
Acceptance suite验收测试集

Test the decision to call, not only the API response不仅测试 API 返回,还要测试是否正确决定调用

Must call必须调用

  • “What is AAPL trading at now?”“AAPL 现在的成交价是多少?”
  • Latest quote, today’s move, market status最新行情、今日涨跌、市场状态
  • Pre-market and after-hours questions盘前与盘后问题
  • Equivalent English and Chinese freshness intent中英文等价实时意图

Must refuse or clarify必须拒绝或追问

  • Duplicate ticker across exchanges跨交易所重复代码
  • Missing provider timestamp缺少数据源时间戳
  • Stale, partial, or malformed envelope过期、不完整或格式异常的行情封装
  • Timeout, rate limit, and missing entitlement超时、限流和授权缺失

Release rule发布规则

Pass only when the answer preserves instrument identity, price meaning, currency, event time, session, source, and delay status—and refuses to repair missing live data with model knowledge.只有回答完整保留标的身份、价格含义、币种、事件时间、交易时段、来源和延迟状态,并且不会用模型知识补齐缺失实时数据时,才算通过。

FAQ常见问题

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

Does DeepSeek provide real-time stock market data?DeepSeek 自带实时股票市场数据吗?

DeepSeek should not be treated as the market-data source. Its tool-calling API can request an external quote function that your application executes, validates, and returns to the model.不应把 DeepSeek 当作行情数据源。它的工具调用 API 可以请求外部行情函数,再由你的应用执行、校验并把结果返回给模型。

How do I prevent DeepSeek from answering with an old stock price?如何防止 DeepSeek 用旧股价回答?

Force the quote tool for current-price intent, require provider and retrieval timestamps, reject results outside your freshness policy, and report tool failures instead of using memory.对当前价格意图强制调用行情工具,要求数据源时间和获取时间,拒绝超出新鲜度策略的结果,并在工具失败时明确说明。

Should every market question trigger the quote tool?每个市场问题都要调用行情工具吗?

No. Stable concepts may not need live data. Current price, latest, today, market status, pre-market, and after-hours requests should use a live-data path.不需要。稳定概念通常不依赖实时数据;当前价格、最新、今日、市场状态、盘前和盘后请求应走实时数据链路。

Can the same tool place trades?同一个工具可以下单吗?

Keep quote retrieval read-only. Order placement needs a separate, tightly authorized action with deterministic risk controls, idempotency, audit logs, and explicit confirmation.行情查询应保持只读。下单需要独立且严格授权的动作工具,以及确定性风控、幂等控制、审计日志和明确确认。

Next step下一步

Prove one quote before building a market copilot先验证一条行情,再构建市场 Copilot

Start with one read-only symbol lookup. Inspect the capability, record the source and timestamps, then deliberately test stale data and provider failure.先从一只股票的只读查询开始。检查能力、记录来源与时间戳,再主动测试过期数据和服务商故障。