Our Vision#

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.

Design Principles#

The following principles guide every QuantScript language and platform decision:

🤖

Designed with AI in Mind

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.

📊

Multi-Dataset Support

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.

🌐

Data Provider Agnostic

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.

🔄

Broker Agnostic

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.

Composable SimEngine

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.

🖥

Renderer Agnostic; Headless-Capable

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).

Per-Candle and Per-Tick Execution

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.

🔎

Auditability & Explainability

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.

🛡

Risk Management is First-Class

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.

💻

Clarity Over Brevity

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.

Best-of-Breeds Design#

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.

InspirationWhat 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.

Designed for Human and AI Authors#

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:

  • Familiar JavaScript- and TypeScript-like syntax and control flow
  • Explicit namespaces such as data.*, ta.*, trade.*, risk.*, and event.*
  • Descriptive names and fully named arguments
  • Object-shaped parameters and uniform result objects
  • Conventional snake_case for DSL named argument keys
  • Explicit execution modes and capability discovery
  • Structured strategy intent through reason, context, and tags
  • Deterministic execution and machine-readable Run Journals
QuantScript
trade.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.

Language and Platform Separation#

QuantScript Language

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.

QuantScript Platform

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.

Canonical Models#

QuantScript places two provider-neutral canonical models between strategy code and the external world:

  1. The Canonical Data Model, which normalises incoming market and alternative data into QuantScript Feeds, Series, Candles, Ticks, and timelines.
  2. The Canonical Trading Model, which normalises outgoing trade requests and incoming broker state into orders, fills, positions, accounts, instruments, and capabilities.

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:

  • Incoming data is resolved through data-provider factories and registries, then normalised by data adapters.
  • Outgoing trade requests are routed through broker factories and registries, then translated by broker adapters.
  • Broker responses, fills, positions, and account state are mapped back into the Canonical Trading Model.
Architecture Flow
External Data Sources
        |
Data Factory / Registry / Adapters
        |
Canonical Data Model
        |
FrameModel
        |
QuantScript Strategy
        |
Canonical Trading Model
        |
Broker Factory / Registry / Adapters
        |
Simulated or Real Broker

This allows strategy code to remain stable while data vendors, brokers, exchanges, simulation engines, and deployment environments change around it.

Four Official Modes#

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.

indicator

For charting, indicators, overlays, panes, alerts, and analysis without trade execution.

backtest

For deterministic historical simulation using historical data and a simulated broker.

forwardtest

For live or replayed market data with simulated execution. The natural mode for paper-live validation and Strategy Arena.

live

For live market data and real broker execution with risk controls, reconciliation, and audit trails.

Propertyindicatorbacktestforwardtestlive
Trade executionNoSimulatedSimulatedReal broker
Historical batchYesYesOptional replayNo
Streaming dataOptionalNoYesYes
DeterministicYesYesAt configured granularityNo
Broker connectionNoNoNoYes

Event-Driven Execution#

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.
  • Broker lifecycle events expose changes to orders, fills, and positions.

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.

Script Declaration Model

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.

QuantScript
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#

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:

AxisPurposeOptions
PositionHow positions are tracked per symbolnetting, hedging, isolated-margin, cross-margin
FillHow orders match against market databar-touch, bar-close, mark-price, orderbook
FeeHow commissions are calculatednone, per-lot, maker-taker, per-share, tiered
MarginLeverage, liquidation, fundingnone, simple, reg-t, funding-rate, portfolio

Common combinations are available as named presets:

PresetTarget
bar-match-nettingDefault (Pine Script-style)
bar-match-hedgingMT5 hedging accounts
crypto-spotBinance/OKX spot
crypto-futuresPerpetual futures
us-equitiesAlpaca, 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.

RiskGuard#

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.

Architectural Commitments#

QuantScript is guided by the following commitments:

  1. Trading-native, not general-purpose — The language is optimised for automated strategy development and deployment.
  2. Portable strategy logic — Data providers, brokers, renderers, and deployment environments are replaceable infrastructure.
  3. Canonical boundaries — External data enters through the Canonical Data Model; trade intent and broker state pass through the Canonical Trading Model.
  4. Adapters over vendor leakage — Provider- and broker-specific details remain behind factories, registries, and adapters.
  5. Explicit time semantics — Candle completion, alignment, gaps, and lookahead behaviour must be clear.
  6. One runtime source of truth — The FrameModel coordinates inputs, derived outputs, and execution state.
  7. Same strategy lifecycle — One strategy should progress naturally from visual analysis to backtesting, forward testing, and live deployment.
  8. Risk before execution — Strategy intent is always subordinate to platform and account safety.
  9. Explainability by default — Runs, decisions, assumptions, and outcomes should be inspectable by humans and AI.
  10. Clarity over brevity — The language should be easy to read, generate, validate, and audit.