PáginasEjemplos de extensiones · 34 / 37
Nuevo en v1.4.0
Ejemplos de extensiones
Novedad en QuantCraft v1.4.0. Esta página describe una funcionalidad que se incluye en la v1.4.0, la próxima versión mayor. La versión actual es la v1.3.0, que todavía no la incluye.
Puntos de partida funcionales. Cada uno es una carpeta de proyecto: créala con New extension project (consulta Crear extensiones) y sustituye los archivos, o pega los archivos en una carpeta nueva. acme.demo y api.example.com son marcadores: usa tu propio id y el host de tu proveedor.
Cada ejemplo empieza una página o script con const qc = await window.qc.ready;. Para la lista completa de funciones, consulta API de extensiones.
| Ejemplo | Muestra |
|---|---|
| 1. Un panel: último cierre | Una ventana de la barra lateral, lectura de barras de precios, un estado en el pie de página |
| 2. Un proveedor de datos para un proveedor REST | Barras de tu proveedor, una clave API como secreto |
| 3. Un conector de ticks en vivo | Un flujo WebSocket enviado a los gráficos |
| 4. Un mapa de calor de fundamentales | Leer fundamentales y dibujarlos |
| 5. Herramientas de IA | Una herramienta que el asistente de IA puede invocar |
| 6. Un motor Python | Calcular en Python, expuesto como herramienta de IA |
| 7. Un tema | Solo colores |
| 8. Un bróker, de forma segura | La forma de una extensión de bróker |
1. Un panel: último cierre
Muestra el último cierre y la variación a 30 días de un símbolo que escribas, y lo refleja en el pie de página.
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());
});El manifiesto apunta a ui/icon.svg como icono de la barra lateral (el asistente crea uno; sirve cualquier SVG pequeño, o elimina la línea icon).
2. Un proveedor de datos para un proveedor REST
Barras de api.example.com, con la clave API guardada como ajuste secreto que el usuario escribe en los Settings de la extensión.
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 }));
},
});Después: Settings → escribe la clave → Set up… → Test, y elígelo en el pie de página Data → Chart bars. Usa Mock primero si aún no tienes clave (la plantilla inicial del asistente tiene un interruptor USE_MOCK justo para eso).
3. Un conector de ticks en vivo
Añade operaciones en vivo a un proveedor con un WebSocket. Añade net:stream.example.com a permissions y amplía el archivo del proveedor:
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);
},
});Elígelo en Data → Live ticks. ¿Muchos ticks a la vez? Envíalos en grupos: qc.provider.emitBatch([{ symbol, kind: "trade", price, size, t }, …]) admite hasta 500 por llamada. QuantCraft limita la velocidad a la que los acepta y cuenta los que descarta.
4. Un mapa de calor de fundamentales
Un panel que lee los últimos ratios de cada símbolo y colorea las celdas. Requiere data.fundamentals.
qcext.json: igual que en el ejemplo 1, con "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);
}El cuerpo de ui/index.html: <table id="grid"></table> (más las dos etiquetas script del ejemplo 1). QuantCraft limita la frecuencia de las lecturas, así que una lista larga se va rellenando poco a poco.
5. Herramientas de IA
Una herramienta que el asistente puede invocar para resumir un símbolo. Requiere ai.tools y 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 (cárgalo desde ui/index.html con <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)) };
});Actívala desde el botón de herramientas del cuadro de chat (una extensión de un origen no verificado empieza desactivada). Escribe la description pensando en el modelo: di qué hace la herramienta y cuándo usarla. Mantén los resultados pequeños.
6. Un motor Python
Calcula en Python y expónlo como herramienta de IA. Requiere apiVersion 2 y el permiso Run its own program. Parte del tipo Python engine del asistente; contiene esto:
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}")manifiesto (extracto)
{
"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 y Build sustituyen por ti los ceros de sha256 por la huella real del archivo. Los paquetes van en requirements.txt como wheels de Python puro (los paquetes compilados como numpy no se admiten). El motor se ejecuta en Developer mode, o cuando la extensión es Verified.
7. Un tema
Solo colores, sin código ni permisos.
qcext.json (extracto): "permissions": [] y
"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"
}
}Los nombres de token empiezan por --c- (colores: hex, rgb(), hsl() o transparent) o --r- (radios de esquina como 8px). Todo lo demás se ignora y se notifica. Un tema solo se aplica mientras la aplicación está en su modo base. Los usuarios lo eligen en Settings → Appearance.
8. Un bróker, de forma segura
Parte siempre del tipo Broker del asistente: incluye un bróker simulado para que puedas colocar, cancelar, rechazar y agotar el tiempo de órdenes sin tocar dinero real. La forma de la versión 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 }) => { /* ... */ },
});Los importes y cantidades son cadenas numéricas. No reintentes dentro de la extensión. QuantCraft aplica los límites del usuario, las confirmaciones y el kill switch alrededor de todo lo que envíes; consulta Extensiones de bróker para ver lo que ven los usuarios.

