Documentation1.0 (latest)
PagesExtension API · 35 / 37

New in v1.4.0

Extension reference

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.

The reference for people writing extensions: the qc functions, the qcext.json manifest, permissions, what a provider must return, errors and limits. The workflow is in Building extensions and runnable code is in Extension examples.

Editor typings for the SDK ship in the SDK package as qc-extension.d.ts.


How an extension talks to QuantCraft: sandboxed code calls the qc SDK, every call passes a permission check, and QuantCraft serves data, storage, secrets, AI tools, or network access to declared hosts only.

Using the SDK

<script type="module" src="/_sdk/qc.js"></script>
const qc = await window.qc.ready; // resolves once QuantCraft has connected your page

Every call returns a promise and rejects with a qc.QcError whose code is one of the error codes.

The qc object

qc

MemberKindWhat it does
qc.readypropertyPromise resolving with qc once the host handshake is done: const qc = await window.qc.ready.
qc.infopropertyAfter the handshake: { extId, name, version, theme, settings, permissions }.
qc.settingspropertyThis extension's current settings (updated by onSettingsChange).
qc.sdkVersionpropertySDK version string.
qc.apiVersionpropertyExtension API version (1).
qc.QcErrorpropertyError class the SDK rejects with; code is stable (timeout, permission_denied, …).
qc.uinamespaceHost UI: badge, footer item, toasts, modal size, theme.
qc.storagenamespacePer-extension key/value storage.
qc.secretsnamespaceSecret settings (needs the secrets permission).
qc.datanamespaceRead-only QuantCraft data (needs data.ohlcv / data.fundamentals / data.calendar).
qc.toolsnamespaceHost tools (needs a tools.* permission; the user is asked the first time).
qc.netnamespaceHTTPS through the host (needs net:<host>).
qc.lognamespaceWrite to the extension's log (Manager › Logs).
qc.eventsnamespaceHost events.
qc.handlefunctionhandle(method, fn): answer a host request, e.g. tool.call for AI tools.
qc.providernamespaceData provider helpers (needs data.provide).
qc.testingnamespaceTest vehicles.
qc.onSettingsChangefunctiononSettingsChange(fn): returns an unsubscribe function.

qc.ui

MemberKindWhat it does
qc.ui.setBadgefunctionsetBadge(n): a count, true for a dot, null/0 clears it.
qc.ui.setFooterfunctionsetFooter({ text, label?, tone?, loading?, tooltip?, details? } | null): a status item in the app footer (declare contributes.footer).
qc.ui.toastfunctiontoast(message, { level }): info | success | warn | error.
qc.ui.resizeModalfunctionresizeModal({ width, height }).
qc.ui.getThemefunctiongetTheme(): the host theme { name, tokens }.
qc.ui.onThemeChangefunctiononThemeChange(fn): returns an unsubscribe function.

qc.storage

MemberKindWhat it does
qc.storage.getfunctionget(key).
qc.storage.setfunctionset(key, value).
qc.storage.deletefunctiondelete(key).
qc.storage.listfunctionlist(prefix?): keys.

qc.secrets

MemberKindWhat it does
qc.secrets.getfunctionget(key): the secret, or null.
qc.secrets.hasfunctionhas(key): whether it is set.

qc.data

MemberKindWhat it does
qc.data.ohlcvnamespaceBars.
qc.data.fundamentalsnamespaceCompany fundamentals.
qc.data.calendarnamespaceCorporate-action and filing events.

qc.data.ohlcv

MemberKindWhat it does
qc.data.ohlcv.getfunctionget({ symbol, timeframe?, start?, end?, limit?, source? }): bars { t, o, h, l, c, v }.

qc.data.fundamentals

MemberKindWhat it does
qc.data.fundamentals.getfunctionget({ symbol, sections?, asOf?, limit? }).

qc.data.calendar

MemberKindWhat it does
qc.data.calendar.eventsfunctionevents({ symbol, kinds?, from?, to?, asOf?, limit? }).

qc.tools

MemberKindWhat it does
qc.tools.listfunctionlist(): tools you may use now.
qc.tools.callfunctioncall(name, args): e.g. screener.run, backtest.run, indicators.compute.

qc.net

MemberKindWhat it does
qc.net.fetchfunctionfetch(url, { method, headers, body, authSecret }): { status, ok, json(), text(), … }.

qc.log

MemberKindWhat it does
qc.log.debugfunctiondebug(...args).
qc.log.infofunctioninfo(...args).
qc.log.warnfunctionwarn(...args).
qc.log.errorfunctionerror(...args).

qc.events

MemberKindWhat it does
qc.events.onfunctionon(event, fn): returns an unsubscribe function.
qc.events.offfunctionoff(event, fn).

qc.provider

MemberKindWhat it does
qc.provider.defineOhlcvfunctiondefineOhlcv({ capabilities, searchSymbols, getBars, subscribe, unsubscribe }).
qc.provider.defineFundamentalsfunctiondefineFundamentals({ capabilities, getFundamentals({ symbol }), listSymbols({ cursor }) }): provide fundamentals (kind fundamentals).
qc.provider.defineBrokerfunctiondefineBroker({ capabilities, getAccount, getPositions, getOrders, placeOrder, cancelOrder, … }): a brokerage account (kind broker, needs trade.place). Be idempotent on client_order_id.
qc.provider.emitBrokerfunctionemitBroker(): tell the host the account, positions or orders changed so it refetches (a hint). emitBroker({ type: 'snapshot', account?, positions?, orders? }) pushes the new state instead (declare updates: 'push'). Needs trade.place.
qc.provider.emitfunctionemit({ symbol, kind: 'trade' | 'bar', … }): push a live trade or bar.
qc.provider.emitBatchfunctionemitBatch([event, …]): push up to 500 live events in one call; resolves { accepted, dropped }.

qc.testing

MemberKindWhat it does
qc.testing.mockOhlcvProviderfunctionmockOhlcvProvider(opts): a fake provider with deterministic bars and simulated trades.
qc.testing.mockBrokerProviderfunctionmockBrokerProvider(opts): a fake brokerage with an in-memory account and options chain, and switches for rejects, outages, timeouts and dropped replies.
qc.testing.mockFundamentalsProviderfunctionmockFundamentalsProvider(opts): a fake fundamentals provider with deterministic statements and a symbol list.

The manifest: qcext.json

A key that is not listed here is an error.

Top level

FieldRequiredRule
idyespublisher.name: lowercase letters, digits and -, at least one ., at most 64 characters. Fixed once published
versionyesSemantic version, e.g. 1.0.0
apiVersionyes1 or up to 2. Use 2 if you use contributes.engines
nameyesAt most 48 characters
permissionsyesA list of permissions (below); [] for none
descriptionnoAt most 280 characters
publishernoAt most 64 characters, usually a domain
iconnoA relative .svg or .png
homepage, repositorynohttps links
licensenoAn SPDX id such as MIT
contributesnoWhat the extension adds (below)
activationnoWhen it starts: onStartup, onSidebarOpen, onProviderUse:<id>, onToolCall:<name>. Leave it out and it starts when first used

contributes

KeyShapeNotes
sidebar{ title, icon?, entry, modal? }A sidebar icon that opens entry (an .html file) in a window. modal: width (320–2400), height (240–2000), minWidth, minHeight, resizable. Default 900×640. title at most 32 characters
footer{ default? }A status item in the app footer, set with qc.ui.setFooter. default: true shows it unless the user hides it. Needs no permission
dataProviders (up to 8){ id, name?, kinds, entry }kinds: any of ohlcv, ticks, symbols, prices, fundamentals, broker. entry is a .js file (or engine for an engine-backed provider). Needs data.provide; kind broker also needs trade.place
aiTools (up to 32){ name, description, inputSchema?, engine? }name: lowercase letters, digits and _, starting with a letter, at most 48 characters. The assistant sees it as ext_<id>__<name>. Needs ai.tools
themes (up to 8){ id, name, tokens }tokens is a .json file { "base": "dark" | "light", "tokens": { "--c-accent": "#ff8800" } }. Token names start --c- (colours) or --r- (radii). No code
engines (up to 4){ id, runtime, limits? }runtime.kind: wasm (module: { entry, sha256 }), python (entry, sha256, packages?) or binary (targets). Needs apiVersion 2 and engine.run
settings (up to 40){ key, label, type, … }The extension's Settings form. type is one of secret, text, url, number, toggle, select, segmented. key: letters and digits, starting with a lowercase letter, at most 40, unique. label at most 60, help at most 200, optional required

A secret setting has no default, needs the secrets permission, and is read with qc.secrets.get(key). A number setting accepts min, max, step, unit and default; select and segmented take a list of options.


Permissions

List only what you use. Adding a permission in an update makes users approve again.

PermissionRiskShown to the user as
trade.placehighPlace orders in your brokerage account
secretshighStore and read secrets
net:<host>mediumConnect to the listed domains
tools.backtestmediumStart backtests and forward runs
tools.screenermediumRun the screener
ai.chatmediumUse your AI connection
ai.toolslowAdd AI tools
data.ohlcvlowRead price bars
data.fundamentalslowRead fundamentals
data.calendarlowRead calendar events
data.providelowProvide market data
engine.runmediumRun its own program

net:<host> is a hostname with at least two parts such as api.example.com: no https://, no port, no path, no wildcard, no IP address and not localhost; at most 20 per extension. A call to any other host is refused.

Reading QuantCraft data needs its data.* permission; running tools through qc.tools.call needs the matching tools.* permission and asks the user the first time.


What a provider must return

A provider is a .js file (listed under dataProviders) that calls one define… function at its top level. Its output is checked by QuantCraft: bars are sorted, duplicates and impossible values are dropped, and future bars are ignored.

Bars: qc.provider.defineOhlcv

FunctionReceivesReturns
capabilities—{ timeframes?, maxBarsPerRequest?, rateLimit?: { requestsPerMinute, requestsPerDay? } }. Timeframes such as 1Min, 5Min, 1D. maxBarsPerRequest 1–10000 (default 1000); requestsPerMinute 1–600 (default 60)
searchSymbols(query)the search text (a string)[{ symbol, name? }]
getBars({ symbol, timeframe, start, end, limit })start and end in epoch millisecondsbars { t, o, h, l, c, v } (t in epoch milliseconds or ISO), oldest first, inside [start, end), at most limit
subscribe({ symbol, timeframe }) / unsubscribe(…)optionalstart / stop a live feed; push with qc.provider.emit or emitBatch
listSymbols(), getQuotes(symbols), getTicks(params)optionala symbol list; last prices for list rows; historical trades for tick replay

Live events: qc.provider.emit({ symbol, kind: "trade" | "bar", … }), or qc.provider.emitBatch([...]) for up to 500 at once (it resolves { accepted, dropped }).

Fundamentals: qc.provider.defineFundamentals

FunctionReturns
capabilities{ name?, rateLimit?: { requestsPerMinute, requestsPerDay? } }
getFundamentals({ symbol }){ symbol, entityName?, incomeStatement: { quarterly: { "2024-03-31": { …fields, filing_date: "2024-05-02" } }, yearly: {} }, balanceSheet, cashFlow, ratios, … }. Tables are keyed by period end. Give every report its filing_date (the day it became public): without it QuantCraft assumes 45 days (quarterly) or 90 days (yearly) after the period end. Throw an error with code no_fundamentals when the vendor has nothing
listSymbols({ cursor }){ symbols: [{ symbol, name, updatedAt }], next? }; return no next on the last page

Broker: qc.provider.defineBroker

Needs data.provide and trade.place, and works only for a Verified extension or your own project in Developer mode.

FunctionReturns / notes
capabilities{ name, mode: "paper" | "live" | "both", instruments: ["equity", "option", "crypto"], orderTypes, timeInForce, shorting, fractional, notional, extendedHours, replace, updates: "poll" | "push", rateLimit }. What you do not declare is never offered; an undeclared mode counts as paper
getAccount(){ cash, equity, buying_power, last_equity, currency, … }: money as numeric strings
getPositions()[{ symbol, qty, side, avg_entry_price, current_price, market_value, unrealized_pl }]
getOrders({ status, limit, cursor })an array, or { orders, next_cursor } to page. status: open, closed, all
getOrder({ id, client_order_id })one order. Used to find an order after a lost reply
placeOrder(order)the order as placed. Idempotent on order.client_order_id: placing the same id twice returns the first order. Throw an error with one of rejected, invalid_order, insufficient_funds, not_tradable, market_closed, halted, unsupported, forbidden only when the broker definitely refused; any other failure is treated as unknown
cancelOrder({ id }), replaceOrder, closePositionas named; replaceOrder only if replace is declared
listAssets({ asset_class, cursor, limit }){ assets: [{ symbol, name, asset_class, exchange, tradable, … }], next_cursor? }: fills the Trade symbol list
getAsset, estimateOrder, getOptionExpirations, getOptionChainoptional; the option functions are needed only if option is declared
qc.provider.emitBroker(…){ type: "changed" } asks QuantCraft to refetch; { type: "snapshot", account?, positions?, orders? } pushes the new state (declare updates: "push")

Order status is one of new, accepted, partially_filled, filled, canceled, expired, rejected, replaced, pending_cancel, unknown.

Test helpers

qc.testing.mockOhlcvProvider(options), qc.testing.mockFundamentalsProvider(options) and qc.testing.mockBrokerProvider(options) register a fake provider with deterministic data and switches for failures, so you can build against a source that never fails or costs money.

AI tools

Answer calls with qc.handle("tool.call", async ({ name, args }) => result). Return plain JSON and keep it small; throw an Error with a clear message for bad input.


Errors

CodeMeaning
invalid_requestThe message to QuantCraft was malformed.
unknown_methodThat qc function does not exist.
invalid_paramsThe arguments are wrong; the message says which.
permission_deniedThe permission is not in qcext.json, or the user turned it off.
consent_deniedThe user said no when asked.
rate_limitedToo many calls; slow down and retry later.
payload_too_largeThe message or result was too big.
unavailableIt is not available right now.
timeoutNo answer in time.
internal_errorA QuantCraft problem; report it with the extension's log.

Your own provider and tool errors can carry a code; the useful ones are rate_limited, quota_exceeded, unsupported_timeframe and no_fundamentals, which QuantCraft treats specially (it stops instead of retrying).

Limits

LimitValue
Size of one result12 MB
qc.data.* calls0.5 a second sustained, a burst of 10, 2 at once
qc.data.ohlcv.get bars1000 by default, at most 5000
Fundamentals and calendar rows40 by default, at most 200
Live events per emitBatch500
Packageup to 2000 files, 20 MB per file, 100 MB in total
Extension API — Documentation (1.0 (latest)) | QuantCraft