Strategy · Pine Script v6 · On the chart

Strategy Examples

by danielbodnar

Strategy Examples is a Pine Script strategy template demonstrating multiple classic technical trading approaches directly on the price chart.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code228
Settings19inputs
LicenceMIT
Last update2 months ago8 Aug 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

228 lines of Pine Script v6 from snippets/pinescript/strategy-examples.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

strategy-examples.pine
// Pine Script Strategy Examples
// @version=6

// ===== BASIC STRATEGY TEMPLATE =====
strategy("Strategy Examples", 
         overlay = true,
         initial_capital = 10000,
         default_qty_type = strategy.percent_of_equity,
         default_qty_value = 10,
         commission_type = strategy.commission.percent,
         commission_value = 0.075,
         slippage = 2)

// ===== MOVING AVERAGE CROSSOVER STRATEGY =====
// Input parameters
fast_length = input.int(10, "Fast MA Length", minval=1)
slow_length = input.int(20, "Slow MA Length", minval=1)
use_ema = input.bool(true, "Use EMA (vs SMA)")

// Calculate moving averages
fast_ma = use_ema ? ta.ema(close, fast_length) : ta.sma(close, fast_length)
slow_ma = use_ema ? ta.ema(close, slow_length) : ta.sma(close, slow_length)

// Entry conditions
long_condition = ta.crossover(fast_ma, slow_ma)
short_condition = ta.crossunder(fast_ma, slow_ma)

// Execute trades
if long_condition
    strategy.entry("Long", strategy.long, comment="MA Cross Up")

if short_condition
    strategy.entry("Short", strategy.short, comment="MA Cross Down")

// Plot moving averages
plot(fast_ma, "Fast MA", color.blue, 2)
plot(slow_ma, "Slow MA", color.red, 2)

// ===== RSI MEAN REVERSION STRATEGY =====
// RSI parameters
rsi_length = input.int(14, "RSI Length", minval=1)
rsi_overbought = input.float(70, "RSI Overbought", minval=50, maxval=100)
rsi_oversold = input.float(30, "RSI Oversold", minval=0, maxval=50)

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

// Entry conditions
rsi_long = rsi < rsi_oversold and rsi > rsi[1]  // RSI bouncing from oversold
rsi_short = rsi > rsi_overbought and rsi < rsi[1]  // RSI falling from overbought

// Execute RSI trades
if rsi_long and strategy.position_size == 0
    strategy.entry("RSI Long", strategy.long, comment="RSI Oversold")

if rsi_short and strategy.position_size == 0
    strategy.entry("RSI Short", strategy.short, comment="RSI Overbought")

// ===== STOP LOSS AND TAKE PROFIT MANAGEMENT =====
// Risk management parameters
stop_loss_pct = input.float(2.0, "Stop Loss %", minval=0.1, maxval=10.0) / 100
take_profit_pct = input.float(4.0, "Take Profit %", minval=0.1, maxval=20.0) / 100

// Calculate stop and profit levels
long_stop = strategy.position_avg_price * (1 - stop_loss_pct)
long_profit = strategy.position_avg_price * (1 + take_profit_pct)
short_stop = strategy.position_avg_price * (1 + stop_loss_pct)
short_profit = strategy.position_avg_price * (1 - take_profit_pct)

// Apply stop loss and take profit
if strategy.position_size > 0
    strategy.exit("Long Exit", "Long", stop=long_stop, limit=long_profit)
    strategy.exit("RSI Long Exit", "RSI Long", stop=long_stop, limit=long_profit)

if strategy.position_size < 0
    strategy.exit("Short Exit", "Short", stop=short_stop, limit=short_profit)
    strategy.exit("RSI Short Exit", "RSI Short", stop=short_stop, limit=short_profit)

// ===== BOLLINGER BANDS BREAKOUT STRATEGY =====
// Bollinger Bands parameters
bb_length = input.int(20, "BB Length", minval=1)
bb_mult = input.float(2.0, "BB Multiplier", minval=0.1, step=0.1)

// Calculate Bollinger Bands
[bb_middle, bb_upper, bb_lower] = ta.bb(close, bb_length, bb_mult)

// Breakout conditions
bb_long = ta.crossover(close, bb_upper)
bb_short = ta.crossunder(close, bb_lower)

// Execute BB breakout trades
if bb_long
    strategy.entry("BB Long", strategy.long, comment="BB Upper Break")

if bb_short
    strategy.entry("BB Short", strategy.short, comment="BB Lower Break")

// Plot Bollinger Bands
p1 = plot(bb_upper, "BB Upper", color.red)
p2 = plot(bb_lower, "BB Lower", color.red)
p3 = plot(bb_middle, "BB Middle", color.gray)
fill(p1, p2, color=color.new(color.red, 90))

// ===== ADVANCED ORDER MANAGEMENT =====
// Trailing Stop Loss
use_trailing = input.bool(false, "Use Trailing Stop")
trail_pct = input.float(1.5, "Trailing Stop %", minval=0.1) / 100

if use_trailing and strategy.position_size != 0
    if strategy.position_size > 0
        strategy.exit("Trailing Long", "Long", trail_percent=trail_pct * 100)
    else
        strategy.exit("Trailing Short", "Short", trail_percent=trail_pct * 100)

// Partial Position Closing
use_partial = input.bool(false, "Use Partial Exits")
partial_pct = input.float(50, "Partial Exit %", minval=10, maxval=90)

if use_partial and strategy.position_size != 0
    profit_target = strategy.position_avg_price * (1 + take_profit_pct / 2)
    
    if strategy.position_size > 0 and close >= profit_target
        strategy.close("Long", qty_percent=partial_pct, comment="Partial Long Exit")
    
    if strategy.position_size < 0 and close <= profit_target
        strategy.close("Short", qty_percent=partial_pct, comment="Partial Short Exit")

// ===== POSITION SIZING BASED ON VOLATILITY =====
// ATR-based position sizing
atr_length = input.int(14, "ATR Length for Position Size")
risk_per_trade = input.float(1.0, "Risk Per Trade %", minval=0.1, maxval=5.0) / 100

current_atr = ta.atr(atr_length)
account_risk = strategy.equity * risk_per_trade
position_size = math.floor(account_risk / (current_atr * 2))  // Risk 2 ATR per trade

// Use calculated position size for new entries
if long_condition and strategy.position_size == 0
    strategy.entry("Sized Long", strategy.long, qty=position_size, comment="ATR Sized Long")

// ===== TIME-BASED FILTERS =====
// Date range filter
start_date = input.time(timestamp("01 Jan 2020 00:00"), "Start Date")
end_date = input.time(timestamp("31 Dec 2024 23:59"), "End Date")
date_filter = time >= start_date and time <= end_date

// Time session filter
session_time = input.session("0930-1600", "Trading Session")
time_filter = not na(time(timeframe.period, session_time))

// Apply filters to entries
filtered_long = long_condition and date_filter and time_filter
filtered_short = short_condition and date_filter and time_filter

if filtered_long
    strategy.entry("Filtered Long", strategy.long, comment="Time Filtered Long")

if filtered_short
    strategy.entry("Filtered Short", strategy.short, comment="Time Filtered Short")

// ===== STRATEGY PERFORMANCE TRACKING =====
// Custom performance metrics
var float total_trades = 0
var float winning_trades = 0
var float total_pnl = 0

// Track trade exits
if strategy.closedtrades > strategy.closedtrades[1]
    total_trades += 1
    last_trade_pnl = strategy.closedtrades.profit(strategy.closedtrades - 1)
    total_pnl += last_trade_pnl
    
    if last_trade_pnl > 0
        winning_trades += 1

// Calculate win rate
win_rate = total_trades > 0 ? (winning_trades / total_trades) * 100 : 0

// Display performance metrics
var table perf_table = table.new(position.bottom_right, 2, 6, bgcolor=color.white, border_width=1)

if barstate.islast
    table.cell(perf_table, 0, 0, "Total Trades", text_color=color.black)
    table.cell(perf_table, 1, 0, str.tostring(total_trades, "#"), text_color=color.black)
    
    table.cell(perf_table, 0, 1, "Win Rate", text_color=color.black)
    table.cell(perf_table, 1, 1, str.tostring(win_rate, "#.#") + "%", text_color=color.black)
    
    table.cell(perf_table, 0, 2, "Total PnL", text_color=color.black)
    table.cell(perf_table, 1, 2, str.tostring(total_pnl, "#.##"), 
               text_color=total_pnl > 0 ? color.green : color.red)
    
    table.cell(perf_table, 0, 3, "Equity", text_color=color.black)
    table.cell(perf_table, 1, 3, str.tostring(strategy.equity, "#.##"), text_color=color.black)
    
    table.cell(perf_table, 0, 4, "Position Size", text_color=color.black)
    table.cell(perf_table, 1, 4, str.tostring(strategy.position_size, "#.##"), text_color=color.black)
    
    table.cell(perf_table, 0, 5, "Drawdown", text_color=color.black)
    table.cell(perf_table, 1, 5, str.tostring(strategy.max_drawdown, "#.##"), text_color=color.red)

// ===== ALERT INTEGRATION =====
// Strategy alert with placeholders
alert_message = "{{strategy.order.action}} {{strategy.position_size}} {{ticker}} @ {{strategy.order.price}}"

// Configure alerts for strategy orders
if long_condition
    strategy.entry("Alert Long", strategy.long, alert_message=alert_message + " - Long Entry")

if short_condition  
    strategy.entry("Alert Short", strategy.short, alert_message=alert_message + " - Short Entry")

// ===== VISUAL INDICATORS =====
// Plot entry and exit points
plotshape(long_condition, "Long Entry", shape.triangleup, location.belowbar, color.green, size=size.small)
plotshape(short_condition, "Short Entry", shape.triangledown, location.abovebar, color.red, size=size.small)

// Background coloring for position
position_color = strategy.position_size > 0 ? color.new(color.green, 95) : 
                 strategy.position_size < 0 ? color.new(color.red, 95) : na
bgcolor(position_color)

// Plot stop loss and take profit levels
plot(strategy.position_size > 0 ? long_stop : strategy.position_size < 0 ? short_stop : na, 
     "Stop Loss", color.red, style=plot.style_linebr, linewidth=2)
     
plot(strategy.position_size > 0 ? long_profit : strategy.position_size < 0 ? short_profit : na, 
     "Take Profit", color.green, style=plot.style_linebr, linewidth=2)

Overview

Strategy Examples incorporates a moving average crossover system using SMA or EMA, an RSI mean reversion model operating on overbought and oversold threshold bounces, and a Bollinger Bands breakout trigger. Trades are managed with percentage-based stop loss and take profit orders. Configurable inputs allow customization of calculation lengths, indicator thresholds, and position exit targets.

Details

Published by

danielbodnar on GitHub

Type

Strategy, Pine Script v6

Draws

On the price chart

Category

Moving averages, Oscillators & momentum, Breakout, Mean reversion

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Fast MA Lengthint10fast_length
Slow MA Lengthint20slow_length
Use EMA (vs SMA)booltrueuse_ema
RSI Lengthint14rsi_length
RSI Overboughtfloat70rsi_overbought
RSI Oversoldfloat30rsi_oversold
Stop Loss %float2.0stop_loss_pct
Take Profit %float4.0take_profit_pct
BB Lengthint20bb_length
BB Multiplierfloat2.0bb_mult
Use Trailing Stopboolfalseuse_trailing
Trailing Stop %float1.5trail_pct
Show all 19 settings
SettingTypeDefaultVariable
Use Partial Exitsboolfalseuse_partial
Partial Exit %float50partial_pct
ATR Length for Position Sizeint14atr_length
Risk Per Trade %float1.0risk_per_trade
Start Datetimetimestamp("01 Jan 2020 00:00")start_date
End Datetimetimestamp("31 Dec 2024 23:59")end_date
Trading Sessionsession0930-1600session_time
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

This mean-reversion strategy combines multi-timeframe exponential moving averages, Bollinger Bands, and the Relative Strength Index. It generates long and optional short trade signals when price interacts with the Bollinger Bands alongside RSI threshold confir

Strategy v5 Mean reversionMoving averages
Updated 2 months ago · None stated GitHub repository of MEMA + BB + RSI [Alorse]

This strategy draws on the price chart and combines Stochastic RSI, the Money Flow Index, and an exponential moving average to open long or short trades. Longs use the lower oscillator thresholds and shorts use the upper ones, with direction limited to longs,

Strategy v5 Oscillators & momentumMoving averages Repaints
Updated 2 years ago · GPL-3.0 GitHub repository of 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders

Bollinger bands examples

by tradingstrategy-ai
53 stars

This strategy plots exponential-moving-average Bollinger bands on the price chart and calculates RSI. It opens a long position when close crosses above the upper band while RSI is at or above a threshold, the date filter allows trading, and no position is open

Strategy v5 Volatility & bandsOscillators & momentum
Updated 3 years ago · None stated GitHub repository of Bollinger bands examples
53 stars

This strategy implements Larry Connors' 2-period RSI mean-reversion algorithm overlaid on the price chart. It filters trades using a long-term Simple Moving Average (SMA), entering long positions when the price trades above the SMA and the short-term RSI drops

Strategy v6 Oscillators & momentumMean reversion
Updated 2 months ago · MPL-2.0 GitHub repository of Larry Connors 2-Period RSI Strategy

ADA4H Optuna Strategy

by skywalker0803r
42 stars

This strategy trades longs and shorts on the price chart. Long entries require a close above the prior Donchian high, a close above a long-term SMA, and RSI above a threshold, with size set as a percentage of equity. Long exits use a stop at the prior Donchian

Strategy v5 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of ADA4H Optuna Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers