Appearance

Personalize your experience

Mode
Accent Color
Direction
QuaScript C++ Engine & Quant DSL

QuaScript C++ Engine & Quant DSL

Coding / QuaScript

Sub-microsecond quantitative algorithmic scripting engine powered by C++20 bytecode VM, SIMD AVX2 acceleration, cache-aligned columnar memory, and direct multi-broker OMS integration.

1. Overview & Execution Philosophy

QuaScript is built for high-frequency and high-density trading: scripts compile to bytecode for a C++20 virtual machine that runs next to the market , with no garbage collector, no network roundtrip per evaluation and memory laid out for the CPU cache.

QuaScript is engineered as a zero-compromise, bare-metal quantitative language. It pairs a clean, declarative syntax with sub-microsecond C++20 compiled bytecode performance.

Sub-Microsecond Latency

34.8 – 45.2 ns per bar evaluation speed. Over 28 Million bars/second single-core throughput.

Zero-GC Execution

circular ring buffers and 64-byte cache-aligned memory structs (alignas(64)) eliminate garbage collection pauses.

Direct QuaCharts Bridge

integration with @quatick/charts via 2.0 GPU shaders and Canvas 2D pipelines.

HFT Broker OMS

Direct lock-free shared memory (<50ns IPC) pipeline connecting signals directly to execution brokers.

2. Engine Benchmarks

Measured performance, memory and operational figures of the QuaScript engine:

Metric / FeatureQuaScript (C++20 Engine)
Throughput (Bars/sec)22M – 28.8M bars/s
Latency per Bar34.8 – 45.2 ns
10,000 Bars Eval Time0.35 ms
1,000,000 Bars Eval Time38.5 ms
Memory per 1M Bars~8 MB (SoA Columnar)
Garbage Collection (GC)0 ms (Zero-GC Arenas)
Real-Time Tick Latency< 1 μs (Direct SHM)
Hardware VectorizationAVX2 / NEON SIMD
Concurrent Strategies1,000,000+ Strategies
Modern Web & Cloud APINative WebGL + REST/WS
★
Pro tip:Key Architectural Takeaway: QuaScript runs compiled bytecode on a C++ VM with the safety of a typed, high-level domain language. By pre-allocating contiguous circular buffers and utilizing 64-byte cache-line aligned structs (alignas(64)), 1,000,000 strategies require only 64 MB of RAM—fitting completely into modern server L3 CPU caches.

Empirical Validation & 1M Bar Benchmark Results

Every performance metric cited in this benchmark is reproducible using standard Linux/macOS profiling tools (perf, callgrind). Using the C++20 CLI (quas bench) on a 3.2 GHz CPU with GCC 13/Clang 17 (-O3 -mavx2), 1,000,000 synthetic bars yield the following exact measured times:

Strategy ScriptExecution DetailsTotal Time (1M Bars)Latency / BarThroughput
volume_osc.qsFast/Slow Volume EMA Ratio32.83 ms32.8 ns30.5 M bars/s
sma_cross.qsSMA 10, SMA 30, Cross, Broker Fills, MTM Equity38.52 ms38.5 ns26.0 M bars/s
rsi_reversion.qsRSI 14, ATR stop/limit brackets, OMS state machine51.20 ms51.2 ns19.5 M bars/s
bollinger.qsSMA 20, Running Stdev, 2-sigma bands, Extremas60.16 ms60.2 ns16.6 M bars/s
bot_breakout.qsDonchian 20 channel, Sizing, Bot order export60.18 ms60.2 ns16.6 M bars/s

The 5 Architectural Pillars of Sub-Microsecond Execution

  • Threaded-Code Direct Labels (goto *I->h): Rather than a switch-case jump where branch mispredictions exceed 40%, QuaScript compiles opcodes into direct address pointers. Handlers jump directly to the next handler (goto *pc->h), slashing branch mispredictions to <1.8%.
  • Power-of-Two Bitmask Ring Buffers (bar & mask): Historical series indexing uses bitwise AND (bar & mask, 1 cycle) instead of modulo (%, 10–25 cycles). Ring buffers stay permanently hot in L1 Cache (4 cycles / ~1 ns) with >99.98% hit rates.
  • Zero-GC Arena : Zero malloc(), zero resizes, and zero heap fragmentation on the hot . 100% deterministic with no garbage-collector pauses.
  • Flattened Single-Tier Opcodes: indicators (sma, ema, rsi) are compiled into dedicated VM opcodes with O(1) accumulators, eliminating function call frames.
  • Structure-of-Arrays (SoA) & AVX2: Price is stored in contiguous columnar arrays. 64-byte cache lines are 100% utilized, allowing AVX2 SIMD instructions to 4 doubles per cycle.

Real-World Bottleneck Disclosure: JSON Serialization vs Direct GPU Buffers

A critical finding in production HFT systems: while the C++ engine computes 1,000,000 bars in 38.5 ms, serializing those numbers to JSON format requires 1,200 ms (1.2 seconds) and writes 107 MB of ASCII . String formatting is 30x slower than the mathematical computation!

To eliminate this bottleneck, Quatick completely bypasses JSON in production: series is mapped directly into binary Float32Array buffers uploaded to GPU VRAM via 2.0, while order signals through lock-free POSIX shared memory ring buffers (<50ns IPC) straight to broker execution engines.

3. Script Header & Execution Modes

Every QuaScript starts with a header block that names the script and sets its kind, pane and :

QuaScript Header Example
analysis "Supertrend Volatility Stop" {    overlay = true    render  = canvas}/// Trailing ATR stop with trend-colored candles.factor = param.float(3.0, title = "Multiplier", min = 0.5, max = 10, step = 0.5)len    = param.int(10, title = "ATR length", min = 1, max = 100)(stop, dir) = ta.supertrend(factor, len)bull = close > stoprender.line(stop, "Supertrend", color = bull ? color.emerald.400 : color.rose.400, width = 2)render.candle_color(bull ? color.emerald.500 : color.rose.500)render.mark(ta.cross_up(close, stop), shape = shape.triangle_up, at = anchor.below_bar, color = color.emerald.400, text = "Long")
FieldTypeDescription
render = canvas | webgl | webgpustringSelects the rendering pipeline: canvas for high-DPI splines and , or webgpu for dense heatmaps, fans and bands drawn on the GPU.
overlay = true | falsebooleantrue renders directly on top of primary price action; false opens a separate synchronized sub-pane.
strategy "Name" { capital = 10000, commission = 0.04 }headerA header switches the VM into / OMS with capital, commission and slippage tracking.

4. Built-in Technical Analysis Functions

QuaScript provides hundreds of optimized, single-pass mathematical indicators. Each function runs in $O(1)$ amortized time per bar:

  • Moving averages: ta.sma, ta., ta.wma, ta.dema, ta.tema, ta.hull, ta.vwma, ta.rma, ta.kaufman, ta.jurik, ta.kalman
  • Oscillators: ta., ta.macd, ta.stoch, ta.cci, ta.williams, ta.roc, ta.fisher, ta.tsi
  • Trend & volatility: ta., ta., ta.keltner, ta.donchian, ta., ta.adx, ta.psar, ta.ichimoku
  • Volume: ta.vwap, ta.obv, ta.money_flow, ta.volume_osc, ta.volume_profile
  • & : stat.linreg, stat.zscore, stat.hurst, stat.entropy, hft.garch, hft.vpin, hft.kyle_lambda
  • Bar : open, high, low, close, volume, time, bar.index, bar.typical, bar.mid
Multi-Horizon Moving Average Ribbon with Splines
analysis "Moving Average Ribbon" {    overlay = true}fast_len = param.int(20, title = "Fast", min = 1, max = 500)mid_len  = param.int(50, title = "Mid", min = 1, max = 500)slow_len = param.int(100, title = "Slow", min = 1, max = 500)base_len = param.int(200, title = "Base", min = 1, max = 500)p1 = render.spline(ta.sma(close, fast_len), "SMA fast", color = color.blue.500, width = 1)p2 = render.spline(ta.sma(close, mid_len), "SMA mid", color = color.cyan.500, width = 1)p3 = render.spline(ta.sma(close, slow_len), "SMA slow", color = color.orange.500, width = 2)p4 = render.spline(ta.sma(close, base_len), "SMA base", color = color.pink.500, width = 2)render.band(p1, p2, color = color.blue.500, opacity = 0.08, title = "Fast ribbon")render.band(p3, p4, texture = "gradient", upper_color = color.orange.500, lower_color = color.pink.700, opacity = 0.18, title = "Slow ribbon")

5. Financial & Institutional Intelligence

QuaScript natively incorporates fundamental valuation and institutional capital flows directly on chart timeframes without external joins:

P/E Valuation Band and Institutional Flows
analysis "P/E Valuation and Flows" {    overlay = false}eps    = param.float(18.5, title = "Annual EPS", min = 0.01, max = 1000)median = param.float(22, title = "Median P/E", min = 1, max = 100)pe = close / epsrender.line(pe, "P/E", color = color.blue.500, width = 2)render.level(median, "Fair value", color = color.slate.500)render.level(median * 1.25, "Overvalued (+25%)", color = color.rose.500)render.level(median * 0.75, "Undervalued (-25%)", color = color.emerald.500)render.histogram(financial.fii_net(), "FII net", color = color.translucent(color.sky.400, 50), pane = 1)render.histogram(financial.dii_net(), "DII net", color = color.translucent(color.amber.400, 50), pane = 1)render.mark(ta.cross_up(pe, median * 1.25), shape = shape.triangle_down, at = anchor.above_bar, color = color.rose.500, text = "Rich")

6. User-Defined Types (UDTs) & Enums

QuaScript supports structured User-Defined (struct) and type-safe enumerations with pattern-matching match expressions:

Type-safe Enum Switch Oscillator
analysis "Oscillator Selector" {    overlay = false}// An enum-driven choice of oscillator. The subject of the match is a param, so only the// selected oscillator is computed and no conditional-state warning is raised.enum OscType {    rsi(title = "Relative Strength")    macd(title = "MACD Momentum")    cci(title = "Commodity Channel")}choice = param.choice(OscType.rsi, title = "Oscillator")len = param.int(14, title = "Period", min = 2, max = 100)osc = match choice {    case OscType.rsi { ta.rsi(close, len) }    case OscType.macd {        (line, _, _) = ta.macd(close, 12, 26, 9)        line    }    case OscType.cci { ta.cci(bar.typical, len) }}hi = choice == OscType.cci ? 100 : choice == OscType.macd ? 0 : 70lo = choice == OscType.cci ? -100 : choice == OscType.macd ? 0 : 30render.line(osc, "Oscillator", color = color.purple.500, width = 2)render.line(hi, "Upper", color = color.rose.500, stroke = style.dashed, width = 1)render.line(lo, "Lower", color = color.emerald.500, stroke = style.dashed, width = 1)render.mark(ta.cross_up(osc, hi), shape = shape.triangle_down, at = anchor.above_bar, color = color.rose.500, text = "OB")render.mark(ta.cross_down(osc, lo), shape = shape.triangle_up, at = anchor.below_bar, color = color.emerald.500, text = "OS")alert.rule(ta.cross_up(osc, hi), "Overbought", "The selected oscillator entered the upper zone")alert.rule(ta.cross_down(osc, lo), "Oversold", "The selected oscillator entered the lower zone")

7. Calling QuaScript in Qua Web Charts

You can instantiate and execute QuaScript directly within @quatick/charts using the addQuaScript() API:

Frontend Execution via @quatick/charts
import { createChart } from '@quatick/charts';const chart = createChart(containerElement, {  width: 1200,  height: 600,  theme: 'dark',});// Load candlestick historical datachart.setData(ohlcvCandles);// Execute native QuaScript indicatorchart.indicators.addQuaScript(  'supertrend-v2',  `analysis "Supertrend" { overlay = true }   factor = param.float(3.0, title = "Factor")   len = param.int(10, title = "Length")   (stop, dir) = ta.supertrend(factor, len)   render.line(stop, "Supertrend", color = color.blue.500, width = 2)   render.candle_color(close > stop ? color.emerald.500 : color.rose.500)  `,  ohlcvCandles,  { overlay: true });

Related articles

  • The Backtest Engine

    Backtesting / Engine

    One service backtests every kind of strategy on Quatick. Each source type runs on the engine built for it, and every result is measured with the same…

  • Writing DSL by Hand

    Coding / Strategy DSL

    Authoring strategy JSON directly: the minimum document, small constructors that keep it readable, validating before anything runs, generating variants, and…

  • Backtesting in Python and C++

    Backtesting / SDKs

    The quatick Python package and the header-only C++ library let you import indicators, backtest on your own machine and send the same file to Quatick.…

  • C++ SDK Reference

    Backtesting / SDKs / C++

    Header-only C++20 (packages/quatick-backtest-cpp): the position simulator, an event-driven engine with the same order rules as Python, analytics, a parallel…

  • Engines — Python vs C++

    Automation / Predefined Strategies

    Two independent implementations of the same grid semantics, consuming the same config and the same command channel. The choice is a runtime choice, not a…

  • Ghost Feed

    Charts / Drawing Tools / Forecasting

    An overlay of another symbol's price data on the current chart. Ghost feeds compare correlated instruments, analyze relative strength, and identify…

  • Indicator Reference

    Automation / Strategy Builder / Reference

    All 94 indicators the strategy engine computes, grouped as in the builder's picker, with their parameters, outputs and the range of values each output can take.

  • Step 5 — Entry Signals

    Automation / Strategy Builder / Wizard Steps

    Where the strategy is actually written. Conditions, operators, nesting, order configuration, multiple entry sets, and the re-entry engine behind Grid, DCA…

  • Step 6 — Exit & Risk

    Automation / Strategy Builder / Wizard Steps

    Exit conditions, stop loss, take profit, staged partial exits and portfolio-level limits. The step that decides whether a losing trade costs you a percent…

Browse all knowledge base articles →