Strategy · Pine Script v4 · On the chart

Strategy Long Template

by krosenfeld7

This long-only strategy template provides boilerplate logic for building custom Pine Script trading systems on the price chart.

View on GitHub

GitHub stars5on the repository
Pine versionv4older, still runs
Lines of code98
Settings9inputs
LicenceApache-2.0
Last update3 years ago12 May 2023

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

98 lines of Pine Script v4 from Strategy_Long_Template.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

Strategy_Long_Template.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © krosenfeld7

//@version=4
strategy("Strategy Long Template", overlay = true, pyramiding = 0, 
         margin_long = 100, margin_short = 100, 
         default_qty_type = strategy.percent_of_equity, 
         default_qty_value = 20, initial_capital = 2000, 
         process_orders_on_close = true)

// Set the starting point for backtesting
start = input(title = "Backtesting Start", type = input.time,
     defval = timestamp("1 Jan 2015"))
maxTimeOpen = input(title = "Order Expiration", type = input.integer,
     defval = 100, minval = 1)
tpSlStrategy = input(title = "Take Profit Strategy", type = input.string,
     defval = "Percent", options = ["Percent", "ATR"])
trailingStop = input(title = "Trailing Stop", type = input.string,
     defval = "Fixed", options = ["Fixed", "Trail"])

// ATR For Stop Loss
atrLength = input(title = "ATR SL Length", defval = 14,
     minval = 1)
atrMultiplier = input(title = "ATR Multiplier", type = input.float, 
     defval = 1, minval = 0.1)
riskLevel = input(title = "Risk Level", type = input.float, 
     defval = 1, minval = 0.1)

longProfitPercent = input(title = "Take Profit %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100
longLossPercent = input(title = "Stop Loss %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100

// Algorithm / Strategy Goes here
// Set long variables to execute positions below
long = 0


// End Algorithm

longExitPrice = 0.0
longStopPrice = 0.0

// Calculating exact prices for stop loss and exit prices
longExitPercentPrice = strategy.position_avg_price * (1 + 
     (longProfitPercent * riskLevel))
longStopPercentPrice = strategy.position_avg_price * (1 - 
     longLossPercent)

// Profit & Loss via ATR
atr = atr(atrLength)

atr := valuewhen(strategy.position_size == 0, atr, 0)

longExitAtrPrice = strategy.position_avg_price + (atr * 
     atrMultiplier * riskLevel)
longStopAtrPrice = strategy.position_avg_price - (atr * 
     atrMultiplier)

if tpSlStrategy == "Percent"
    longExitPrice := longExitPercentPrice
    
    if trailingStop == "Fixed"
        longStopPrice := longStopPercentPrice
    else if trailingStop == "Trail"
        stopValue      = close * (1 - longLossPercent)
        longStopPrice := (strategy.position_size > 0) ? 
             max(stopValue, longStopPrice[1]) : 0

else if tpSlStrategy == "ATR"
    if strategy.position_size > 0
        longExitPrice := longExitAtrPrice
        
    if trailingStop == "Fixed"
        longStopPrice := longStopAtrPrice
    else if trailingStop == "Trail"
        stopValue      = close - (atr * atrMultiplier)
        longStopPrice := (strategy.position_size > 0) ? 
             max(stopValue, longStopPrice[1]) : 0

// Plotting profit / loss targets
plot(series = (strategy.position_size > 0) ? longExitPrice : na, 
     color = color.green, style = plot.style_linebr, 
     linewidth = 3, title = "Long Target")
plot(series = (strategy.position_size > 0) ? longStopPrice : na, 
     color = color.red, style = plot.style_linebr, 
     linewidth = 3, title = "Long Stop Loss")

// Submit entry orders
if time >= start
    strategy.entry(id = "Long", long = strategy.long, 
         comment = "Long Open", when = long)

// Submit exit orders
strategy.exit(id = "Long", limit = longExitPrice, stop = longStopPrice, 
     comment = "Long Close", when = strategy.position_size > 0)
strategy.close(id = "Long", comment = "Expired: >" + tostring(maxTimeOpen), 
     when = (barssince(change(strategy.opentrades)) + 1) >= maxTimeOpen)

Overview

Strategy Long Template features built-in risk management that calculates target exits and stop-loss levels using either percentage-based distances or Average True Range (ATR) calculations. Traders can toggle between fixed and trailing stop-loss options and adjust risk multipliers. Visual lines plot target and stop-loss prices during active positions. The strategy relies on placeholder logic for entry signals, requiring custom entry conditions to be added.

Details

Published by

krosenfeld7 on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Volatility & bands

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
Backtesting Starttimetimestamp("1 Jan 2015")start
Order Expirationint100maxTimeOpen
Take Profit StrategystringPercenttpSlStrategy
Trailing StopstringFixedtrailingStop
ATR SL Lengthint14atrLength
ATR Multiplierfloat1atrMultiplier
Risk Levelfloat1riskLevel
Take Profit %float10longProfitPercent
Stop Loss %float10longLossPercent
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

Alert BB + RSI [Alorse] is a multi-symbol mean-reversion strategy designed for cryptocurrency trading. It evaluates Bollinger Bands and the Relative Strength Index (RSI) across up to 20 user-defined ticker symbols simultaneously. The strategy enters long posit

Strategy v4 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Alert BB + RSI [Alorse]

This overlay strategy offers two selectable entry modes: a Bollinger squeeze on typical price and a simple moving-average cross. It filters trades by weekday, session, date range, and an optional news window, and can restrict direction or invert the side. Risk

Strategy v5 Volatility & bandsMoving averages
Updated today · None stated GitHub repository of Boilerplate Configurable Strategy [Yosiet]
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

STRG-BBForce

by harryguiacorn
219 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce
218 stars

This strategy detects price breakouts above rolling highest highs or below lowest lows over a customizable lookback period. It includes optional volume spike and ATR volatility threshold filters, along with bar confirmation rules. Positions are taken upon conf

Strategy v6 BreakoutVolatility & bands
Updated 3 months ago · None stated GitHub repository of Breakout Strategy Template

Bollinger Breakout

by hackingthemarkets
189 stars

This price-chart strategy plots a simple moving average and upper and lower bands built from the standard deviation of close, scaled by separate offset inputs. It enters a fixed quantity long when close crosses above the upper band and a fixed quantity short w

Strategy v4 Volatility & bandsBreakout
Updated 3 years ago · None stated GitHub repository of Bollinger Breakout

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