Documentation1.0 (latest)
PagesExtension examples · 34 / 37

New in v1.4.0

Extension examples

New in QuantCraft v1.4.0. This page describes functionality that ships with v1.4.0, the next major release. The current release is v1.3.0, which does not include it yet.

Working starting points. Each one is a project folder: create it with New extension project (see Building extensions) and replace the files, or paste the files into a new folder. acme.demo and api.example.com are placeholders: use your own id and your vendor's host.

Every example starts a page or script with const qc = await window.qc.ready;. For the full list of functions, see Extension API.

ExampleShows
1. A panel: last closeA sidebar window, reading price bars, a footer status
2. A data provider for a REST vendorBars from your vendor, an API key as a secret
3. A live-ticks connectorA WebSocket feed pushed into charts
4. A fundamentals heatmapReading fundamentals and drawing them
5. AI toolsA tool the AI assistant can call
6. A Python engineCompute in Python, exposed as an AI tool
7. A themeColours only
8. A broker, the safe wayThe shape of a broker extension

1. A panel: last close

Shows the latest close and 30-day change for a symbol you type, and mirrors it in the footer.

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

The manifest points at ui/icon.svg for the sidebar icon (the wizard creates one; any small SVG works, or remove the icon line).


2. A data provider for a REST vendor

Bars from api.example.com, with the API key stored as a secret setting the user types in the extension's 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 })); }, });

Then: Settings → type the key → Set up… → Test, and choose it in the footer Data → Chart bars. Use Mock first if you do not have a key yet (the wizard's starter has a USE_MOCK switch for exactly that).


3. A live-ticks connector

Add live trades to a provider with a WebSocket. Add net:stream.example.com to permissions, and extend the provider file:

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

Choose it in Data → Live ticks. Many ticks at once? Send them in groups: qc.provider.emitBatch([{ symbol, kind: "trade", price, size, t }, …]) takes up to 500 per call. QuantCraft limits how fast it accepts them and counts what it drops.


4. A fundamentals heatmap

A panel that reads each symbol's latest ratios and colours the cells. Needs data.fundamentals.

qcext.json: same as example 1, with "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> (plus the two script tags from example 1). The reads are rate-limited by QuantCraft, so a long list fills in gradually.


5. AI tools

A tool the assistant can call to summarise a symbol. Needs ai.tools and 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 (load it from ui/index.html with <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)) }; });

Turn it on from the chat composer's tools button (an extension from an unverified source starts off). Write the description for the model: say what the tool does and when to use it. Keep results small.


6. A Python engine

Compute in Python and expose it as an AI tool. It needs apiVersion 2 and the Run its own program permission. Start from the Python engine part in the wizard; it contains this:

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

manifest (excerpt)

{ "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 and Build replace the zeros in sha256 with the file's real fingerprint for you. Packages go in requirements.txt as pure-Python wheels (compiled packages like numpy are not supported). The engine runs in Developer mode, or when the extension is Verified.


7. A theme

Colours only, no code, no permissions.

qcext.json (excerpt): "permissions": [] and

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

Token names start with --c- (colours: hex, rgb(), hsl() or transparent) or --r- (corner radii such as 8px). Anything else is ignored and reported. A theme applies only while the app is in its base mode. Users pick it in Settings → Appearance.


8. A broker, the safe way

Always start from the Broker part in the wizard: it comes with a mock broker so you can place, cancel, reject and time out orders without touching real money. The shape of the real thing:

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

Money and quantities are numeric strings. Do not retry inside the extension. QuantCraft enforces the user's limits, confirmations and the kill switch around everything you send; see Broker extensions for what users see.

Extension examples — Documentation (1.0 (latest)) | QuantCraft