Exciting Update: Version 1.0.6 is now available, introducing Direct Pine Script Mode, Pine Logs Runtime Bridge, Zero-Repaint Linting, Source Maps, Intrabar MFE/MAE Stats, and expanded Pine v5/v6 Transpiler Parity. Read more
Version: 1.0.6

API Reference

Searchable catalog of properties, methods, technical indicators, Pine Logs, v1.0.6 plotting/vector primitives, strategy analytics, and Direct Pine Mode globals on the ctx and transpiler runtime.

Data Feeds

ctx.bars Property

Array of raw candlestick objects representing the loaded historical market feed.

BacktestX Script
// Shape of a bar object:
{
  open: 101.25,   // Opening price
  high: 103.50,   // High price of the tick
  low: 99.80,     // Low price of the tick
  close: 102.10,   // Closing price
  volume: 240500,   // Volume units
  time: 1784931200 // Unix epoch in milliseconds
}

ctx.bounds Property

Object holding indicators about the visible chart boundaries on screen. Extremely useful to avoid executing drawing math outside the screen.

BacktestX Script
{
  chartW: 960,       // Canvas width in pixels
  chartH: 480,       // Canvas height in pixels
  startIndex: 45,    // Gutter index of leftmost visible bar
  endIndex: 125,     // Gutter index of rightmost visible bar
  numVisible: 80,    // Count of visible bars
  candleSlot: 8,     // Width + gap of one candlestick
  xOffset: 0         // Scroll offset in pixels
}

Coordinate Projections

ctx.priceToY(price) Method

Translates a price coordinate (e.g. 102.50) to the canvas Y pixel coordinate.

BacktestX Script
// Returns pixel coordinate (e.g. 142.6)
const yPos = ctx.priceToY(105.75);

ctx.barToX(index) Method

Translates a bar index (representing an offset in ctx.bars) to the horizontal X pixel coordinate on the canvas.

BacktestX Script
// Returns pixel X centered on that candle index
const xPos = ctx.barToX(88);

Canvas Drawings

The script engine wraps HTML5 Canvas rendering contexts. You can write standard shapes, paths, text, or styling attributes directly.

Styling Attributes

  • ctx.strokeStyle (string): Set line border color (e.g. '#2962ff').
  • ctx.fillStyle (string): Set solid fill color (e.g. 'rgba(41,98,255,0.1)').
  • ctx.lineWidth (number): Set thickness of lines in pixels.
  • ctx.globalAlpha (number): Set opacity multiplier (0.0 to 1.0).
  • ctx.font (string): Gutter text sizing and family (e.g. 'bold 11px Inter').
  • ctx.textAlign (string): Set text alignment ('left', 'center', 'right').

Path Methods

  • beginPath(): Start drawing coordinates.
  • moveTo(x, y): Lift drawing tip to coordinates.
  • lineTo(x, y): Draw linear segment from cursor to coordinates.
  • arc(x, y, r, startAngle, endAngle): Draw circular segments.
  • fillRect(x, y, w, h): Draw a solid rectangle box.
  • strokeRect(x, y, w, h): Draw a border rectangle outline.
  • roundRect(x, y, w, h, radius): Render rounded rectangle corners.
  • fillText(text, x, y): Draw text strings at coordinate.
  • measureText(text): Measures width metrics (returns { width }).
  • save() / restore(): Stack and recall drawing configs.

Technical Indicators

Pre-compiled math methods executing natively to avoid JavaScript performance bottlenecks during looping.

ctx.sma(dataArray, period) Indicator

Computes a Simple Moving Average array.

BacktestX Script
// Returns numeric array of equal length containing computed SMAs
const sma = ctx.sma(bars.map(b => b.close), 20);

ctx.ema(dataArray, period) Indicator

Computes an Exponential Moving Average array.

BacktestX Script
// Returns numeric array containing computed EMAs
const ema = ctx.ema(bars.map(b => b.close), 50);

ctx.rsi(dataArray, period) Indicator

Computes the Relative Strength Index (RSI) oscillator values.

BacktestX Script
const rsi = ctx.rsi(bars.map(b => b.close), 14);

ctx.atr(barsArray, period) Indicator

Computes the Average True Range (ATR) values using high, low, and close arrays.

BacktestX Script
// Note: requires the full bars object array
const atr = ctx.atr(ctx.bars, 14);

ctx.vwap(barsArray) Indicator

Computes Volume Weighted Average Price.

BacktestX Script
const vwap = ctx.vwap(ctx.bars);

ctx.macd(dataArray, fast, slow, signal) Indicator

Computes Moving Average Convergence Divergence.

BacktestX Script
// Returns: { line: [], signal: [], hist: [] }
const { line, signal, hist } = ctx.macd(bars.map(b => b.close), 12, 26, 9);

ctx.bollingerBands(dataArray, period, mult) Indicator

Computes Bollinger Bands standard deviation limits.

BacktestX Script
// Returns: { mid: [], upper: [], lower: [] }
const { mid, upper, lower } = ctx.bollingerBands(bars.map(b => b.close), 20, 2);

Drawing Utilities

ctx.plot(series, title, color, width) Utility

Automatically renders a numeric array overlay line on the chart canvas without manual looping.

BacktestX Script
const fastEMA = ctx.ema(bars.map(b => b.close), 9);
ctx.plot(fastEMA, 'EMA 9', '#ff9800', 2);

ctx.plotchar(series, char, title, color, size) Utility

Renders text markers (e.g. buy/sell characters like ▲ or ▼) directly above or below candles.

BacktestX Script
// Render "B" label under candles where indicator fires buySignal
ctx.plotchar(buySignals, 'B', 'Buy tag', '#4caf50', 12);

ctx.alert(condition, message) Utility

Dispatches a notification alert inside the trading dashboard if condition evaluates to true on the latest bar.

BacktestX Script
const crossover = close > emaVal && prevClose <= prevEmaVal;
ctx.alert(crossover, 'Bullish crossover detected on BTCUSD!');

ctx.table.new(rows, cols, position) Utility

Creates an overlay table grid positioned on one of the corners of the viewport (top_left, top_right, bottom_left, bottom_right).

BacktestX Script
// Returns: Table component wrapping grid cells
const metricsTable = ctx.table.new(2, 2, ctx.position.top_right);
metricsTable.cell(0, 0, 'RSI');
metricsTable.cell(0, 1, rsiVal.toFixed(2));
metricsTable.set_bgcolor(0, 0, '#1b1b1d');

Advanced Strategy Engine API

ctx.strategy.config(options) Method

Configures strategy execution settings and position sizing mode (percent_of_equity, cash, or fixed).

  • initial_capital: (Number) Starting account capital (e.g. 100000).
  • currency: (String) Base currency (e.g. 'USD').
  • default_qty_type: Sizing calculation mode: percent_of_equity, cash, or fixed.
  • default_qty_value: (Number) Allocation value (e.g. 15 for 15% compounding equity).

ctx.strategy.initial_capital(amount, currency) Method

Programmatically sets the starting capital for the strategy, which automatically updates the UI.

  • amount: (Number) The starting account balance (e.g., 10000).
  • currency: (String) Optional currency string (default is 'USD').

ctx.strategy.entry(id, direction, condArray, qty, limit, stop) Method

Executes a new trade.

  • id: (String) Custom name for the trade (e.g. "MACD Long"). Populates the "Trade ID" column.
  • direction: (String) 'Long' or 'Short'.
  • condArray: (Array of Booleans) The condition that triggers the entry.
  • qty: (Number) Position size (default is 1).
  • limit / stop: (Numbers) Optional limit or stop prices for entry.

ctx.strategy.order(id, direction, qty, limit, stop, options) Method

Places a standalone resting pending limit or stop order into the strategy execution queue.

  • id: (String) Unique order identifier.
  • direction: (String) 'long' or 'short'.
  • qty: (Number) Order size, or configure with options.qty_type.
  • limit / stop: (Numbers) Limit execution price or stop activation trigger price.

ctx.strategy.cancel(id) / cancel_all() Method

Explicitly cancels resting pending orders from the execution queue matching id, or purges all pending orders with cancel_all().

ctx.strategy.close(id, condArray, qty) Method

Closes an active position at the market price.

  • id: (String) The specific Trade ID you want to close.
  • condArray: (Array of Booleans) The condition that triggers the close.
  • qty: (Number) Optional quantity to partially close.

ctx.strategy.exit(id, condArray, profit, loss, limit, stop, trail_points, trail_offset) Method

Advanced exit logic with trailing stops and brackets.

  • profit / loss: (Numbers) Set absolute profit/loss targets.
  • limit / stop: (Numbers) Bracket exit orders.
  • trail_points / trail_offset: (Numbers) Enables dynamic trailing stops.

ctx.strategy.risk.* Methods

Functions to enforce risk rules, mathematically honored when generating Net Profit and Drawdown stats.

  • max_drawdown(value, type): Stops trading if the strategy loses a certain amount. (type can be 'percent' or 'cash').
  • max_intraday_loss(value, type): Caps the maximum loss allowed per day.
  • max_cons_loss_days(count): Halts strategy execution after consecutive losing sessions.
  • max_intraday_filled_orders(count): Hard-caps filled trades count allowed per calendar day.
  • max_position_size(count): Enforces strict position exposure limits.
  • allow_entry_in(direction): Restricts trade direction ('long', 'short', or 'all').

ctx.strategy.* (Costs, Pyramiding, Closed Trades & MFE/MAE) v1.0.6 Properties

Real-time and closed-trade telemetry alongside execution cost/pyramiding fields in ctx.strategy.config():

  • commission_type / commission_value / slippage / pyramiding: Configured in strategy.config() or Pine strategy(...) (percent, cash_per_contract, cash_per_order); deducts fill costs and scales position_avg_price.
  • position_size / position_avg_price / openprofit(): Active position units, weighted entry price, and floating PnL.
  • netprofit / grossprofit / grossloss / wintrades / losstrades / opentrades: Portfolio aggregates updated on every fill.
  • strategy.closedtrades.*: Per-trade arrays/accessors for profit, entry_price, exit_price, size, commission, entry_bar_index, exit_bar_index, mfe, and mae (with automatic Avg MFE / Avg MAE / Total Commission KPIs).

ctx.strategy.setMetric / tagTrade (strategy.set_metric / tag_trade) Methods

Allows customizing the Strategy Tester UI directly from JS or Direct Pine scripts.

  • setMetric(label, value, color) / strategy.set_metric(...): Injects a custom stats card into the Strategy Tester KPI header.
  • tagTrade(id, columnName, value, color) / strategy.tag_trade(...): Appends custom column badges to trade ledger rows.

Logging, Metadata, Sessions & Hover (v1.0.6)

ctx.log.{info, warn, error} / Pine log.{info, warning, error} v1.0.6

Emits {0}-formatted telemetry tagged with automatic bar index/timestamp (capped at MAX_SCRIPT_LOGS = 500, dispatched via cl:script-logs) supporting clickable bar jump navigation in the console.

ctx.session.* / ctx.ticker.heikinashi / request.timeframe_data v1.0.6

Exposes ctx.session.in_range(time, spec) plus Pine session.{ismarket, ispremarket, ispostmarket, regular, extended}, synthetic ctx.ticker.heikinashi(bars) / ticker.{standard, new, renko, kagi, pointfigure}, and MTF request.timeframe_data(symbol, tf, indName, ...args).

ctx.isHovered / is_hovered() & ctx.mouse / mouse.* Interactive

Hit-test bar/price regions via is_hovered(barIndex, priceLevel, width, height), read live pointer fields on mouse.{x, y, is_down, clicked}, or attach Pine tooltip= strings / ctx.registerTooltip.

ctx.ta.tr, pivots & v1.0.6 TA Adapters Indicator

Gap-aware ctx.ta.tr(bars, handle_na) / ta.tr, non-repainting 2-arg/3-arg ta.pivothigh / ta.pivotlow, ta.sar, ta.dmi, ta.donchian / ta.dc, ta.kama, plus adapters: lsma, lrc, mcg, cks, ce, fisher, crsi, cvd, bop, cho, ci, bbtrend, bbpb, bbw, env, hv, bbp, cc, efi, eom, and adr.

Plot Styles, Handles, Gradients & Vectors (v1.0.6)

plot.style_*, Assigned Handles, ctx.fill_plots & color.gradient v1.0.6

Supports all 8 plot.style_* constants (line/solid, linebr, stepline, histogram, columns, circles, cross, area), per-bar dynamic colors, offset, histbase, assigned handles p1 = plot(...) / h1 = hline(...), fill(p1, p2, { top_color, bottom_color, fillgaps }), and color.gradient(color1, color2, vertical = true).

chart.point.*, polyline.new, polygon.new & fib.new Mutators Vector

Coordinate anchors via chart.point.{new, from_index, from_time, copy}, vector shapes via polyline.new(points, curved, closed, xloc, line_color, fill_color, line_style, line_width) and polygon.new(points, color, fill_color, width), plus mutable Fibonacci handles (.set_levels, .set_color, .set_extend, .set_first_point, .set_second_point).

Direct Pine Mode Globals & Compiler Directives (v1.0.6)

Derived Series, Calendar, barstate.* & syminfo.* Pine v5/v6

Built-in hl2, hlc3, ohlc4, hlcc4, last_bar_index, last_bar_time, timenow, calendar helpers (year, month, weekofyear, dayofmonth, dayofweek, hour, minute, second), barstate.{isfirst, islast, ishistory, isrealtime, isnew, isconfirmed, islastconfirmedhistory}, and metadata-backed syminfo.{ticker, tickerid, prefix, root, description, currency, basecurrency, timezone, mintick, pointvalue, type}.

//@strict-no-repaint, //@js-raw, Constructs & Stdlib Compiler

transpilePineToJSWithMap(pineCode) returns { code, sourceMap, diagnostics, strictNoRepaint, error }. Supports //@strict-no-repaint lookahead auditing, //@js-raw ... //@end-js-raw raw Canvas 2D blocks, x = if ... / x = switch ... expressions, countdown for ... by -1, type/enum/method, tuple returns [a, b] = fn(), math.* (pow, sqrt, log, exp, sign, trig, pi), and str.* (trim, startswith, endswith, replace, format_time).