Strategy · Pine Script v5 · On the chart

Boilerplate Configurable Strategy [Yosiet]

by pegaltier· code credited to yosietserga

This overlay strategy offers two selectable entry modes: a Bollinger squeeze on typical price and a simple moving-average cross.

View on GitHub

GitHub stars307on the repository
Pine versionv5runs as is
Lines of code202
Settings30inputs
LicenceNone statedfile: MPL-2.0
Last updatetoday28 Oct 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

202 lines of Pine Script v5 from utils-pine/template1.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

template1.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © yosietserga
// https://www.tradingview.com/pine/?id=PUB%3B9e64d80926ef45fb87703ce1290ea520
//@version=5
strategy("Boilerplate Configurable Strategy [Yosiet]", overlay=true, margin_long=100, margin_short=100)

//Strategy Specific inputs 
strategyType = input.string("SQUEEZE", "Strategy Type", options=["SQUEEZE", "SMA_CROSS"])

// === MODULAR ENTRY/EXIT SYSTEM ===

//You can colapse all code blocks that begins with comments brackets
//You can DM for any question or comment in the post

// Entry/Exit conditions {
length = input.int(20, "Length", group="General Strategy Settings")
// Bollinger Bands Settings
mult1 = input.float(1.5, "Wide BB Multiplier", step=0.1, group="Squeeze Settings")
mult2 = input.float(2.0, "Narrow BB Multiplier", step=0.1, group="Squeeze Settings")

// SMA Cross Settings
maFast = ta.sma(close, length)
maSlow = ta.sma(open, length)


// Bollinger Bands
[basis1, upper1, lower1] = ta.bb(hlc3, length, mult1)
[basis2, upper2, lower2] = ta.bb(hlc3, length, mult2)
// Squeeze Condition
squeeze = hlc3 < upper2 and hlc3 > lower2

// }

//{ inputs block 

// ********** INPUTS ********** //
// -- Trading Days Configuration --
var groupDays = "Trading Days"
enableMon = input.bool(true, "Monday", group=groupDays)
enableTue = input.bool(true, "Tuesday", group=groupDays)
enableWed = input.bool(true, "Wednesday", group=groupDays)
enableThu = input.bool(true, "Thursday", group=groupDays)
enableFri = input.bool(true, "Friday", group=groupDays)
enableSat = input.bool(true, "Saturday", group=groupDays)
enableSun = input.bool(true, "Sunday", group=groupDays)

// Session Configuration
sessionInput = input.string("0000-0000", "Trading Session (HHmm-HHmm)", tooltip="24h format", group="Hour Settings")
var sessionTime = request.security(syminfo.tickerid, "D", time(timeframe.period, sessionInput))

// Hours Exclusions
exitTime = input.session("1600-1700", "Daily Exit Time", options=["1500-1600", "1600-1700", "1700-1800", "1800-1900"], group="Hour Settings")

// Date Range Filter
startDate = input.time(timestamp("1 Jan 2024"), "Start Date", group="Data Date Range")
endDate = input.time(timestamp("31 Jan 2025"), "End Date", group="Data Date Range")



// -- News Avoidance Configuration --
var groupNews = "News Filter"
enableNewsFilter = input.bool(false, "Enable News Filter", group=groupNews)
newsTime = input.time(timestamp("2023-01-01 14:30"), "News Time (UTC)", group=groupNews)
newsWindow = input.int(5, "News Window (minutes)", minval=1, group=groupNews)

// Trade Direction Configuration
var groupTradeConfiguration = "Trade Side Configuration"
tradeDirection = input.string("Both", "Trade Direction", options=["Long", "Short", "Both"], group=groupTradeConfiguration)
tradeInverse = input.bool(false, "Inverse Trade Side", group=groupTradeConfiguration)

// Capital Risk Management Parameters
var groupRisk = "Money Risk Management"
maxLossPerc = input.float(2.0, "Max Loss per Trade (%)", group=groupRisk) / 100
maxLosingDays = input.int(3, "Max Consecutive Losing Days", group=groupRisk)
maxDD = input.float(10.0, "Max Drawdown (%)", group=groupRisk) / 100

// Risk/Reward Configuration
var groupRRR = "Risk/Reward Ratio"
rrMode = input.string("ATR", "RR Mode", options=["ATR", "Static"], group=groupRRR)
atrLength  = input.int(14, "ATR Length", group=groupRRR)
atrMultiplier = input.float(1.5, "ATR Multiplier", step=0.1, group=groupRRR)
staticRR = input.float(2.0, "Static RR Ratio", step=0.1, group=groupRRR)
useTrail   = input.bool(false, "Enable Trailing Stop")
trailStart = input.float(15, "Trail Activation (%)") / 100
trailDist  = input.float(0.5, "Trail Distance (%)") / 100

// 7. Strategy Logic
var int consecutiveLosses = 0
var float peakEquity = strategy.equity
var bool drawdownBreached = false
// }

// { Calculate drawdown
currentEquity = strategy.equity
drawdown = (peakEquity - currentEquity) / peakEquity
if currentEquity > peakEquity
    peakEquity := currentEquity
    drawdownBreached := false

if drawdown >= maxDD and not drawdownBreached
    drawdownBreached := true
    strategy.close_all("Max DD Reached")
// }

// { Trading session  and date filter
inSession = time(timeframe.period, sessionInput)

inDateRange = time >= startDate and time <= endDate

// ********** FUNCTIONS ********** //
// -- Trading Day Filter --
isTradingDay() =>
    day = dayofweek
    (enableMon and day == dayofweek.monday) or
     (enableTue and day == dayofweek.tuesday) or
     (enableWed and day == dayofweek.wednesday) or
     (enableThu and day == dayofweek.thursday) or
     (enableFri and day == dayofweek.friday) or 
     (enableSat and day == dayofweek.saturday) or 
     (enableSun and day == dayofweek.sunday)

// -- News Avoidance Filter --
isNewsTime() =>
    if not enableNewsFilter or na(newsTime)
        false
    else
        windowStart = newsTime - newsWindow * 60 * 1000
        windowEnd = newsTime + newsWindow * 60 * 1000
        time >= windowStart and time <= windowEnd

// Exit time filter
exitPeriod = not na(time(timeframe.period, exitTime))
// }

// { Risk Reward Calculations 
// Calculate position size
positionSize = strategy.equity * maxLossPerc / (ta.atr(14) / close)

// RR calculations
atr = ta.atr(atrLength)
stopLoss = rrMode == "ATR" ? atr * atrMultiplier : close * maxLossPerc
takeProfit = rrMode == "ATR" ? stopLoss * staticRR : stopLoss * staticRR
// }

// { Entries and Exits execution 

var bool longCondition = false
var bool shortCondition = false

if strategyType == "SMA_CROSS"
    longCondition  := ta.crossover(maFast, maSlow)
    shortCondition := ta.crossunder(maFast, maSlow)
    
if strategyType == "SQUEEZE"
    longCondition  := ta.crossover(hlc3, upper1) and squeeze
    shortCondition := ta.crossunder(hlc3, lower1) and squeeze

// Strategy logic
if inSession and inDateRange and not exitPeriod and not drawdownBreached and isTradingDay() and not isNewsTime()
    // Long entries
    if (tradeDirection == "Long" or tradeDirection == "Both") and ((longCondition and not tradeInverse) or (tradeInverse and shortCondition))
        strategy.entry("Long", strategy.long, qty=positionSize/close)
        strategy.exit("Exit Long", "Long", 
         stop=close - stopLoss, 
         limit=close + takeProfit,
         trail_points = useTrail ? close * trailStart : na,
         trail_offset = useTrail ? close * trailDist : na)
    
    // Short entries
    if (tradeDirection == "Short" or tradeDirection == "Both") and ((longCondition and tradeInverse) or (not tradeInverse and shortCondition))
        strategy.entry("Short", strategy.short, qty=positionSize/close)
        strategy.exit("Exit Short", "Short", 
         stop=close + stopLoss, 
         limit=close - takeProfit,
         trail_points = useTrail ? close * trailStart : na,
         trail_offset = useTrail ? close * trailDist : na)

// Close all positions during exit period
if exitPeriod
    strategy.close_all("Daily Exit")

// Track consecutive losing days
var float dailyProfit = 0
if ta.change(time("D"))
    if dailyProfit < 0
        consecutiveLosses += 1
    else
        consecutiveLosses := 0
    dailyProfit := 0

if strategy.closedtrades > 0
    dailyProfit += strategy.closedtrades.profit(strategy.closedtrades - 1)

if consecutiveLosses >= maxLosingDays
    strategy.close_all("Max Losing Days Reached")

if drawdownBreached
    strategy.close_all("Drawdown Limit Reached")
    
if isNewsTime()
    strategy.close_all("News Window")
// }

Overview

Boilerplate Configurable Strategy [Yosiet] filters trades by weekday, session, date range, and an optional news window, and can restrict direction or invert the side. Risk settings include a percentage loss cap, consecutive losing-day and drawdown limits, plus ATR or static reward targets and an optional trailing stop. It draws on the price chart. The provided excerpt does not show completed exit orders.

Details

Published by

pegaltier on GitHub

Code credit

yosietserga, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Moving averages, Sessions & time

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.

Topics

androidangularcleancodecryptogitseostartupwebdesignjavaergonomics

Settings

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

SettingTypeDefaultVariable
Strategy TypestringSQUEEZEstrategyType
Lengthint20length
Wide BB Multiplierfloat1.5mult1
Narrow BB Multiplierfloat2.0mult2
MondaybooltrueenableMon
TuesdaybooltrueenableTue
WednesdaybooltrueenableWed
ThursdaybooltrueenableThu
FridaybooltrueenableFri
SaturdaybooltrueenableSat
SundaybooltrueenableSun
Trading Session (HHmm-HHmm)string0000-0000sessionInput
Show all 30 settings
SettingTypeDefaultVariable
Daily Exit Timesession1600-1700exitTime
Start Datetimetimestamp("1 Jan 2024")startDate
End Datetimetimestamp("31 Jan 2025")endDate
Enable News FilterboolfalseenableNewsFilter
News Time (UTC)timetimestamp("2023-01-01 14:30")newsTime
News Window (minutes)int5newsWindow
Trade DirectionstringBothtradeDirection
Inverse Trade SideboolfalsetradeInverse
Max Loss per Trade (%)float2.0maxLossPerc
Max Consecutive Losing Daysint3maxLosingDays
Max Drawdown (%)float10.0maxDD
RR ModestringATRrrMode
ATR Lengthint14atrLength
ATR Multiplierfloat1.5atrMultiplier
Static RR Ratiofloat2.0staticRR
Enable Trailing StopboolfalseuseTrail
Trail Activation (%)float15trailStart
Trail Distance (%)float0.5trailDist
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

4 stars

This strategy trades directional momentum breakouts for crude oil on the price chart. It enters long or short positions when a fast exponential moving average crosses a slow exponential moving average, provided that current Average True Range exceeds its movin

Strategy v6 TrendMoving averages
Updated 2 months ago · MIT GitHub repository of CL Crude Oil Momentum [trugurpala]
3 stars

This strategy plots Bollinger bands and a simple moving average on the price chart. It opens a short when price crosses above the upper band while below the average, and a long when price crosses below the lower band while above the average. Entries are allowe

Strategy v5 Volatility & bandsMoving averages
Updated 2 years ago · None stated GitHub repository of 周末布林带策略

Session Wicks

by g-moe
3 stars

This strategy executes long and short trades on the price chart by combining multi-timeframe smoothed Heikin-Ashi trends, higher-timeframe Hull Moving Average variations, and an ATR-based trailing stop. Users can adjust timeframes, smoothing lengths, Hull form

Strategy v5 TrendMoving averages Repaints
Updated 5 months ago · None stated GitHub repository of Session Wicks

3Commas Bot

by regalouisei
2 stars

This strategy draws two moving averages on the price chart and uses their bias to open long or short trades. It places the stop beyond a swing high or low using an ATR risk multiple, then sets a limit exit from the reward-to-risk ratio. An optional ATR trail c

Strategy v5 TrendMoving averages
Updated 8 months ago · None stated GitHub repository of 3Commas Bot
2 stars

Gold Multi-TF NYSE Scalper v2 is an intraday trading strategy for XAUUSD that seeks momentum entries by aligning RSI and EMA bias across multiple timeframes. It filters trades using an optional NYSE session clock and an ATR volatility spike check. Entries exit

Strategy v6 Oscillators & momentumVolatility & bands
Updated 7 days ago · None stated GitHub repository of Gold Multi-TF NYSE Scalper v2

ORB Hunter

by nxtaiapp
2 stars

ORB Hunter is an Opening Range Breakout strategy that identifies price breakouts beyond a defined opening session window (such as 09:30 to 09:45 EST). It places long or short trades when price crosses the opening range bounds with buffer, confirmed by optional

Strategy v5 BreakoutSessions & time
Updated 11 months ago · MIT GitHub repository of ORB Hunter

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