Pine Script Examples

Ready-to-use Pine Script strategies configured for TradeStaq webhooks. Copy, customize, and deploy.

Basic RSI Strategy

A simple RSI-based mean reversion strategy:

//@version=5
strategy("RSI Mean Reversion", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// Inputs
rsiLength = input.int(14, "RSI Length", minval=1)
rsiOversold = input.int(30, "Oversold Level", minval=1, maxval=50)
rsiOverbought = input.int(70, "Overbought Level", minval=50, maxval=100)

// Calculate RSI
rsi = ta.rsi(close, rsiLength)

// Entry Conditions
longEntry = ta.crossover(rsi, rsiOversold)
shortEntry = ta.crossunder(rsi, rsiOverbought)

// Long Entry
if (longEntry)
    strategy.entry("Long", strategy.long,
        alert_message='{"action":"buy","symbol":"{{ticker}}","price":"{{close}}"}')

// Short Entry
if (shortEntry)
    strategy.entry("Short", strategy.short,
        alert_message='{"action":"sell","symbol":"{{ticker}}","price":"{{close}}"}')

// Plot RSI
hline(rsiOverbought, "Overbought", color=color.red)
hline(rsiOversold, "Oversold", color=color.green)
plot(rsi, "RSI", color=color.purple)

MACD Crossover Strategy

Trend-following strategy using MACD:

//@version=5
strategy("MACD Crossover", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// Inputs
fastLength = input.int(12, "Fast Length")
slowLength = input.int(26, "Slow Length")
signalLength = input.int(9, "Signal Length")

// Calculate MACD
[macdLine, signalLine, histLine] = ta.macd(close, fastLength, slowLength, signalLength)

// Entry Conditions
bullishCross = ta.crossover(macdLine, signalLine)
bearishCross = ta.crossunder(macdLine, signalLine)

// Long Entry
if (bullishCross)
    strategy.entry("Long", strategy.long,
        alert_message='{"action":"buy","symbol":"{{ticker}}","price":"{{close}}"}')

// Close Long on Bearish Cross
if (bearishCross and strategy.position_size > 0)
    strategy.close("Long",
        alert_message='{"action":"close","symbol":"{{ticker}}"}')

// Short Entry (optional - for futures)
if (bearishCross)
    strategy.entry("Short", strategy.short,
        alert_message='{"action":"sell","symbol":"{{ticker}}","price":"{{close}}"}')

// Close Short on Bullish Cross
if (bullishCross and strategy.position_size < 0)
    strategy.close("Short",
        alert_message='{"action":"close","symbol":"{{ticker}}"}')

EMA Crossover with Trend Filter

EMA crossover filtered by longer-term trend:

//@version=5
strategy("EMA Cross with Trend", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// Inputs
fastEMA = input.int(9, "Fast EMA")
slowEMA = input.int(21, "Slow EMA")
trendEMA = input.int(200, "Trend EMA")

// Calculate EMAs
emaFast = ta.ema(close, fastEMA)
emaSlow = ta.ema(close, slowEMA)
emaTrend = ta.ema(close, trendEMA)

// Trend Direction
uptrend = close > emaTrend
downtrend = close < emaTrend

// Entry Conditions
longSignal = ta.crossover(emaFast, emaSlow) and uptrend
shortSignal = ta.crossunder(emaFast, emaSlow) and downtrend

// Long Entry (only in uptrend)
if (longSignal)
    strategy.entry("Long", strategy.long,
        alert_message='{"action":"buy","symbol":"{{ticker}}","price":"{{close}}"}')

// Short Entry (only in downtrend)
if (shortSignal)
    strategy.entry("Short", strategy.short,
        alert_message='{"action":"sell","symbol":"{{ticker}}","price":"{{close}}"}')

// Exit on opposite signal
if (ta.crossunder(emaFast, emaSlow) and strategy.position_size > 0)
    strategy.close("Long",
        alert_message='{"action":"close","symbol":"{{ticker}}"}')

if (ta.crossover(emaFast, emaSlow) and strategy.position_size < 0)
    strategy.close("Short",
        alert_message='{"action":"close","symbol":"{{ticker}}"}')

// Plot EMAs
plot(emaFast, "Fast EMA", color=color.blue)
plot(emaSlow, "Slow EMA", color=color.orange)
plot(emaTrend, "Trend EMA", color=color.gray, linewidth=2)

Bollinger Bands Breakout

Volatility breakout strategy using Bollinger Bands:

//@version=5
strategy("BB Breakout", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// Inputs
bbLength = input.int(20, "BB Length")
bbMult = input.float(2.0, "BB Multiplier")

// Calculate Bollinger Bands
basis = ta.sma(close, bbLength)
dev = bbMult * ta.stdev(close, bbLength)
upper = basis + dev
lower = basis - dev

// Entry Conditions
breakoutUp = ta.crossover(close, upper)
breakoutDown = ta.crossunder(close, lower)
returnToBasis = ta.cross(close, basis)

// Long on upper breakout
if (breakoutUp)
    strategy.entry("Long", strategy.long,
        alert_message='{"action":"buy","symbol":"{{ticker}}","price":"{{close}}"}')

// Short on lower breakout
if (breakoutDown)
    strategy.entry("Short", strategy.short,
        alert_message='{"action":"sell","symbol":"{{ticker}}","price":"{{close}}"}')

// Exit at basis
if (returnToBasis)
    strategy.close_all(
        alert_message='{"action":"close","symbol":"{{ticker}}"}')

// Plot
plot(basis, "Basis", color=color.blue)
plot(upper, "Upper", color=color.red)
plot(lower, "Lower", color=color.green)

Multi-Indicator Strategy

Combining RSI, MACD, and EMA for confirmation:

//@version=5
strategy("Multi-Indicator", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// RSI
rsiLength = input.int(14, "RSI Length")
rsi = ta.rsi(close, rsiLength)

// MACD
[macdLine, signalLine, _] = ta.macd(close, 12, 26, 9)

// EMA
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)

// Conditions
rsiOversold = rsi < 30
rsiOverbought = rsi > 70
macdBullish = macdLine > signalLine
macdBearish = macdLine < signalLine
uptrendEMA = ema50 > ema200
downtrendEMA = ema50 < ema200

// Long: RSI oversold + MACD bullish + uptrend
longCondition = rsiOversold and macdBullish and uptrendEMA

// Short: RSI overbought + MACD bearish + downtrend
shortCondition = rsiOverbought and macdBearish and downtrendEMA

if (longCondition)
    strategy.entry("Long", strategy.long,
        alert_message='{"action":"buy","symbol":"{{ticker}}","price":"{{close}}"}')

if (shortCondition)
    strategy.entry("Short", strategy.short,
        alert_message='{"action":"sell","symbol":"{{ticker}}","price":"{{close}}"}')

// Exit conditions
exitLong = rsiOverbought or macdBearish
exitShort = rsiOversold or macdBullish

if (exitLong and strategy.position_size > 0)
    strategy.close("Long",
        alert_message='{"action":"close","symbol":"{{ticker}}"}')

if (exitShort and strategy.position_size < 0)
    strategy.close("Short",
        alert_message='{"action":"close","symbol":"{{ticker}}"}')

Strategy with Stop Loss & Take Profit

Including risk management in the alert:

//@version=5
strategy("RSI with SL/TP", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// Inputs
rsiLength = input.int(14, "RSI Length")
stopLossPct = input.float(2.0, "Stop Loss %")
takeProfitPct = input.float(4.0, "Take Profit %")

// Calculate RSI
rsi = ta.rsi(close, rsiLength)

// Calculate SL/TP prices
longSL = close * (1 - stopLossPct/100)
longTP = close * (1 + takeProfitPct/100)
shortSL = close * (1 + stopLossPct/100)
shortTP = close * (1 - takeProfitPct/100)

// Entry Conditions
longEntry = ta.crossover(rsi, 30)
shortEntry = ta.crossunder(rsi, 70)

// Long Entry with SL/TP
if (longEntry)
    strategy.entry("Long", strategy.long,
        alert_message='{"action":"buy","symbol":"{{ticker}}","price":"' + str.tostring(close) + '","stopLoss":"' + str.tostring(longSL) + '","takeProfit":"' + str.tostring(longTP) + '"}')

// Short Entry with SL/TP
if (shortEntry)
    strategy.entry("Short", strategy.short,
        alert_message='{"action":"sell","symbol":"{{ticker}}","price":"' + str.tostring(close) + '","stopLoss":"' + str.tostring(shortSL) + '","takeProfit":"' + str.tostring(shortTP) + '"}')

Indicator-Based Alerts (Non-Strategy)

For indicators without strategy logic, create manual alerts:

//@version=5
indicator("Alert Signals", overlay=true)

// Your indicator logic
rsi = ta.rsi(close, 14)
buySignal = ta.crossover(rsi, 30)
sellSignal = ta.crossunder(rsi, 70)

// Plot signals
plotshape(buySignal, "Buy", shape.triangleup, location.belowbar, color.green, size=size.small)
plotshape(sellSignal, "Sell", shape.triangledown, location.abovebar, color.red, size=size.small)

// Alert conditions
alertcondition(buySignal, "Buy Signal", '{"action":"buy","symbol":"{{ticker}}"}')
alertcondition(sellSignal, "Sell Signal", '{"action":"sell","symbol":"{{ticker}}"}')

Note: For indicator-based alerts, you need to create separate alerts for buy and sell conditions in TradingView's alert dialog.

Tips for Pine Script with TradeStaq

1. Always Use alert_message

strategy.entry("Long", strategy.long,
    alert_message='{"action":"buy"}')  // This ensures correct JSON

2. Stringify Dynamic Values

// Correct
'{"price":"' + str.tostring(close) + '"}'

// Wrong - will cause JSON errors
'{"price":' + str.tostring(close) + '}'

3. Test in Strategy Tester First

Before setting up live alerts:

  1. Add strategy to chart
  2. Review backtest results
  3. Verify signal frequency
  4. Then create alerts

4. Use Realistic Settings

strategy("My Strategy",
    overlay=true,
    initial_capital=10000,
    default_qty_type=strategy.percent_of_equity,
    default_qty_value=10,  // 10% per trade
    commission_type=strategy.commission.percent,
    commission_value=0.1)  // 0.1% fee