Tutorials & Presets
Step-by-step guides demonstrating both custom Canvas 2D JavaScript overlays and v1.0.6 Direct Pine Mode indicators & zero-repaint strategies.
EMA Crossover Indicator
In this tutorial, we will write a script that calculates a fast EMA (9 periods) and a slow EMA (21 periods). When the fast EMA crosses above the slow EMA, it renders a green buy arrow. When it crosses under, it renders a red sell arrow.
Key Concepts: Coordinate conversions (priceToY, barToX), path drawing operations, and indicator functions (ema).
const bars = ctx.bars;
const bounds = ctx.bounds;
if (!bars || bars.length < 21) return;
const closePrices = bars.map(b => b.close);
const ema9 = ctx.ema(closePrices, 9);
const ema21 = ctx.ema(closePrices, 21);
// 1. Draw EMA 9 (Red Line)
ctx.beginPath();
ctx.strokeStyle = '#ef5350';
ctx.lineWidth = 1.5;
let started9 = false;
for (let i = Math.max(0, Math.floor(bounds.startIndex) - 1); i <= Math.ceil(bounds.endIndex) + 1; i++) {
if (isNaN(ema9[i])) continue;
const x = ctx.barToX(i);
const y = ctx.priceToY(ema9[i]);
if (!started9) { ctx.moveTo(x, y); started9 = true; } else ctx.lineTo(x, y);
}
ctx.stroke();
// 2. Draw EMA 21 (Blue Line)
ctx.beginPath();
ctx.strokeStyle = '#2962ff';
ctx.lineWidth = 1.5;
let started21 = false;
for (let i = Math.max(0, Math.floor(bounds.startIndex) - 1); i <= Math.ceil(bounds.endIndex) + 1; i++) {
if (isNaN(ema21[i])) continue;
const x = ctx.barToX(i);
const y = ctx.priceToY(ema21[i]);
if (!started21) { ctx.moveTo(x, y); started21 = true; } else ctx.lineTo(x, y);
}
ctx.stroke();
// 3. Draw Signal Arrows
for (let i = Math.max(1, Math.floor(bounds.startIndex) - 1); i <= Math.ceil(bounds.endIndex) + 1; i++) {
const prevFast = ema9[i - 1];
const prevSlow = ema21[i - 1];
const currFast = ema9[i];
const currSlow = ema21[i];
if (isNaN(prevFast) || isNaN(prevSlow) || isNaN(currFast) || isNaN(currSlow)) continue;
const crossedUp = prevFast <= prevSlow && currFast > currSlow;
const crossedDown = prevFast >= prevSlow && currFast < currSlow;
const x = ctx.barToX(i);
if (crossedUp) {
const y = ctx.priceToY(bars[i].low) + 12;
ctx.fillStyle = '#089981';
ctx.beginPath();
ctx.moveTo(x, y - 6);
ctx.lineTo(x - 6, y + 6);
ctx.lineTo(x + 6, y + 6);
ctx.closePath();
ctx.fill();
} else if (crossedDown) {
const y = ctx.priceToY(bars[i].high) - 12;
ctx.fillStyle = '#f23645';
ctx.beginPath();
ctx.moveTo(x, y + 6);
ctx.lineTo(x - 6, y - 6);
ctx.lineTo(x + 6, y - 6);
ctx.closePath();
ctx.fill();
}
}
RSI Signal Dots & Alerts
This script computes a 14-period RSI. When RSI crosses below 30 (oversold) and rises back, it places a green circle marker on the low of the candlestick. If RSI crosses above 70 (overbought), it places a red circle marker on the high. It also triggers an automated alert callback via ctx.alert() on the latest candle.
const bars = ctx.bars;
const bounds = ctx.bounds;
if (!bars || bars.length < 15) return;
const rsi = ctx.rsi(bars.map(b => b.close), 14);
for (let i = Math.max(0, Math.floor(bounds.startIndex) - 1); i <= Math.ceil(bounds.endIndex) + 1; i++) {
if (isNaN(rsi[i])) continue;
const x = ctx.barToX(i);
if (rsi[i] < 30) {
// Draw Green Transparent Circle
const y = ctx.priceToY(bars[i].low) + 10;
ctx.fillStyle = 'rgba(8, 153, 129, 0.35)';
ctx.beginPath();
ctx.arc(x, y, 6, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#089981';
ctx.lineWidth = 1.5;
ctx.stroke();
} else if (rsi[i] > 70) {
// Draw Red Transparent Circle
const y = ctx.priceToY(bars[i].high) - 10;
ctx.fillStyle = 'rgba(242, 54, 69, 0.35)';
ctx.beginPath();
ctx.arc(x, y, 6, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#f23645';
ctx.lineWidth = 1.5;
ctx.stroke();
}
}
// Send alert notifications dynamically
const lastIdx = bars.length - 1;
if (rsi[lastIdx] < 30) {
ctx.alert(true, `RSI Oversold Alert: ${rsi[lastIdx].toFixed(2)}`);
} else if (rsi[lastIdx] > 70) {
ctx.alert(true, `RSI Overbought Alert: ${rsi[lastIdx].toFixed(2)}`);
}
Technical Analysis (ta.*) Library
Writing your own loops to calculate indicators like RSI or MACD from scratch can be tedious. Instead, use the built-in ta.* library! This tutorial shows you how to use ctx.ta.supertrend and ctx.ta.crossover to build a complete trading signal system in just a few lines.
Key Concepts
ctx.ta.*methods accept data arrays and parameters, and return calculated arrays.- Some methods return objects containing multiple arrays (e.g.,
ta.supertrendreturns{ supertrend, direction }). ta.crossoverandta.crossunderare logic helpers that return boolean arrays (true/false).- View the full TA API Reference here.
// 1. Setup Data
const closes = ctx.bars.map(b => b.close);
// 2. Calculate Supertrend (Factor: 3, ATR Period: 10)
const { supertrend, direction } = ctx.ta.supertrend(ctx.bars, 3, 10);
// 3. Calculate an EMA for a baseline
const ema50 = ctx.ta.ema(closes, 50);
// 4. Logic: We want to trigger a BUY when price crosses over the Supertrend,
// BUT only if the Supertrend is above the 50 EMA.
const priceCrossedUp = ctx.ta.crossover(closes, supertrend);
// 5. Plotting and Shapes
ctx.plot(supertrend, { title: 'Supertrend', color: '#ffeb3b', width: 2 });
ctx.plot(ema50, { title: 'EMA 50', color: '#2196f3' });
for (let i = 1; i < ctx.bars.length; i++) {
if (priceCrossedUp[i] && supertrend[i] > ema50[i]) {
ctx.shape(i, {
style: 'arrow_up',
location: 'belowbar',
color: '#00E676',
size: 'normal',
text: 'BUY'
});
}
}
Support/Resistance Zones & HUD Table
This advanced indicator computes a support and resistance boundary by reading high and low averages, fills a translucent zone box across the viewport, and prints statistics directly on a HUD overlay dashboard using the ctx.table utilities.
const bars = ctx.bars;
const bounds = ctx.bounds;
if (!bars || bars.length < 50) return;
// Calculate average levels
let sumHigh = 0, sumLow = 0;
for (let i = bars.length - 20; i < bars.length; i++) {
sumHigh += bars[i].high;
sumLow += bars[i].low;
}
const resistanceVal = sumHigh / 20;
const supportVal = sumLow / 20;
const startX = ctx.barToX(Math.max(0, Math.floor(bounds.startIndex)));
const endX = ctx.barToX(bounds.endIndex);
const yRes = ctx.priceToY(resistanceVal);
const ySup = ctx.priceToY(supportVal);
// 1. Fill Translucent Resistance zone
ctx.fillStyle = 'rgba(239, 83, 80, 0.1)';
ctx.fillRect(startX, yRes - 10, endX - startX, 20);
ctx.strokeStyle = 'rgba(239, 83, 80, 0.4)';
ctx.lineWidth = 1;
ctx.strokeRect(startX, yRes - 10, endX - startX, 20);
// 2. Fill Translucent Support zone
ctx.fillStyle = 'rgba(8, 153, 129, 0.1)';
ctx.fillRect(startX, ySup - 10, endX - startX, 20);
ctx.strokeStyle = 'rgba(8, 153, 129, 0.4)';
ctx.strokeRect(startX, ySup - 10, endX - startX, 20);
// 3. Construct overlay table grid dashboard
const tbl = ctx.table.new(3, 2, ctx.position.top_right);
tbl.cell(0, 0, 'Levels');
tbl.cell(0, 1, 'Price');
tbl.cell(1, 0, 'Resistance');
tbl.cell(1, 1, resistanceVal.toFixed(2));
tbl.cell(2, 0, 'Support');
tbl.cell(2, 1, supportVal.toFixed(2));
tbl.set_bgcolor(0, 0, '#111111');
tbl.set_bgcolor(0, 1, '#111111');
Direct Pine Script Mode, Pine Logs & Bar Jump
In v1.0.6, you can paste Pine Script directly into the editor (with langModeBtn showing Auto · Pine or Mode · Pine) and let compileScriptSource transpile it automatically on run—no manual converter modal required. Set overlay=false to auto-allocate a dedicated sub-pane, use var persistent counters and out-of-order named arguments, and stream structured runtime diagnostics with log.info() / log.warning().
Logs flow from the bar loop (with synchronized ctx._currentIndex) into the cl:script-logs bridge (capped at MAX_SCRIPT_LOGS = 500). Filter with the Pine Logs console pill or search #bar, then click any log row to jump directly to that candle and return via the Back to Script Editor / Dismiss (Esc) restore banner. See Direct Pine Mode & Pine Logs for full details.
//@version=5
indicator("Direct Pine RSI + Gradient & Logs", overlay=false)
len = input.int(14, "RSI Length")
src = input.source(close, "Source")
var int crosses = 0
// Named arguments work in any order (quote- and comment-safe)
rsiVal = ta.rsi(src, len)
rsiEma = ta.ema(length=9, source=rsiVal)
// Assigned plot & hline handles drive gradient fills
pRsi = plot(rsiVal, "RSI", color=color.rgb(59, 130, 246), linewidth=2)
hMid = hline(50, "Midline", color=color.gray)
fill(pRsi, hMid, top_value=70, bottom_value=30, top_color=color.new(color.lime, 65), bottom_color=color.new(color.red, 65))
if ta.crossover(rsiVal, 50)
crosses += 1
log.info("Bullish midline cross #{0} at close={1}", crosses, math.round(close, 2))
else if ta.crossunder(rsiVal, 30)
log.warning("Oversold dip on bar {0}: RSI={1}", bar_index, math.round(rsiVal, 1))
Zero-Repaint Pyramiding Strategy, Custom KPIs & MFE/MAE
Enable //@strict-no-repaint at the top of a strategy to enforce compile-time diagnostics against barmerge.lookahead_on, negative series offsets, and forward bar_index indexing, paired with runtime make_series bounds guards. Configure realistic commissions, tick slippage, and pyramiding directly in strategy(...), draw dynamic retracements with fib.new(...) + .set_levels(...), and enrich the Strategy Tester with strategy.set_metric(), strategy.tag_trade(), and automatic per-trade MFE / MAE excursion badges.
Learn more in Zero-Repaint Linter & Source Maps and Strategy Costs, Pyramiding & MFE/MAE.
//@version=5
//@strict-no-repaint
strategy("Zero-Repaint Pyramid + MFE/MAE", overlay=true, pyramiding=2, commission_type=strategy.commission.percent, commission_value=0.05, slippage=2)
fast = ta.ema(close, 21)
slow = ta.ema(close, 55)
atrVal = ta.atr(14)
plot(fast, "EMA 21", color=color.aqua, linewidth=2)
plot(slow, "EMA 55", color=color.orange, linewidth=2)
longCond = ta.crossover(fast, slow) and session.ismarket
addCond = strategy.position_size > 0 and close > strategy.position_avg_price + atrVal
if longCond
strategy.entry("LongBase", strategy.long)
strategy.tag_trade("LongBase", "EMA-Cross", "Primary Trend")
else if addCond
strategy.entry("LongAdd", strategy.long)
strategy.tag_trade("LongAdd", "Pyramid-ATR")
if ta.crossunder(fast, slow)
strategy.close_all("Trend Reversal")
// Highlight recent swing retracement with fib.new
var fib recentFib = na
if barstate.islast and bar_index >= 20
pStart = chart.point.from_index(bar_index - 20, ta.lowest(low, 20))
pEnd = chart.point.from_index(bar_index, ta.highest(high, 20))
recentFib := fib.new(pStart, pEnd, levels=[0.0, 0.382, 0.5, 0.618, 1.0])
recentFib.set_levels([0.0, 0.382, 0.618, 1.0])
strategy.set_metric("Win Rate %", strategy.wintrades / math.max(1, strategy.closedtrades) * 100)
strategy.set_metric("Net Profit", strategy.netprofit)