文档1.0 (latest)
页面扩展示例 · 34 / 37

v1.4.0 新增

扩展示例

QuantCraft v1.4.0 新增。 本页介绍随下一个主要版本 v1.4.0 发布的功能。当前版本为 v1.3.0,尚不包含这些功能。

可直接运行的起点。每个示例都是一个项目文件夹:用 New extension project 创建(参见开发扩展)并替换其中的文件,或把文件粘贴到新文件夹中。acme.demo 和 api.example.com 是占位符:请使用您自己的 id 和供应商的主机。

每个示例都以 const qc = await window.qc.ready; 开始页面或脚本。完整的函数列表请参阅扩展 API。

示例演示内容
1. 面板:最新收盘价侧边栏窗口、读取价格 K 线、页脚状态
2. REST 供应商的数据提供方来自您供应商的 K 线,API 密钥作为机密
3. 实时 tick 连接器推送到图表的 WebSocket 数据流
4. 基本面热力图读取基本面数据并绘制
5. AI 工具可供 AI 助手调用的工具
6. Python 引擎用 Python 计算,并作为 AI 工具公开
7. 主题仅颜色
8. 券商:安全的做法券商扩展的结构

1. 面板:最新收盘价

显示您输入的标的的最新收盘价和 30 天涨跌幅,并同步显示在页脚中。

qcext.json

{ "id": "acme.lastclose", "version": "0.1.0", "apiVersion": 1, "name": "Last close", "description": "Latest close and 30-day change for a symbol.", "permissions": ["data.ohlcv"], "contributes": { "sidebar": { "title": "Last close", "icon": "ui/icon.svg", "entry": "ui/index.html", "modal": { "width": 420, "height": 300, "minWidth": 320, "minHeight": 220 } }, "footer": { "default": true } } }

ui/index.html

<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Last close</title> <link rel="stylesheet" href="style.css" /> <script type="module" src="/_sdk/qc.js"></script> <script type="module" src="app.js"></script> </head> <body> <form id="form"> <input id="symbol" value="AAPL" aria-label="Symbol" /> <button type="submit">Load</button> </form> <p id="result" class="muted">Enter a symbol.</p> </body> </html>

ui/style.css

body { font: 14px system-ui; padding: 16px; color: var(--qc-text, inherit); background: var(--qc-bg, transparent); } input { width: 7em; text-transform: uppercase; } .muted { opacity: 0.7; } .up { color: #1a9d55; } .down { color: #d0453a; }

ui/app.js

const qc = await window.qc.ready; const result = document.getElementById("result"); async function load(symbol) { result.textContent = "Loading…"; try { const r = await qc.data.ohlcv.get({ symbol, timeframe: "1D", limit: 30 }); const bars = r.bars; if (!bars.length) throw new Error(`No bars for ${symbol}`); const last = bars[bars.length - 1].c; const first = bars[0].c; const pct = ((last - first) / first) * 100; result.innerHTML = `<strong>${symbol}</strong> ${last.toFixed(2)} <span class="${pct >= 0 ? "up" : "down"}">${pct >= 0 ? "+" : ""}${pct.toFixed(1)}%</span> <span class="muted">over ${bars.length} days</span>`; qc.ui.setFooter({ text: `${symbol} ${last.toFixed(2)}`, tone: pct >= 0 ? "ok" : "warn" }); } catch (e) { result.textContent = e.message; qc.log.warn("load failed", e.message); } } document.getElementById("form").addEventListener("submit", (ev) => { ev.preventDefault(); void load(document.getElementById("symbol").value.trim().toUpperCase()); });

清单中的侧边栏图标指向 ui/icon.svg(向导会创建一个;任何小型 SVG 都可以,或者删除 icon 这一行)。


2. REST 供应商的数据提供方

来自 api.example.com 的 K 线,API 密钥作为机密设置保存,由用户在扩展的 Settings 中输入。

qcext.json

{ "id": "acme.vendorbars", "version": "0.1.0", "apiVersion": 1, "name": "Vendor bars", "description": "Daily and minute bars from Example Data.", "permissions": ["data.provide", "secrets", "net:api.example.com"], "contributes": { "dataProviders": [ { "id": "bars", "name": "Example Data", "kinds": ["ohlcv"], "entry": "providers/bars.js" } ], "settings": [ { "key": "apiKey", "label": "API key", "type": "secret", "required": true, "help": "From your Example Data dashboard." } ] } }

providers/bars.js

const qc = await window.qc.ready; const BASE = "https://api.example.com/v1"; async function api(path) { const key = await qc.secrets.get("apiKey"); if (!key) throw Object.assign(new Error("Add your API key in this extension's Settings."), { code: "no_key" }); const res = await qc.net.fetch(`${BASE}${path}`, { headers: { Authorization: `Bearer ${key}` } }); if (res.status === 429) throw Object.assign(new Error("Example Data says: too many requests."), { code: "rate_limited" }); if (!res.ok) throw new Error(`Example Data answered ${res.status}.`); return res.json(); } qc.provider.defineOhlcv({ // Say what the vendor really allows: QuantCraft paces its calls to this. capabilities: { timeframes: ["1Min", "5Min", "1D"], maxBarsPerRequest: 1000, rateLimit: { requestsPerMinute: 30 } }, // The search box in the symbol list. Receives the text typed. searchSymbols: async (query) => { const rows = await api(`/symbols?q=${encodeURIComponent(query)}`); return rows.map((r) => ({ symbol: r.ticker, name: r.name })); }, // start and end are epoch milliseconds; return bars in [start, end), oldest first, at most `limit`. getBars: async ({ symbol, timeframe, start, end, limit }) => { const rows = await api(`/bars?symbol=${encodeURIComponent(symbol)}&tf=${timeframe}&from=${start}&to=${end}&limit=${limit}`); return rows.map((r) => ({ t: r.time, o: r.open, h: r.high, l: r.low, c: r.close, v: r.volume })); }, });

然后:Settings → 输入密钥 → Set up… → Test,并在页脚的 Data → Chart bars 中选择它。如果您还没有密钥,请先使用 Mock(向导的起始模板就带有专为此用途的 USE_MOCK 开关)。


3. 实时 tick 连接器

用 WebSocket 为提供方增加实时成交。把 net:stream.example.com 加入 permissions,并扩展提供方文件:

const qc = await window.qc.ready; const sockets = new Map(); // symbol -> WebSocket qc.provider.defineOhlcv({ capabilities: { timeframes: ["1D"], rateLimit: { requestsPerMinute: 30 } }, searchSymbols: async () => [], getBars: async () => [], // history comes from another source, or implement it as in example 2 // QuantCraft calls this when a chart or run needs live data for a symbol. subscribe: async ({ symbol }) => { if (sockets.has(symbol)) return; const key = await qc.secrets.get("apiKey"); const ws = new WebSocket(`wss://stream.example.com/v1/trades?symbol=${encodeURIComponent(symbol)}&key=${key}`); ws.onmessage = (m) => { const t = JSON.parse(m.data); // { price, size, time } void qc.provider.emit({ symbol, kind: "trade", price: t.price, size: t.size, t: t.time }); }; ws.onclose = () => sockets.delete(symbol); sockets.set(symbol, ws); }, unsubscribe: async ({ symbol }) => { sockets.get(symbol)?.close(); sockets.delete(symbol); }, });

在 Data → Live ticks 中选择它。一次有很多 tick?请分组发送:qc.provider.emitBatch([{ symbol, kind: "trade", price, size, t }, …]) 每次调用最多接受 500 条。QuantCraft 会限制接受它们的速度,并统计被丢弃的数量。


4. 基本面热力图

一个读取每个标的最新比率并为单元格着色的面板。需要 data.fundamentals。

qcext.json:与示例 1 相同,但 "permissions": ["data.fundamentals"]。

ui/app.js

const qc = await window.qc.ready; const SYMBOLS = ["AAPL", "MSFT", "NVDA", "AMZN", "GOOGL"]; const METRICS = [ ["grossMargin", "Gross margin"], ["operatingMargin", "Operating margin"], ["netProfitMargin", "Net margin"], ["returnOnEquity", "ROE"], ]; const table = document.getElementById("grid"); const cell = (text, v) => { const td = document.createElement("td"); td.textContent = text; if (typeof v === "number") td.style.background = `hsl(${Math.max(0, Math.min(120, 60 + v * 200))} 55% 32%)`; // red .. green return td; }; table.innerHTML = "<tr><th></th>" + METRICS.map(([, label]) => `<th>${label}</th>`).join("") + "</tr>"; for (const symbol of SYMBOLS) { const tr = document.createElement("tr"); const th = document.createElement("th"); th.textContent = symbol; tr.append(th); try { const r = await qc.data.fundamentals.get({ symbol, sections: ["ratios"], limit: 1 }); const rows = r.sections.ratios?.quarterly ?? []; const latest = rows[rows.length - 1] ?? {}; for (const [key] of METRICS) { const v = latest[key]; tr.append(cell(typeof v === "number" ? `${(v * 100).toFixed(1)}%` : "n/a", v)); } } catch (e) { qc.log.warn(`fundamentals for ${symbol} failed`, e.message); for (const _ of METRICS) tr.append(cell("n/a")); } table.append(tr); }

ui/index.html 的 body:<table id="grid"></table>(外加示例 1 中的两个 script 标签)。读取受 QuantCraft 频率限制,因此较长的列表会逐步填充。


5. AI 工具

一个助手可调用来概括某个标的的工具。需要 ai.tools 和 data.ohlcv。

qcext.json

{ "id": "acme.moves", "version": "0.1.0", "apiVersion": 1, "name": "Moves", "description": "Gives the AI assistant a recent-moves tool.", "permissions": ["ai.tools", "data.ohlcv"], "contributes": { "sidebar": { "title": "Moves", "icon": "ui/icon.svg", "entry": "ui/index.html" }, "aiTools": [ { "name": "recent_move", "description": "Last close and percent change over the last N daily bars for a stock symbol. Use it when asked how a stock has moved recently.", "inputSchema": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker, e.g. AAPL" }, "days": { "type": "integer", "description": "Number of daily bars, 2 to 90 (default 5)" } }, "required": ["symbol"] } } ] } }

ui/tools.js(在 ui/index.html 中用 <script type="module" src="tools.js"></script> 加载)

const qc = await window.qc.ready; qc.handle("tool.call", async ({ name, args }) => { if (name !== "recent_move") throw new Error(`Unknown tool ${name}`); const symbol = String(args?.symbol ?? "").toUpperCase().trim(); const days = Math.min(90, Math.max(2, Number(args?.days) || 5)); if (!symbol) throw new Error("symbol is required"); const { bars } = await qc.data.ohlcv.get({ symbol, timeframe: "1D", limit: days }); if (bars.length < 2) throw new Error(`Not enough data for ${symbol}`); const last = bars[bars.length - 1].c; const first = bars[0].c; return { symbol, bars: bars.length, lastClose: last, changePercent: Number((((last - first) / first) * 100).toFixed(2)) }; });

从聊天输入框的工具按钮中开启它(来自未验证来源的扩展默认关闭)。请为模型编写 description:说明工具做什么、何时使用。保持结果精简。


6. Python 引擎

用 Python 计算并作为 AI 工具公开。它需要 apiVersion 2 和 Run its own program 权限。请从向导的 Python engine 部分开始;它包含以下内容:

engine/main.py

async def handle(method, params, host): if method == "tool.call" and params.get("name") == "add_py": args = params.get("args") or {} a, b = args.get("a"), args.get("b") if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): raise EngineError("bad_input", "a and b must be numbers") return {"sum": a + b} raise EngineError("unknown_method", f"unknown method {method}")

清单(节选)

{ "apiVersion": 2, "permissions": ["engine.run", "ai.tools"], "contributes": { "engines": [{ "id": "py-calc", "runtime": { "kind": "python", "entry": "engine/main.py", "sha256": "0000000000000000000000000000000000000000000000000000000000000000", "packages": [] } }], "aiTools": [{ "name": "add_py", "description": "Add two numbers in Python.", "engine": "py-calc", "inputSchema": { "type": "object", "properties": { "a": { "type": "number" }, "b": { "type": "number" } }, "required": ["a", "b"] } }] } }

Run 和 Build 会为您把 sha256 中的零替换为文件的真实指纹。包以纯 Python wheel 的形式放入 requirements.txt(不支持 numpy 等已编译的包)。引擎在 Developer mode 下运行,或在扩展为 Verified 时运行。


7. 主题

仅颜色,无需代码,无需权限。

qcext.json(节选):"permissions": [] 以及

"contributes": { "themes": [{ "id": "midnight", "name": "Midnight", "tokens": "theme.json" }] }

theme.json

{ "base": "dark", "tokens": { "--c-accent": "#ff8800", "--c-accent-hover": "#ff9a26", "--c-accent-on": "#101010", "--c-surface-app": "#0e0f12", "--c-surface-pane": "#14161a" } }

令牌名以 --c-(颜色:十六进制、rgb()、hsl() 或 transparent)或 --r-(圆角半径,如 8px)开头。其他一律被忽略并给出报告。主题仅在应用处于其 base 模式时生效。用户在 Settings → Appearance 中选择它。


8. 券商:安全的做法

请始终从向导的 Broker 部分开始:它自带一个模拟券商,让您可以下单、撤单、拒单和模拟超时,而不接触真实资金。真实版本的结构如下:

const qc = await window.qc.ready; qc.provider.defineBroker({ capabilities: { name: "My broker", mode: "paper", // "paper" | "live" | "both": say it truthfully instruments: ["equity"], // add "option" only if you implement the option functions orderTypes: ["market", "limit"], timeInForce: ["day", "gtc"], }, getAccount: async () => ({ cash: "10000.00", equity: "10000.00", buying_power: "10000.00", currency: "USD" }), getPositions: async () => [], // [{ symbol, qty, side, avg_entry_price, current_price, market_value, unrealized_pl }] getOrders: async ({ status }) => [], // "open" | "closed" | "all" getOrder: async ({ id, client_order_id }) => { throw Object.assign(new Error("Not found"), { code: "not_found" }); }, // Be idempotent on order.client_order_id: if you already placed it, return that same order. placeOrder: async (order) => { /* call your broker */ }, // Throw one of these codes ONLY when the broker definitely refused the order: // rejected, invalid_order, insufficient_funds, not_tradable, market_closed, halted, unsupported, forbidden. // Any other failure is treated as "outcome unknown" and QuantCraft looks the order up instead of guessing. cancelOrder: async ({ id }) => { /* ... */ }, });

金额和数量是数字字符串。不要在扩展内部重试。QuantCraft 会围绕您发送的一切执行用户的限额、确认和紧急停止开关;用户会看到什么,请参阅券商扩展。

阅读约 8 分钟建议修改 ↗
扩展示例 — 文档 (1.0 (latest)) | QuantCraft