Documentação1.0 (latest)
PáginasExemplos de extensões · 34 / 37

Novo na v1.4.0

Exemplos de extensões

Novidade no QuantCraft v1.4.0. Esta página descreve uma funcionalidade que acompanha a v1.4.0, a próxima versão principal. A versão atual é a v1.3.0, que ainda não a inclui.

Pontos de partida funcionais. Cada um é uma pasta de projeto: crie-a com New extension project (veja Criar extensões) e substitua os arquivos, ou cole os arquivos em uma pasta nova. acme.demo e api.example.com são marcadores: use seu próprio id e o host do seu fornecedor.

Cada exemplo começa uma página ou script com const qc = await window.qc.ready;. Para a lista completa de funções, veja API de extensões.

ExemploMostra
1. Um painel: último fechamentoUma janela da barra lateral, leitura de barras de preço, um status no rodapé
2. Um provedor de dados para um fornecedor RESTBarras do seu fornecedor, uma chave de API como segredo
3. Um conector de ticks ao vivoUm feed WebSocket enviado aos gráficos
4. Um mapa de calor de fundamentosLer fundamentos e desenhá-los
5. Ferramentas de IAUma ferramenta que o assistente de IA pode chamar
6. Um mecanismo PythonCalcular em Python, exposto como ferramenta de IA
7. Um temaSomente cores
8. Uma corretora, do jeito seguroO formato de uma extensão de corretora

1. Um painel: último fechamento

Mostra o último fechamento e a variação de 30 dias de um símbolo digitado, e o espelha no rodapé.

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()); });

O manifesto aponta para ui/icon.svg como ícone da barra lateral (o assistente cria um; qualquer SVG pequeno serve, ou remova a linha icon).


2. Um provedor de dados para um fornecedor REST

Barras de api.example.com, com a chave de API guardada como configuração secreta que o usuário digita nos Settings da extensão.

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 })); }, });

Depois: Settings → digite a chave → Set up… → Test, e escolha-o no rodapé em Data → Chart bars. Use Mock primeiro se ainda não tiver uma chave (o modelo inicial do assistente tem um interruptor USE_MOCK exatamente para isso).


3. Um conector de ticks ao vivo

Adicione negociações ao vivo a um provedor com um WebSocket. Adicione net:stream.example.com a permissions e estenda o arquivo do provedor:

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); }, });

Escolha-o em Data → Live ticks. Muitos ticks de uma vez? Envie-os em grupos: qc.provider.emitBatch([{ symbol, kind: "trade", price, size, t }, …]) aceita até 500 por chamada. O QuantCraft limita a velocidade com que os aceita e conta o que descarta.


4. Um mapa de calor de fundamentos

Um painel que lê os últimos indicadores de cada símbolo e colore as células. Requer data.fundamentals.

qcext.json: igual ao do exemplo 1, com "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); }

O corpo de ui/index.html: <table id="grid"></table> (mais as duas tags script do exemplo 1). As leituras têm taxa limitada pelo QuantCraft, então uma lista longa é preenchida aos poucos.


5. Ferramentas de IA

Uma ferramenta que o assistente pode chamar para resumir um símbolo. Requer ai.tools e 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 (carregue-o a partir de ui/index.html com <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)) }; });

Ative-a pelo botão de ferramentas do campo de chat (uma extensão de origem não verificada começa desligada). Escreva a description pensando no modelo: diga o que a ferramenta faz e quando usá-la. Mantenha os resultados pequenos.


6. Um mecanismo Python

Calcule em Python e exponha como ferramenta de IA. Requer apiVersion 2 e a permissão Run its own program. Comece pelo tipo Python engine do assistente; ele contém isto:

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}")

manifesto (trecho)

{ "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 e Build substituem para você os zeros de sha256 pela impressão digital real do arquivo. Os pacotes vão em requirements.txt como wheels Python puros (pacotes compilados como numpy não são suportados). O mecanismo roda em Developer mode, ou quando a extensão é Verified.


7. Um tema

Somente cores, sem código nem permissões.

qcext.json (trecho): "permissions": [] e

"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" } }

Os nomes de token começam com --c- (cores: hex, rgb(), hsl() ou transparent) ou --r- (raios de canto como 8px). Qualquer outra coisa é ignorada e relatada. Um tema só se aplica enquanto o app está no modo base dele. Os usuários o escolhem em Settings → Appearance.


8. Uma corretora, do jeito seguro

Comece sempre pelo tipo Broker do assistente: ele vem com uma corretora simulada para que você possa enviar, cancelar, rejeitar e expirar ordens sem tocar em dinheiro real. O formato da versão real:

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 }) => { /* ... */ }, });

Valores e quantidades são strings numéricas. Não tente de novo dentro da extensão. O QuantCraft aplica os limites do usuário, as confirmações e o kill switch em torno de tudo o que você envia; veja Extensões de corretora para o que os usuários veem.

11 min de leituraSugerir uma edição ↗
Exemplos de extensões — Documentação (1.0 (latest)) | QuantCraft