Strategy · Pine Script v4 · On the chart

StrategyNameHere - BuildABot-DRR

by myn

This script provides a standardized template for building and testing trading strategies in Pine Script v4.

View on GitHub

GitHub stars4on the repository
Pine versionv4older, still runs
Lines of code304
Settings28inputs
LicenceApache-2.0
Last update6 years ago15 Apr 2020

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

304 lines of Pine Script v4 from RiskManagement-TradingView-Strategy-Template-BuildABot-v4.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

RiskManagement-TradingView-Strategy-Template-BuildABot-v4.pine
//@version=4
strategy("StrategyNameHere [Strategy] - BuildABot-DRR", precision=6, overlay=true, pyramiding=0, initial_capital=20000, currency="USD", default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_value=0.075)
// study("StrategyNameHere [Study] - BuildABot-DRR", overlay=true)


/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////



//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////

longLogic = false
shortLogic = false

longCondClose = false
shortCondClose = false

///////////////////////////////////////////////
//* Backtesting Period Selector | Component *//
///////////////////////////////////////////////

//* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-Component *//
//* https://www.tradingview.com/u/pbergden/ *//
//* Modifications made *//
timePeriodDivider = input(false,"░░░░░░░░░░░░░░░░░░░░░░░░░")
testStartYear = input(2019, "Backtest Start Year") 
testStartMonth = input(1, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)

testStopYear = input(77777777, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(31, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)

testPeriod() =>
    time >= testPeriodStart and time <= testPeriodStop ? true : false


//////////////////////////
//* Strategy Component *//
//////////////////////////
longShortFlipDivider = input(false, "░░░░░░░░░░░░░░░░░░░░░░░░░")
isLong = input(false, "Longs Only")
isShort = input(false, "Shorts Only")
isFlip = input(false, "Flip the Opens")

long = longLogic
short = shortLogic

if isFlip
    long := shortLogic
    short := longLogic
    short
else
    long := longLogic
    short := shortLogic
    short

if isLong
    long := long
    short := na
    short

if isShort
    long := na
    short := short
    short

////////////////////////////////
//======[ Signal Count ]======//
////////////////////////////////

sectionLongs = 0
sectionLongs := nz(sectionLongs[1])
sectionShorts = 0
sectionShorts := nz(sectionShorts[1])

if long
    sectionLongs := sectionLongs + 1
    sectionShorts := 0
    sectionShorts

if short
    sectionLongs := 0
    sectionShorts := sectionShorts + 1
    sectionShorts

//////////////////////////////
//======[ Pyramiding ]======//
//////////////////////////////
pyramidingDivider = input(false, "░░░░░░░░░░░░░░░░░░░░░░░░░")
pyrl = input(1, "Pyramiding less than")  // If your count is less than this number
pyre = input(0, "Pyramiding equal to")  // If your count is equal to this number
pyrg = input(1000000, "Pyramiding greater than")  // If your count is greater than this number

longCondition = long and sectionLongs <= pyrl or long and sectionLongs >= pyrg or 
   long and sectionLongs == pyre ? 1 : 0
shortCondition = short and sectionShorts <= pyrl or short and sectionShorts >= pyrg or 
   short and sectionShorts == pyre ? 1 : 0

////////////////////////////////
//======[ Entry Prices ]======//
////////////////////////////////

last_open_longCondition = float(na)
last_open_shortCondition = float(na)
last_open_longCondition := longCondition ? close : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition ? close : nz(last_open_shortCondition[1])

////////////////////////////////////
//======[ Open Order Count ]======//
////////////////////////////////////

sectionLongConditions = 0
sectionLongConditions := nz(sectionLongConditions[1])
sectionShortConditions = 0
sectionShortConditions := nz(sectionShortConditions[1])

if longCondition
    sectionLongConditions := sectionLongConditions + 1
    sectionShortConditions := 0
    sectionShortConditions

if shortCondition
    sectionLongConditions := 0
    sectionShortConditions := sectionShortConditions + 1
    sectionShortConditions

///////////////////////////////////////////////
//======[ Position Check (long/short) ]======//
///////////////////////////////////////////////

last_longCondition = float(na)
last_shortCondition = float(na)
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])

in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition

/////////////////////////////////////
//======[ Position Averages ]======//
/////////////////////////////////////

totalLongs = 0.0
totalLongs := nz(totalLongs[1])
totalShorts = 0.0
totalShorts := nz(totalShorts[1])
averageLongs = 0.0
averageLongs := nz(averageLongs[1])
averageShorts = 0.0
averageShorts := nz(averageShorts[1])

if longCondition
    totalLongs := totalLongs + last_open_longCondition
    totalShorts := 0.0
    totalShorts

if shortCondition
    totalLongs := 0.0
    totalShorts := totalShorts + last_open_shortCondition
    totalShorts

averageLongs := totalLongs / sectionLongConditions
averageShorts := totalShorts / sectionShortConditions

/////////////////////////////////
//======[ Trailing Stop ]======//
/////////////////////////////////

trailingStopDivider = input(false, "░░░░░░░░░░░░░░░░░░░░░░░░░")
isTS = input(false, "Trailing Stop")
tsi = input(1, "Activate Trailing Stop Price (%)", type=input.float, step=0.10)
ts = input(1, "Trailing Stop (%)", type=input.float, step=0.10)

last_high = float(na)
last_low = float(na)
last_high_short = float(na)
last_low_short = float(na)
last_high := not in_longCondition ? na : 
   in_longCondition and (na(last_high[1]) or high > nz(last_high[1])) ? high : 
   nz(last_high[1])
last_high_short := not in_shortCondition ? na : 
   in_shortCondition and (na(last_high[1]) or high > nz(last_high[1])) ? high : 
   nz(last_high[1])
last_low := not in_shortCondition ? na : 
   in_shortCondition and (na(last_low[1]) or low < nz(last_low[1])) ? low : 
   nz(last_low[1])
last_low_short := not in_longCondition ? na : 
   in_longCondition and (na(last_low[1]) or low < nz(last_low[1])) ? low : 
   nz(last_low[1])

long_ts = isTS and not na(last_high) and low <= last_high - last_high / 100 * ts and 
   longCondition == 0 and last_high >= averageLongs + averageLongs / 100 * tsi
short_ts = isTS and not na(last_low) and high >= last_low + last_low / 100 * ts and 
   shortCondition == 0 and last_low <= averageShorts - averageShorts / 100 * tsi

///////////////////////////////
//======[ Take Profit ]======//
///////////////////////////////

takeProfitDivider = input(false, "░░░░░░░░░░░░░░░░░░░░░░░░░")
isTP = input(false, "Take Profit")
tp = input(1.25, "Take Profit (%)", type=input.float, step=0.10)
long_tp = isTP and close > averageLongs + averageLongs / 100 * tp and not longCondition
short_tp = isTP and close < averageShorts - averageShorts / 100 * tp and not shortCondition

/////////////////////////////
//======[ Stop Loss ]======//
/////////////////////////////

stopLossDivider = input(false, "░░░░░░░░░░░░░░░░░░░░░░░░░")
isSL = input(false, "Stop Loss")
sl = input(1.4, "Stop Loss (%)", type=input.float, step=0.10)
long_sl = isSL and close < averageLongs - averageLongs / 100 * sl and longCondition == 0
short_sl = isSL and close > averageShorts + averageShorts / 100 * sl and 
   shortCondition == 0

//////////////////////////////////////
//======[ Conditional Closes ]======//
/////////////////////////////////////
conditionalClosesDivider = input(false, "░░░░░░░░░░░░░░░░░░░░░░░░░")
isCLl = input(false, "Close Condition Long")
isCLs = input(false, "Close Condition Short")
long_cl = isCLl and longCondClose and in_longCondition == 1
short_cl = isCLs and shortCondClose and in_shortCondition == 1


/////////////////////////////////
//======[ Close Signals ]======//
/////////////////////////////////

longClose = long_tp or long_sl or long_ts or long_cl ? 1 : 0
shortClose = short_tp or short_sl or short_ts or short_cl ? 1 : 0

///////////////////////////////
//======[ Plot Colors ]======//
///////////////////////////////

longCloseCol = color(na)
shortCloseCol = color(na)
longCloseCol := long_tp ? color.purple : 
   long_sl ? color.maroon : long_ts ? color.blue : longCloseCol[1]
shortCloseCol := short_tp ? color.purple : 
   short_sl ? color.maroon : short_ts ? color.blue : shortCloseCol[1]
tpColor = isTP and in_longCondition ? color.purple : 
   isTP and in_shortCondition ? color.purple : color.white
slColor = isSL and in_longCondition ? color.red : 
   isSL and in_shortCondition ? color.red : color.white

//////////////////////////////////
//======[ Strategy Plots ]======//
//////////////////////////////////

plot(isTS and in_longCondition ? averageLongs + averageLongs / 100 * tsi : na, "Long Trailing Activate", color.blue, style=3, linewidth=2)
plot(isTS and in_longCondition and last_high >= averageLongs + averageLongs / 100 * tsi ? last_high - last_high / 100 * ts : na, "Long Trailing", color.fuchsia, style=2, linewidth=3)
plot(isTS and in_shortCondition ? averageShorts - averageShorts / 100 * tsi : na, "Short Trailing Activate", color.blue, style=3, linewidth=2)
plot(isTS and in_shortCondition and last_low <= averageShorts - averageShorts / 100 * tsi ? last_low + last_low / 100 * ts : na, "Short Trailing", color.fuchsia, style=2, linewidth=3)
plot(isTP and in_longCondition and last_high < averageLongs + averageLongs / 100 * tp ? averageLongs + averageLongs / 100 * tp : na, "Long TP", tpColor, style=3, linewidth=2)
plot(isTP and in_shortCondition and last_low > averageShorts - averageShorts / 100 * tp ? averageShorts - averageShorts / 100 * tp : na, "Short TP", tpColor, style=3, linewidth=2)
plot(isSL and in_longCondition and last_low_short > averageLongs - averageLongs / 100 * sl ? averageLongs - averageLongs / 100 * sl : na, "Long SL", slColor, style=3, linewidth=2)
plot(isSL and in_shortCondition and last_high_short < averageShorts + averageShorts / 100 * sl ? averageShorts + averageShorts / 100 * sl : na, "Short SL", slColor, style=3, linewidth=2)

///////////////////////////////
//======[ Alert Plots ]======//
///////////////////////////////

// plot(longCondition, "Long", green)
// plot(shortCondition, "Short", red)
// plot(longClose, "Long Close", longCloseCol)
// plot(shortClose, "Short Close", shortCloseCol)

///////////////////////////////////
//======[ Reset Variables ]======//
///////////////////////////////////

if longClose or not in_longCondition
    averageLongs := 0
    totalLongs := 0.0
    sectionLongs := 0
    sectionLongConditions := 0
    sectionLongConditions

if shortClose or not in_shortCondition
    averageShorts := 0
    totalShorts := 0.0
    sectionShorts := 0
    sectionShortConditions := 0
    sectionShortConditions

////////////////////////////////////////////
//======[ Strategy Entry and Exits ]======//
////////////////////////////////////////////

if testPeriod()
    strategy.entry("Long", 1, when=longCondition)
    strategy.entry("Short", 0, when=shortCondition)
    strategy.close("Long", when=longClose)
    strategy.close("Short", when=shortClose)

Overview

StrategyNameHere - BuildABot-DRR includes built-in risk management modules such as backtest date filtering, trade direction toggles (long-only, short-only, or flipped), signal-count pyramiding rules, and percentage-based stop loss, take profit, and trailing stop exits. Plotted on the main price chart, it acts as a foundation where custom entry and exit logic can be inserted.

Details

Published by

myn on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
░░░░░░░░░░░░░░░░░░░░░░░░░boolfalsetimePeriodDivider
Backtest Start Yearint2019testStartYear
Backtest Start Monthint1testStartMonth
Backtest Start Dayint1testStartDay
Backtest Stop Yearint77777777testStopYear
Backtest Stop Monthint12testStopMonth
Backtest Stop Dayint31testStopDay
░░░░░░░░░░░░░░░░░░░░░░░░░boolfalselongShortFlipDivider
Longs OnlyboolfalseisLong
Shorts OnlyboolfalseisShort
Flip the OpensboolfalseisFlip
░░░░░░░░░░░░░░░░░░░░░░░░░boolfalsepyramidingDivider
Show all 28 settings
SettingTypeDefaultVariable
Pyramiding less thanint1pyrl
Pyramiding equal toint0pyre
Pyramiding greater thanint1000000pyrg
░░░░░░░░░░░░░░░░░░░░░░░░░boolfalsetrailingStopDivider
Trailing StopboolfalseisTS
Activate Trailing Stop Price (%)float1tsi
Trailing Stop (%)float1ts
░░░░░░░░░░░░░░░░░░░░░░░░░boolfalsetakeProfitDivider
Take ProfitboolfalseisTP
Take Profit (%)float1.25tp
░░░░░░░░░░░░░░░░░░░░░░░░░boolfalsestopLossDivider
Stop LossboolfalseisSL
Stop Loss (%)float1.4sl
░░░░░░░░░░░░░░░░░░░░░░░░░boolfalseconditionalClosesDivider
Close Condition LongboolfalseisCLl
Close Condition ShortboolfalseisCLs
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

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA
440 stars

This script is an empty strategy template for Pine Script developers. It declares a version 4 strategy named Basic Strategy Boilerplate with the short title Strategy Boilerplate and sets overlay to true so any future plots would appear on the price chart. It d

Strategy v4
Updated 7 years ago · GPL-3.0 GitHub repository of Basic Strategy Boilerplate

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated today · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy

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]

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