7 Best Pine Script Strategies for TradingView (With Code)
By HorizonAI Team
Looking for profitable Pine Script strategies to use on TradingView? This guide covers the most effective strategy types, from classic indicator-based systems to modern smart money concepts.
Each strategy includes code examples, best practices, and tips for customization.
What Makes a Good Pine Script Strategy?
Before diving into specific strategies, understand what separates good strategies from bad ones:
Characteristics of robust strategies:
- Clear entry and exit rules (no ambiguity)
- Defined risk management (stop loss, position sizing)
- Works across multiple symbols and timeframes
- Positive expectancy over large sample sizes
- Not over-optimized to past data
Pro tip: The "best" strategy is one that matches your trading style, risk tolerance, and available time. A complex strategy you can't follow consistently will underperform a simple one you execute perfectly.
1. EMA Crossover Strategy
The EMA crossover is a classic trend-following strategy that's simple yet effective.
How it works:
- Buy when fast EMA crosses above slow EMA
- Sell when fast EMA crosses below slow EMA
- Optional: Add a trend filter (only trade in direction of longer-term trend)
Best for: Trending markets, swing trading, beginners
//@version=6
strategy("EMA Crossover Strategy", overlay=true)
// Inputs
fastLength = input.int(9, "Fast EMA")
slowLength = input.int(21, "Slow EMA")
riskReward = input.float(2.0, "Risk:Reward Ratio")
atrMultiplier = input.float(1.5, "ATR Stop Multiplier")
// Indicators
fastEMA = ta.ema(close, fastLength)
slowEMA = ta.ema(close, slowLength)
atr = ta.atr(14)
// Signals
longCondition = ta.crossover(fastEMA, slowEMA)
shortCondition = ta.crossunder(fastEMA, slowEMA)
// Execute trades with ATR-based stops
if longCondition
stopLoss = close - (atr * atrMultiplier)
takeProfit = close + (atr * atrMultiplier * riskReward)
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", stop=stopLoss, limit=takeProfit)
if shortCondition
stopLoss = close + (atr * atrMultiplier)
takeProfit = close - (atr * atrMultiplier * riskReward)
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", stop=stopLoss, limit=takeProfit)
// Plot EMAs
plot(fastEMA, "Fast EMA", color=color.blue)
plot(slowEMA, "Slow EMA", color=color.red)
Optimization tips:
- Test different EMA lengths (8/21, 9/21, 12/26)
- Add volume confirmation
- Only trade when ADX > 25 (strong trend)
2. RSI Mean Reversion Strategy
Mean reversion strategies profit from price returning to average levels after extreme moves.
How it works:
- Buy when RSI drops below oversold level (30) then crosses back above
- Sell when RSI rises above overbought level (70) then crosses back below
- Best in ranging markets
Best for: Sideways markets, range trading, forex pairs
//@version=6
strategy("RSI Mean Reversion", overlay=true)
// Inputs
rsiLength = input.int(14, "RSI Length")
oversold = input.int(30, "Oversold Level")
overbought = input.int(70, "Overbought Level")
atrLength = input.int(14, "ATR Length")
stopMultiplier = input.float(2.0, "Stop Loss ATR Multiplier")
tpMultiplier = input.float(3.0, "Take Profit ATR Multiplier")
// Indicators
rsi = ta.rsi(close, rsiLength)
atr = ta.atr(atrLength)
// Signals - entering as RSI leaves extreme zones
longSignal = ta.crossover(rsi, oversold)
shortSignal = ta.crossunder(rsi, overbought)
// Trend filter (optional) - 200 EMA
ema200 = ta.ema(close, 200)
bullishBias = close > ema200
bearishBias = close < ema200
// Execute trades
if longSignal and bullishBias
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long",
stop=close - atr * stopMultiplier,
limit=close + atr * tpMultiplier)
if shortSignal and bearishBias
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short",
stop=close + atr * stopMultiplier,
limit=close - atr * tpMultiplier)
Warning: Mean reversion fails in trending markets. Consider adding a trend filter—only take long signals when price is above 200 EMA, shorts when below.
3. Bollinger Bands Squeeze Breakout
This strategy captures explosive moves after periods of low volatility.
How it works:
- Identify when Bollinger Bands contract (squeeze)
- Enter when price breaks out of the bands after a squeeze
- Ride the momentum with a trailing stop
Best for: Breakout trading, volatility expansion, all markets
//@version=6
strategy("BB Squeeze Breakout", overlay=true)
// Inputs
bbLength = input.int(20, "BB Length")
bbMult = input.float(2.0, "BB Multiplier")
kcLength = input.int(20, "KC Length")
kcMult = input.float(1.5, "KC Multiplier")
// Bollinger Bands
basis = ta.sma(close, bbLength)
dev = bbMult * ta.stdev(close, bbLength)
upperBB = basis + dev
lowerBB = basis - dev
// Keltner Channel (for squeeze detection)
kcBasis = ta.ema(close, kcLength)
kcRange = ta.atr(kcLength)
upperKC = kcBasis + kcRange * kcMult
lowerKC = kcBasis - kcRange * kcMult
// Squeeze detection
sqzOn = lowerBB > lowerKC and upperBB < upperKC
sqzOff = sqzOn == false
// Momentum
momentum = ta.linreg(close - ta.sma(close, bbLength), bbLength, 0)
// Signals
longCondition = sqzOff and sqzOn[1] and momentum > 0
shortCondition = sqzOff and sqzOn[1] and momentum < 0
// Execute with trailing stop
if longCondition
strategy.entry("Long", strategy.long)
if shortCondition
strategy.entry("Short", strategy.short)
// Trailing stop exit
atr = ta.atr(14)
strategy.exit("Trail Long", "Long", trail_points=atr*2/syminfo.mintick, trail_offset=atr/syminfo.mintick)
strategy.exit("Trail Short", "Short", trail_points=atr*2/syminfo.mintick, trail_offset=atr/syminfo.mintick)
// Plots
plot(upperBB, "Upper BB", color=color.blue)
plot(lowerBB, "Lower BB", color=color.blue)
bgcolor(sqzOn ? color.new(color.orange, 80) : na)
4. MACD + RSI Confluence Strategy
Combining indicators reduces false signals and increases win rate.
How it works:
- Wait for MACD crossover (trend direction)
- Confirm with RSI not in extreme territory
- Enter with defined risk management
Best for: Swing trading, higher timeframes (4H, Daily)
//@version=6
strategy("MACD + RSI Confluence", overlay=true)
// MACD
[macdLine, signalLine, hist] = ta.macd(close, 12, 26, 9)
// RSI
rsi = ta.rsi(close, 14)
// ATR for stops
atr = ta.atr(14)
// Long: MACD bullish cross + RSI not overbought
longCondition = ta.crossover(macdLine, signalLine) and rsi < 70 and rsi > 40
// Short: MACD bearish cross + RSI not oversold
shortCondition = ta.crossunder(macdLine, signalLine) and rsi > 30 and rsi < 60
if longCondition
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", stop=close - atr * 2, limit=close + atr * 4)
if shortCondition
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", stop=close + atr * 2, limit=close - atr * 4)
5. Support/Resistance Breakout Strategy
Trade breakouts of key price levels with momentum confirmation.
How it works:
- Identify recent swing highs/lows as S/R levels
- Enter when price breaks and closes beyond the level
- Confirm with volume spike
Best for: Day trading, momentum trading, stocks
//@version=6
strategy("S/R Breakout Strategy", overlay=true)
// Inputs
lookback = input.int(20, "Lookback Period")
volMultiplier = input.float(1.5, "Volume Spike Multiplier")
// Calculate swing high/low
swingHigh = ta.highest(high, lookback)[1]
swingLow = ta.lowest(low, lookback)[1]
// Volume confirmation
avgVolume = ta.sma(volume, 20)
volumeSpike = volume > avgVolume * volMultiplier
// Breakout conditions
longBreakout = close > swingHigh and volumeSpike
shortBreakout = close < swingLow and volumeSpike
// ATR for dynamic stops
atr = ta.atr(14)
if longBreakout
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", stop=swingHigh - atr, limit=close + atr * 3)
if shortBreakout
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", stop=swingLow + atr, limit=close - atr * 3)
// Plot levels
plot(swingHigh, "Resistance", color=color.red, style=plot.style_circles)
plot(swingLow, "Support", color=color.green, style=plot.style_circles)
6. Smart Money Concepts (SMC) Strategy
Modern institutional trading concepts adapted for retail traders.
How it works:
- Identify order blocks (institutional buying/selling zones)
- Wait for price to return to these zones
- Enter with tight stops below/above the order block
Best for: Forex, indices, understanding market structure
//@version=6
strategy("SMC Order Block Strategy", overlay=true)
// Identify bearish order block (last up candle before down move)
bearishOB = high[1] > high[2] and low[1] > low[2] and close < open and close < low[1]
// Identify bullish order block (last down candle before up move)
bullishOB = low[1] < low[2] and high[1] < high[2] and close > open and close > high[1]
// Track OB levels
var float activeBullishOBHigh = na
var float activeBullishOBLow = na
var float activeBearishOBHigh = na
var float activeBearishOBLow = na
if bullishOB
activeBullishOBHigh := high[1]
activeBullishOBLow := low[1]
if bearishOB
activeBearishOBHigh := high[1]
activeBearishOBLow := low[1]
// Entry on return to OB
atr = ta.atr(14)
longCondition = not na(activeBullishOBLow) and low <= activeBullishOBHigh and close > activeBullishOBLow
shortCondition = not na(activeBearishOBHigh) and high >= activeBearishOBLow and close < activeBearishOBHigh
if longCondition
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", stop=activeBullishOBLow - atr * 0.5, limit=close + atr * 3)
activeBullishOBHigh := na
activeBullishOBLow := na
if shortCondition
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", stop=activeBearishOBHigh + atr * 0.5, limit=close - atr * 3)
activeBearishOBHigh := na
activeBearishOBLow := na
Pro tip: SMC concepts work best when combined with higher timeframe analysis. Identify the trend on Daily, then trade order blocks on 1H or 4H.
7. Multi-Timeframe Trend Strategy
Align multiple timeframes to trade with the dominant trend.
How it works:
- Check trend on higher timeframe (e.g., Daily)
- Enter trades on lower timeframe in trend direction
- Avoid counter-trend trades
Best for: Swing trading, reducing false signals, all markets
//@version=6
strategy("Multi-Timeframe Trend", overlay=true)
// Higher timeframe trend (Daily)
htfEMA = request.security(syminfo.tickerid, "D", ta.ema(close, 50))
htfTrendUp = close > htfEMA
htfTrendDown = close < htfEMA
// Current timeframe signals
fastEMA = ta.ema(close, 9)
slowEMA = ta.ema(close, 21)
atr = ta.atr(14)
// Only long when HTF trend is up
longCondition = ta.crossover(fastEMA, slowEMA) and htfTrendUp
// Only short when HTF trend is down
shortCondition = ta.crossunder(fastEMA, slowEMA) and htfTrendDown
if longCondition
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", stop=close - atr * 2, limit=close + atr * 4)
if shortCondition
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", stop=close + atr * 2, limit=close - atr * 4)
// Visual
bgcolor(htfTrendUp ? color.new(color.green, 90) : htfTrendDown ? color.new(color.red, 90) : na)
plot(htfEMA, "Daily EMA", color=color.orange, linewidth=2)
Strategy Comparison
- EMA Crossover: Best for trending markets, low complexity, 40-50% win rate, 1.5-2:1 R:R
- RSI Mean Reversion: Best for ranging markets, low complexity, 50-60% win rate, 1-1.5:1 R:R
- BB Squeeze: Best for volatile markets, medium complexity, 45-55% win rate, 2-3:1 R:R
- MACD + RSI: Best for trending markets, medium complexity, 50-55% win rate, 2:1 R:R
- S/R Breakout: Best for breakout markets, medium complexity, 40-45% win rate, 2-3:1 R:R
- SMC Order Blocks: Works in all markets, high complexity, 45-55% win rate, 2-4:1 R:R
- Multi-Timeframe: Best for trending markets, medium complexity, 50-60% win rate, 2:1 R:R
Building Custom Strategies with HorizonAI
Instead of copying code, describe your strategy idea to HorizonAI:
Example prompts:
- "Create an EMA crossover strategy that only trades during London session with 2:1 risk reward"
- "Build a mean reversion strategy using RSI and Bollinger Bands with ATR-based stops"
- "Make an SMC strategy that identifies fair value gaps and enters on retracement"
Iteration prompts:
- "Add a 200 EMA trend filter—only take longs above it"
- "Change the stop loss to trail after 1R profit"
- "Add alerts for entry signals"
FAQs
Which strategy is best for beginners?
Start with EMA Crossover or RSI Mean Reversion. They're simple to understand, have clear rules, and teach fundamental concepts. Graduate to more complex strategies once you're consistently profitable.
Can I use these strategies for live trading?
These are starting points. Always backtest on your specific symbols and timeframes, paper trade first, and adjust parameters for your risk tolerance before risking real money.
Do these strategies work on crypto?
Yes, all strategies work on crypto, but crypto's high volatility may require wider stops and smaller position sizes. The SMC and breakout strategies often work well in crypto markets.
How do I know which strategy to use?
Match strategy to market conditions:
- Trending market: EMA Crossover, Multi-Timeframe, MACD+RSI
- Ranging market: RSI Mean Reversion, S/R levels
- Low volatility about to expand: BB Squeeze
- All conditions: SMC (requires more skill)
Summary
The best Pine Script strategies share common traits:
- Clear rules: No ambiguity in entry, exit, or risk management
- Risk management: Every strategy includes stop losses
- Market fit: Match strategy type to market conditions
- Simplicity: More indicators ≠ better results
Start with a simple strategy, backtest it thoroughly, and only add complexity when you have a specific reason.
Have questions about Pine Script strategies? Join our Discord to discuss with other traders!
