QuantScript is a domain-specific language designed from the ground up for creating, testing, explaining, and deploying automated trading strategies. Learn about the architecture, design principles, and philosophy.
QuantScript is a domain-specific language designed from the ground up for creating, testing, explaining, and deploying automated trading strategies.
Its primary audience is the retail quant: traders, strategy writers, technical analysts, and developers who want to move from an idea to a working strategy without assembling a large collection of unrelated data, backtesting, charting, broker, risk, and deployment libraries.
QuantScript is not a general-purpose programming language. It provides a deliberately constrained, trading-native environment in which market data, indicators, strategy logic, risk controls, order execution, visualisation, backtesting, forward testing, and live deployment share one coherent model.
A QuantScript strategy progresses through the full lifecycle:
Describe → Visualise → Backtest → Explain → Forward-test → Deploy → Monitor
The same strategy logic remains recognisable throughout this lifecycle. Changing a data provider, broker, execution mode, renderer, or deployment environment does not require rewriting the core strategy.
Try QuantScript in your browser at quantscript.com/playground — no installation required.
The following principles guide every QuantScript language and platform decision:
QuantScript treats AI-assisted authoring, translation, debugging, and explanation as an architectural requirement, not an afterthought. Fully named arguments, explicit namespaces, uniform result objects, and structured trade intent (reason/context/tags) make strategy code easy for AI systems to generate, review, and analyse correctly.
Strategies can reason over multiple symbols, timeframes, and alternative datasets (sentiment, fundamentals, news, economic indicators) within a single execution. The data.loadCandles() API loads secondary OHLCV feeds with explicit alignment semantics, and the architecture accommodates non-OHLCV data sources through the same adapter and Feed model.
Strategy logic does not depend on any particular data vendor's response format, authentication scheme, or symbol convention. Data enters through the Canonical Data Model via provider adapters. Switching data providers requires changing the adapter declaration, not rewriting strategy code.
The script-facing trade.* API operates against the Canonical Trading Model, not against any broker-specific API. Target broker classes include crypto exchanges, stock brokers, and FX/CFD brokers — all behind one universal trade.buy(), trade.createOrder(), etc. Switching brokers requires changing the adapter declaration, not rewriting trading logic.
QuantScript ships a built-in simulation engine for backtest and forwardtest modes. Rather than monolithic fill logic, SimEngine composes its behaviour from orthogonal strategy axes (position model, fill model, fee model, margin model) exposed as named execution profiles — bar-match-netting, crypto-spot, us-equities — so strategies can be tested reproducibly against a wide range of broker behaviours.
QuantScript separates computation from presentation. The engine writes derived series, chart intent, and trade events into the FrameModel without knowing who will consume them. Renderers are pluggable, decoupled subscribers. The same script runs identically in CLI (headless), browser (interactive charts), and cloud deployment (no UI at all).
Both candle-by-candle bar iteration (Pine-style) and tick-level reactive execution (MQL-style) are first-class through the same event model. The language is designed for retail quant use cases — not professional HFT, which requires specialised low-latency infrastructure outside QuantScript's scope.
Every trade decision should be traceable. The reason/context/tags convention, structured Run Journals, and console.journal() all serve this goal. Runs produce lightweight, machine-readable execution timelines for debugging, replay, AI-assisted explanation, and reproducibility.
Strategies declare risk limits as top-level declarations alongside data and broker configuration. The risk.* namespace provides granular control over per-order validation, portfolio exposure, drawdown limits, circuit breakers, and kill switches. Every trade request passes through RiskGuard before reaching the broker — strategy intent is always subordinate to account safety.
QuantScript deliberately favours clarity over terseness. A slightly more verbose trade instruction is preferable when it is easier for a human to review, an AI agent to generate correctly, and the runtime to validate safely. Familiar JavaScript-like syntax keeps the learning curve minimal.
QuantScript does not attempt to reproduce any existing language or platform exactly. Instead, it takes proven ideas from several ecosystems and combines them into a coherent QuantScript-native model.
| Inspiration | What QuantScript Draws From |
|---|---|
| Pine Script / TradingView | Chart-first strategy development, candle-by-candle execution, historical series references, incremental technical indicators, and a shared execution model for indicators and strategies. |
| MQL / MetaTrader | Tick-driven execution, broker events, orders, deals, positions, timers, account state, and the operational discipline required for live automated trading. |
| CCXT | Provider and broker portability through unified interfaces, capability discovery, and adapter-driven integration. |
| pandas | Multiple DataFrames and Series, explicit dataset alignment, as-of joins, resampling, forward-fill and gap handling, and the ability to combine multiple symbols, timeframes, and alternative datasets. |
| QuantConnect / Freqtrade | Reproducible backtesting, execution modelling, portfolio-aware risk management, deployment guardrails, continuous account monitoring, and operational controls such as kill switches. |
| JavaScript / TypeScript | Familiar syntax, lexical structure, functions, arrays, objects, and broadly understood programming concepts that are readable to both developers and AI coding systems. |
QuantScript is not constrained by compatibility with any one of these systems. Syntax parity and function-name parity are secondary to clarity, portability, safety, and consistency. Where an existing convention would make QuantScript ambiguous, broker-specific, difficult to analyse, or difficult to generate reliably, QuantScript adopts a cleaner DSL-specific design.
AI-assisted coding is becoming a normal part of software development, and automated trading languages should be designed with this reality in mind. QuantScript treats AI-assisted authoring, translation, debugging, testing, and explanation as architectural requirements rather than optional platform additions.
The language favours:
data.*, ta.*, trade.*, risk.*, and event.*snake_case for DSL named argument keysreason, context, and tagstrade.buy({
symbol: "BTCUSD",
qty: 0.1,
stopLoss: 60200,
takeProfit: 62800,
comment: "EMA cross entry",
reason: "EMA20 crossed above EMA50 with RSI confirmation",
context: { close: candle.close, ema_20, ema_50, rsi_14 },
tags: ["momentum", "ema_cross"]
});AI may assist with writing and analysing strategies, but execution remains governed by explicit QuantScript code, deterministic runtime semantics, broker capabilities, and platform risk controls. AI must not silently change live strategy behaviour.
Website: quantscript.org
QuantScript Language defines the portable strategy model: syntax and semantics; declarations and event handlers; candle, tick, timer, and broker events; Series and DataFrame behaviour; technical-analysis functions; canonical data and trading APIs; execution modes and safety rules.
Website: quantscript.com
QuantScript Platform provides an implementation of that language: data-provider and broker adapters; simulated and live execution; chart and report renderers; CLI and browser tooling; cloud deployment; Run Journals and manifests; AI-assisted analysis; Strategy Playground and Strategy Arena workflows.
A .qs script has a well-defined meaning independent of a particular user interface, broker, data vendor, or cloud provider. Platform-specific functionality is exposed through declared capabilities and adapters rather than embedded into strategy logic.
QuantScript places two provider-neutral canonical models between strategy code and the external world:
These models are the stable boundaries of the language. External providers and brokers differ widely, so QuantScript uses factory, registry, and adapter patterns on both sides:
External Data Sources
|
Data Factory / Registry / Adapters
|
Canonical Data Model
|
FrameModel
|
QuantScript Strategy
|
Canonical Trading Model
|
Broker Factory / Registry / Adapters
|
Simulated or Real BrokerThis allows strategy code to remain stable while data vendors, brokers, exchanges, simulation engines, and deployment environments change around it.
QuantScript defines four official language modes. Terms such as interactive, visualise, replay, and analysis are platform or workflow concepts — they map onto one of the four language modes rather than becoming additional core modes.
For charting, indicators, overlays, panes, alerts, and analysis without trade execution.
For deterministic historical simulation using historical data and a simulated broker.
For live or replayed market data with simulated execution. The natural mode for paper-live validation and Strategy Arena.
For live market data and real broker execution with risk controls, reconciliation, and audit trails.
| Property | indicator | backtest | forwardtest | live |
|---|---|---|---|---|
| Trade execution | No | Simulated | Simulated | Real broker |
| Historical batch | Yes | Yes | Optional replay | No |
| Streaming data | Optional | No | Yes | Yes |
| Deterministic | Yes | Yes | At configured granularity | No |
| Broker connection | No | No | No | Yes |
QuantScript supports both candle-driven and event-driven strategies through one consistent event model:
event.onCandle() provides Pine-style bar-by-bar execution.event.onTick() provides MQL-style reactive execution.event.onNewCandle() fires reactively on bar completion.event.onTimer() supports scheduled logic at configurable intervals.The active mode determines which clock drives execution: historical bar time in indicator and backtest modes; streaming market time in forward-test mode; market and broker events in live mode. The language presents one consistent event model even though the underlying host may use batch execution, polling, streaming, or serverless wake-ups.
QuantScript scripts separate declarations from event handlers. Declarations describe the execution environment: the mode, primary market data, optional tick streams, broker, and risk limits. Event handlers contain the strategy logic that reacts to candles, ticks, timers, and broker events.
mode(mode_type: "backtest", script_name: "My Strategy");
candles(
"BTCUSD",
resolution_type: "1h",
bars: 720,
provider: "demotrader"
);
risk(
max_position_pct: 25,
daily_loss_limit: 3
);
broker(adapter: "sim", config: {
initial_capital: 100000,
commission: 0.05,
execution_strategy: "bar-match-hedging"
});
event.onCandle((candle) => {
// Strategy logic
});The declaration model keeps configuration explicit and allows the runtime to validate requirements before execution begins.
SimEngine is QuantScript's built-in simulation engine for backtest and forwardtest modes. Rather than monolithic fill logic, SimEngine composes its behaviour from four orthogonal strategy axes:
| Axis | Purpose | Options |
|---|---|---|
| Position | How positions are tracked per symbol | netting, hedging, isolated-margin, cross-margin |
| Fill | How orders match against market data | bar-touch, bar-close, mark-price, orderbook |
| Fee | How commissions are calculated | none, per-lot, maker-taker, per-share, tiered |
| Margin | Leverage, liquidation, funding | none, simple, reg-t, funding-rate, portfolio |
Common combinations are available as named presets:
| Preset | Target |
|---|---|
bar-match-netting | Default (Pine Script-style) |
bar-match-hedging | MT5 hedging accounts |
crypto-spot | Binance/OKX spot |
crypto-futures | Perpetual futures |
us-equities | Alpaca, IBKR equities |
SimBrokerAdapter wraps SimEngine behind the same BrokerAPI interface used by live brokers. Backtest and forwardtest modes use the same script-facing trade.* calls as live mode — the only difference is that fills are simulated rather than executed by a real broker.
Risk management is a first-class platform concern. A strategy may request a trade, but it does not have unconditional authority to create broker exposure. Every live trade request must pass through RiskGuard, which evaluates it against platform policy, broker constraints, account condition, deployment limits, and strategy-level controls.
RiskGuard operates both before and after trade submission: before submission, it checks whether a proposed order is allowed; after broker or account updates, it re-evaluates whether trading may safely continue.
Four control categories mirror the risk.* DSL sub-namespaces:
risk.require.* — validates that the connected broker, account, instruments, and execution model are suitable for the strategy.risk.trade.* — validates each proposed order and position change before submission (direction, quantity, loss per trade).risk.portfolio.* — evaluates aggregate exposure, leverage, drawdown, losses, concentration, and account-wide risk.risk.protection.* — pauses or restricts trading in response to repeated losses, stale data, broker failures, or abnormal strategy behaviour.Fail-Closed Principle: When QuantScript cannot establish the true account state or risk exposure, it should block new risk rather than assume conditions are safe.
QuantScript is guided by the following commitments: