API Reference
Detailed catalog of properties, methods, and built-in technical indicators exposed via the global ctx runtime object.
Data Feeds
ctx.bars Property
Array of raw candlestick objects representing the loaded historical market feed.
// 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.
{
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.
// 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.
// 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.
// 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.
// 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.
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.
// Note: requires the full bars object array
const atr = ctx.atr(ctx.bars, 14);
ctx.vwap(barsArray) Indicator
Computes Volume Weighted Average Price.
const vwap = ctx.vwap(ctx.bars);
ctx.macd(dataArray, fast, slow, signal) Indicator
Computes Moving Average Convergence Divergence.
// 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.
// 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.
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.
// 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.
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).
// 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.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.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.
ctx.strategy.* (Tracking) Properties
Real-time tracking values for dynamic position sizing decisions inside the script.
- position_size: Returns the current open quantity (positive for Longs, negative for Shorts).
- position_avg_price: Returns the exact entry price of the current active trade.
- openprofit(): Returns the floating Unrealized PnL of the current trade.
Custom Strategy UI Methods
Allows customizing the Strategy Tester UI directly from scripts.
- setMetric(label, value, color): Injects a custom stats block into the top Key Stats dashboard.
- tagTrade(id, columnName, value, color): Appends a custom data column to the trade table for a specific trade.