ページ拡張機能のサンプル · 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. パネル:直近の終値 | サイドバーのウィンドウ、価格バーの読み取り、フッターのステータス |
| 2. REST ベンダー向けのデータプロバイダー | ベンダーからのバー、API キーをシークレットとして扱う |
| 3. ライブティックのコネクター | チャートにプッシュされる 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 からのバーです。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. ライブティックのコネクター
WebSocket でプロバイダーにライブ約定を追加します。permissions に net:stream.example.com を追加し、プロバイダーファイルを拡張します。
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 で選択します。一度に大量のティックがある場合は、グループにして送信してください。qc.provider.emitBatch([{ symbol, kind: "trade", price, size, t }, …]) は 1 回の呼び出しで最大 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 の 2 つの 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-(色:16 進、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 は、送信するすべてのものの周りで、ユーザーの上限、確認、キルスイッチを適用します。ユーザーに表示される内容はブローカー拡張機能を参照してください。

